front/src/views/wechat/bind/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

376 lines
11 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.bind.goLogin') }}
</button>
<LoginLangToggle />
</div>
<div v-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.authBindGateTitle') }}</h2>
<p class="wechat-h5-hint">{{ t('wechat.common.authBindGateTip') }}</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.bind.goLogin') }}</a-button>
</div>
</div>
<div v-else-if="statusCode === 'oauth-error'" class="wechat-h5-state">
<a-result status="error" :title="t('wechat.bind.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.bind.goLogin') }}</a-button>
</div>
</div>
<div v-else-if="statusCode === 'already-bound'" class="wechat-h5-state">
<a-result status="warning" :title="t('wechat.bind.alreadyBound')" />
<div class="wechat-h5-state-actions">
<a-button type="primary" long @click="goLogin">{{ t('wechat.bind.goLogin') }}</a-button>
<a-button long @click="goCustomerCenter">{{ t('wechat.bind.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.bind.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.bind.wxUser') }}
</h2>
<p class="wechat-h5-hero__tip">{{ t('wechat.bind.wxReady') }}</p>
</section>
<section class="wechat-h5-card">
<div class="wechat-h5-header">
<h1 class="wechat-h5-title">{{ t('wechat.bind.title') }}</h1>
<p class="wechat-h5-subtitle">{{ t('wechat.bind.subtitle') }}</p>
</div>
<a-form
ref="formRef"
class="wechat-h5-form"
:model="formState"
:rules="formRules"
layout="vertical"
>
<a-form-item field="account" :label="t('wechat.bind.account')" required>
<a-input
v-model="formState.account"
size="large"
:placeholder="t('wechat.bind.accountPlaceholder')"
allow-clear
autocomplete="username"
/>
</a-form-item>
<a-form-item field="password" :label="t('wechat.bind.password')" required>
<a-input-password
v-model="formState.password"
size="large"
:placeholder="t('wechat.bind.passwordPlaceholder')"
allow-clear
autocomplete="current-password"
/>
</a-form-item>
<a-button
type="primary"
long
size="large"
:loading="submitting"
class="wechat-h5-submit"
@click="handleSubmit"
>
{{ submitting ? t('wechat.bind.submitting') : t('wechat.bind.submit') }}
</a-button>
</a-form>
<p class="wechat-h5-hint">{{ t('wechat.bind.hint') }}</p>
<p class="wechat-h5-switch">
{{ t('wechat.bind.noAccount') }}
<button type="button" @click="goRegister">{{ t('wechat.bind.goRegister') }}</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.bind.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 {
bindByWechat,
getOAuthUserInfo,
type WeChatOAuthUserInfo,
} from '@/api/wechat';
import { handleApiError } from '@/utils/rbac-error-handler';
import { redirectToWeChatOAuth } from '@/utils/wechatOAuth';
import { loginCustomerAfterWechatAuth } from '@/utils/wechatAuthLogin';
import { isTimeoutError, withTimeout } from '@/utils/withTimeout';
import { hideWeChatBrowserNav, isWeChatBrowser } from '@/utils/device';
import { markH5FollowPromptPending } from '@/utils/h5FollowPrompt';
import LoginLangToggle from '@/views/login/components/LoginLangToggle.vue';
defineOptions({ name: 'WechatBind' });
type PageStatus = 'loading' | 'ready' | 'oauth-error' | 'already-bound' | '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 goRegister() {
if (isWeChatBrowser()) {
void redirectToWeChatOAuth('register').catch(() => {
router.replace('/wechat/register');
});
return;
}
router.replace('/wechat/register');
}
function startOAuth() {
authModalVisible.value = false;
void redirectToWeChatOAuth('bind');
}
function retryOAuth() {
startOAuth();
}
function retryLoad() {
const code = route.query.code;
if (typeof code === 'string' && code) {
void loadOAuthUserInfo(code);
return;
}
startOAuth();
}
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);
let loadingSlowTimer: number | undefined;
const formState = reactive({
account: '',
password: '',
});
const avatarLetter = computed(() => {
const name = wxUserInfo.value?.nickname || 'W';
return name.trim().charAt(0).toUpperCase();
});
const formRules: Record<string, FieldRule | FieldRule[]> = {
account: [{ required: true, message: t('wechat.bind.accountPlaceholder') }],
password: [{ required: true, message: t('wechat.bind.passwordPlaceholder') }],
};
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 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;
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;
submitting.value = true;
try {
await bindByWechat({
account: formState.account.trim(),
password: formState.password,
wechat: {
openid: wxUserInfo.value.openid,
nickname: wxUserInfo.value.nickname,
avatar: wxUserInfo.value.headimgurl,
unionid: wxUserInfo.value.unionid,
},
});
Message.success(t('wechat.bind.success'));
const loggedIn = await loginCustomerAfterWechatAuth({
account: formState.account.trim(),
password: formState.password,
skipRedirect: true,
});
markH5FollowPromptPending();
if (loggedIn) {
goCustomerCenter();
return;
}
goLogin();
} catch (error) {
handleApiError(error);
} finally {
submitting.value = false;
}
}
onMounted(() => {
hideWeChatBrowserNav();
loadingHint.value = t('wechat.common.loading');
const code = route.query.code;
if (typeof code !== 'string' || !code) {
if (!isWeChatBrowser()) {
statusCode.value = 'need-auth';
return;
}
statusCode.value = 'need-auth';
startOAuth();
return;
}
void loadOAuthUserInfo(code);
});
onBeforeUnmount(() => {
clearLoadingTimers();
});
</script>
<style lang="less" scoped>
@import '../styles/wechat-h5.less';
.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>