front/src/views/wechat/register/index.vue
zzh 99088ad461
All checks were successful
Build and Deploy Front / deploy (push) Successful in 5m27s
fix: H5 微信 OAuth 从 wechat_mp 读取 AppId 与回调根
去掉写死 AppId,跳转前拉取 /wechat/mp/oauth-config,与公众号网页授权域名对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 09:17:14 +08:00

529 lines
16 KiB
Vue

<template>
<div class="wechat-h5-page">
<div class="wechat-h5-container">
<div class="wechat-h5-toolbar">
<button type="button" class="wechat-h5-back" @click="goLogin">
<icon-left :size="18" />
{{ t('wechat.register.goLogin') }}
</button>
<LoginLangToggle />
</div>
<div v-if="statusCode === 'open-in-wechat'" class="wechat-h5-state">
<a-result status="warning" :title="t('wechat.register.openInWechat')" />
<p class="wechat-h5-hint" style="text-align: center; margin-top: 8px">
{{ t('wechat.register.openInWechatTip') }}
</p>
<div v-if="inviteCode" class="wechat-h5-state-actions">
<a-button type="primary" long @click="copyInviteLink">
{{ t('wechat.register.copyInviteLink') }}
</a-button>
</div>
</div>
<div v-else-if="statusCode === 'need-auth'" class="wechat-h5-state wechat-h5-auth-gate">
<div class="wechat-h5-auth-gate__icon" aria-hidden="true">
<icon-user />
</div>
<h2 class="wechat-h5-auth-gate__title">{{ t('wechat.common.authGateTitle') }}</h2>
<p class="wechat-h5-hint">{{ t('wechat.common.authGateTip') }}</p>
<div class="wechat-h5-state-actions">
<a-button type="primary" long size="large" class="wechat-h5-submit" @click="startOAuth">
{{ t('wechat.common.authOk') }}
</a-button>
<a-button long @click="goLogin">{{ t('wechat.register.goLogin') }}</a-button>
</div>
</div>
<div v-else-if="statusCode === 'oauth-error'" class="wechat-h5-state">
<a-result status="error" :title="t('wechat.register.oauthError')" />
<div class="wechat-h5-state-actions">
<a-button type="primary" long @click="retryOAuth">{{ t('wechat.common.retry') }}</a-button>
<a-button long @click="goLogin">{{ t('wechat.register.goLogin') }}</a-button>
</div>
</div>
<div v-else-if="statusCode === 'already-bound'" class="wechat-h5-state">
<a-result
status="warning"
:title="t('wechat.register.alreadyBound')"
:subtitle="
inviteCode
? t('wechat.register.alreadyBoundInviteTip')
: t('wechat.register.alreadyBoundTip')
"
/>
<div class="wechat-h5-state-actions">
<a-button type="primary" long @click="goOAuthLogin">{{ t('wechat.register.goLogin') }}</a-button>
<a-button long @click="goCustomerCenter">{{ t('wechat.register.goCenter') }}</a-button>
</div>
</div>
<div v-else-if="statusCode === 'network-error'" class="wechat-h5-state">
<a-result
status="error"
:title="t('wechat.common.networkError')"
:subtitle="t('wechat.common.networkErrorTip')"
/>
<div class="wechat-h5-state-actions">
<a-button type="primary" long @click="retryLoad">{{ t('wechat.common.retryLoad') }}</a-button>
<a-button long @click="goLogin">{{ t('wechat.register.goLogin') }}</a-button>
</div>
</div>
<template v-else-if="statusCode === 'ready' && wxUserInfo">
<section class="wechat-h5-hero">
<img
v-if="wxUserInfo.headimgurl"
:src="wxUserInfo.headimgurl"
alt=""
class="wechat-h5-hero__avatar"
draggable="false"
@contextmenu.prevent
/>
<div v-else class="wechat-h5-hero__avatar wechat-h5-hero__fallback">
{{ avatarLetter }}
</div>
<h2 class="wechat-h5-hero__name">
{{ wxUserInfo.nickname || t('wechat.register.wxUser') }}
</h2>
</section>
<section class="wechat-h5-card">
<a-alert
v-if="referrerInfo"
type="success"
:show-icon="true"
class="wechat-h5-referrer"
>
{{
t('wechat.register.referrerHint', {
name: referrerInfo.name,
code: referrerInfo.code,
})
}}
</a-alert>
<a-alert
v-else-if="inviteCode && referrerValidated === false"
type="warning"
:show-icon="true"
class="wechat-h5-referrer"
>
{{ t('wechat.register.invalidRef') }}
</a-alert>
<a-form
ref="formRef"
class="wechat-h5-form"
:model="formState"
:rules="formRules"
layout="vertical"
>
<a-form-item
field="customerName"
:label="t('wechat.register.customerName')"
required
>
<a-input
v-model="formState.customerName"
size="large"
:placeholder="t('wechat.register.customerNamePlaceholder')"
allow-clear
/>
</a-form-item>
<a-form-item field="password" :label="t('wechat.register.password')" required>
<a-input-password
v-model="formState.password"
size="large"
:default-visibility="true"
:placeholder="t('wechat.register.passwordPlaceholder')"
allow-clear
/>
</a-form-item>
<p class="wechat-h5-pwd-tip">
{{ t('wechat.register.passwordTipPrefix') }}
<strong>{{ DEFAULT_CUSTOMER_PASSWORD }}</strong>
{{ t('wechat.register.passwordTipSuffix') }}
</p>
<a-button
type="primary"
long
size="large"
:loading="submitting"
class="wechat-h5-submit"
@click="handleSubmit"
>
{{ submitting ? t('wechat.register.submitting') : t('wechat.register.submit') }}
</a-button>
</a-form>
<p class="wechat-h5-switch">
{{ t('wechat.register.hasAccount') }}
<button type="button" @click="goBind">{{ t('wechat.register.goBind') }}</button>
</p>
</section>
</template>
<div v-else class="wechat-h5-loading">
<a-spin :size="32" />
<p class="wechat-h5-hint">{{ loadingHint }}</p>
</div>
</div>
<a-modal
v-model:visible="authModalVisible"
:title="t('wechat.common.authTitle')"
:ok-text="t('wechat.common.authOk')"
:cancel-text="t('wechat.common.authLater')"
:mask-closable="false"
:esc-to-close="false"
unmount-on-close
simple
@ok="startOAuth"
>
<p class="wechat-h5-auth-modal__desc">{{ t('wechat.common.authDesc') }}</p>
</a-modal>
</div>
</template>
<script lang="ts" setup>
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Message } from '@arco-design/web-vue';
import type { FormInstance, FieldRule } from '@arco-design/web-vue';
import { IconLeft, IconUser } from '@arco-design/web-vue/es/icon';
import {
getOAuthUserInfo,
registerByWechat,
type WeChatOAuthUserInfo,
} from '@/api/wechat';
import { validateInviteCode } from '@/api/marketing/portal';
import { handleApiError } from '@/utils/rbac-error-handler';
import {
DEFAULT_CUSTOMER_PASSWORD,
isLetterAndDigitPassword,
} from '@/utils/customerPassword';
import {
clearStashedWeChatInviteRef,
redirectToWeChatOAuth,
resolveWeChatInviteRef,
stashWeChatInviteRef,
} from '@/utils/wechatOAuth';
import {
clearStashedAdvisorInvite,
resolveAdvisorInvite,
stashAdvisorInvite,
} from '@/utils/advisorInviteStorage';
import { buildInviteRegisterUrl } from '@/utils/inviteLink';
import { isTimeoutError, withTimeout } from '@/utils/withTimeout';
import { isWeChatBrowser, hideWeChatBrowserNav } from '@/utils/device';
import { loginCustomerAfterWechatAuth } from '@/utils/wechatAuthLogin';
import { markH5FollowPromptPending } from '@/utils/h5FollowPrompt';
import LoginLangToggle from '@/views/login/components/LoginLangToggle.vue';
defineOptions({ name: 'WechatRegister' });
type PageStatus =
| 'loading'
| 'ready'
| 'oauth-error'
| 'already-bound'
| 'open-in-wechat'
| 'need-auth'
| 'network-error';
const OAUTH_LOAD_TIMEOUT_MS = 15000;
const LOADING_SLOW_HINT_MS = 3500;
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
function goCustomerCenter() {
router.replace('/h5/me');
}
function goLogin() {
if (isWeChatBrowser()) {
void redirectToWeChatOAuth('login', null, { afterLoginPath: '/h5/me' }).catch(() => {
router.replace('/h5/login');
});
return;
}
router.replace('/h5/login');
}
function goOAuthLogin() {
goLogin();
}
function goBind() {
if (isWeChatBrowser()) {
void redirectToWeChatOAuth('bind').catch(() => {
router.replace('/wechat/bind');
});
return;
}
router.replace('/wechat/bind');
}
function startOAuth() {
authModalVisible.value = false;
void redirectToWeChatOAuth('register', inviteCode.value);
}
function retryOAuth() {
startOAuth();
}
function retryLoad() {
const code = route.query.code;
if (typeof code === 'string' && code) {
void loadOAuthUserInfo(code);
return;
}
startOAuth();
}
async function copyInviteLink() {
const url = buildInviteRegisterUrl(inviteCode.value) || window.location.href;
try {
await navigator.clipboard.writeText(url);
Message.success(t('wechat.register.copyInviteSuccess'));
} catch {
Message.error(t('wechat.register.copyInviteFailed'));
}
}
const formRef = ref<FormInstance>();
const submitting = ref(false);
const statusCode = ref<PageStatus>('loading');
const loadingHint = ref('');
const authModalVisible = ref(false);
const wxUserInfo = ref<WeChatOAuthUserInfo | null>(null);
const inviteCode = ref('');
const advisorCode = ref('');
const referrerValidated = ref<boolean | null>(null);
const referrerInfo = ref<{ name: string; code: string } | null>(null);
let loadingSlowTimer: number | undefined;
const formState = reactive({
customerName: '',
password: DEFAULT_CUSTOMER_PASSWORD,
});
const avatarLetter = computed(() => {
const name = wxUserInfo.value?.nickname || formState.customerName || 'W';
return name.trim().charAt(0).toUpperCase();
});
const formRules: Record<string, FieldRule | FieldRule[]> = {
customerName: [{ required: true, message: t('wechat.register.customerNamePlaceholder') }],
password: [
{ required: true, message: t('wechat.register.passwordPlaceholder') },
{ minLength: 6, message: t('wechat.register.passwordMinLength') },
{
validator: (value: string, callback: (error?: string) => void) => {
if (!isLetterAndDigitPassword(value)) {
callback(t('wechat.register.passwordLetterAndDigit'));
} else {
callback();
}
},
},
],
};
function clearLoadingTimers() {
if (loadingSlowTimer != null) {
window.clearTimeout(loadingSlowTimer);
loadingSlowTimer = undefined;
}
}
function beginLoading() {
clearLoadingTimers();
statusCode.value = 'loading';
loadingHint.value = t('wechat.common.loading');
loadingSlowTimer = window.setTimeout(() => {
if (statusCode.value === 'loading') {
loadingHint.value = t('wechat.common.loadingSlow');
}
}, LOADING_SLOW_HINT_MS);
}
async function loadReferrer(code: string) {
inviteCode.value = code;
stashWeChatInviteRef(code);
try {
const data = (await withTimeout(
validateInviteCode(code) as Promise<Record<string, unknown>>,
OAUTH_LOAD_TIMEOUT_MS,
)) as Record<string, unknown>;
const valid = data.valid ?? data.Valid;
if (valid === false) {
referrerInfo.value = null;
referrerValidated.value = false;
return;
}
const name = String(
data.inviterNameMasked ?? data.InviterNameMasked ?? data.inviterCustomerCode ?? data.InviterCustomerCode ?? '',
);
const inviterCode = String(data.inviterCustomerCode ?? data.InviterCustomerCode ?? code);
if (!name && !inviterCode) {
referrerInfo.value = null;
referrerValidated.value = false;
return;
}
referrerInfo.value = { name: name || inviterCode, code: inviterCode };
referrerValidated.value = true;
} catch {
referrerInfo.value = null;
referrerValidated.value = false;
}
}
async function loadOAuthUserInfo(code: string) {
beginLoading();
try {
const info = await withTimeout(getOAuthUserInfo(code), OAUTH_LOAD_TIMEOUT_MS);
if (!info?.openid) {
statusCode.value = 'oauth-error';
return;
}
if (info.alreadyBound) {
statusCode.value = 'already-bound';
return;
}
wxUserInfo.value = info;
formState.customerName = info.nickname || '';
formState.password = DEFAULT_CUSTOMER_PASSWORD;
statusCode.value = 'ready';
} catch (error) {
if (isTimeoutError(error)) {
statusCode.value = 'network-error';
return;
}
handleApiError(error);
statusCode.value = 'network-error';
} finally {
clearLoadingTimers();
}
}
async function handleSubmit() {
if (!wxUserInfo.value?.openid || submitting.value) return;
const errors = await formRef.value?.validate();
if (errors) return;
const canBindInvite = Boolean(inviteCode.value && referrerValidated.value === true);
submitting.value = true;
try {
const result = await registerByWechat({
customerName: formState.customerName.trim(),
password: formState.password,
...(canBindInvite ? { inviteCode: inviteCode.value } : {}),
...(advisorCode.value ? { advisorCode: advisorCode.value } : {}),
wechat: {
openid: wxUserInfo.value.openid,
nickname: wxUserInfo.value.nickname,
avatar: wxUserInfo.value.headimgurl,
unionid: wxUserInfo.value.unionid,
},
});
clearStashedWeChatInviteRef();
clearStashedAdvisorInvite();
Message.success(t('wechat.register.success'));
const account = String(result?.customerCode || '').trim();
const loggedIn = account
? await loginCustomerAfterWechatAuth({
account,
password: formState.password,
skipRedirect: true,
})
: false;
markH5FollowPromptPending();
if (loggedIn) {
goCustomerCenter();
return;
}
goLogin();
} catch (error) {
handleApiError(error);
} finally {
submitting.value = false;
}
}
onMounted(() => {
hideWeChatBrowserNav();
loadingHint.value = t('wechat.common.loading');
const refCode = resolveWeChatInviteRef(route.query as Record<string, unknown>);
if (refCode) {
void loadReferrer(refCode);
}
const advisor = resolveAdvisorInvite(route.query as Record<string, unknown>);
if (advisor) {
advisorCode.value = advisor;
stashAdvisorInvite(advisor);
}
const code = route.query.code;
if (typeof code !== 'string' || !code) {
if (!isWeChatBrowser()) {
statusCode.value = 'open-in-wechat';
return;
}
// 微信内直接拉起授权,无需扫码 / 二次弹窗
statusCode.value = 'need-auth';
startOAuth();
return;
}
void loadOAuthUserInfo(code);
});
onBeforeUnmount(() => {
clearLoadingTimers();
});
</script>
<style lang="less" scoped>
@import '../styles/wechat-h5.less';
.wechat-h5-referrer {
margin-bottom: 16px;
}
.wechat-h5-auth-gate__icon {
width: 56px;
height: 56px;
margin: 0 auto 12px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
background: var(--app-primary-color);
font-size: 28px;
}
.wechat-h5-auth-gate__title {
margin: 0 0 6px;
font-size: 18px;
font-weight: 700;
color: #1d2129;
text-align: center;
}
.wechat-h5-auth-modal__desc {
margin: 0;
font-size: 14px;
line-height: 1.6;
color: #4e5969;
}
</style>