index.vue 7.35 KB
<template>
    <div class="scan-livecode-page">
        <div v-if="!isWeChatOrWeCom.isWeChat" class="scan-only-tip">
            请使用微信扫码打开
        </div>

        <div v-else-if="phase === 'error' && message" class="scan-card">
            {{ message }}
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";

import { exchangeOpenIdByCode, getScanLivecodeQrcode } from "@/api/modules/vehicle-message";
import { fetchConfig, getConfig } from "@/config/center";
import { closeToast, showLoadingToast, showToast } from "vant";

type Phase = "auth" | "done" | "error" | "init" | "loading";

const phase = ref<Phase>("init");
const message = ref("");
const wechatAppId = ref("");

const isWeChatOrWeCom = computed(() => {
	if (typeof navigator === "undefined") {
		return { isWeChat: false, isWeCom: false, ok: false };
	}
	const ua = navigator.userAgent.toLowerCase();
	const hasMicroMessenger = ua.includes("micromessenger");
	const hasWxWork = ua.includes("wxwork");
	const hasWv = ua.includes("wv");
	const isMobile = /mobile|android|iphone/i.test(ua);
	const hasWeixinJSBridge = typeof WeixinJSBridge !== "undefined";
	const hasWxObject = window.wx !== undefined;
	const hasWxContext = window.__wxjs_environment !== undefined;
	const hasRealWeChatFeature = hasWeixinJSBridge || hasWxObject || hasWxContext;
	const isWeCom = hasWxWork;
	const isWeChat = isMobile && hasMicroMessenger && !isWeCom && (hasWv || hasRealWeChatFeature);

	return {
		isWeChat,
		isWeCom,
		ok: isWeChat || isWeCom,
	};
});

function getFirstQueryValue(keys: string[]) {
	const url = new URL(window.location.href);
	for (const k of keys) {
		const v = url.searchParams.get(k);
		if (typeof v === "string" && v) return v;
	}
	return "";
}

function removeQueryKeys(urlText: string, keys: string[]) {
	const url = new URL(urlText);
	for (const k of keys) url.searchParams.delete(k);
	url.hash = "";
	return url.toString();
}

function replaceUrlQuery(next: (url: URL) => void) {
	try {
		const url = new URL(window.location.href);
		next(url);
		window.history.replaceState({}, document.title, url.toString());
	} catch {
		// ignore
	}
}

function resolveWeChatAppId() {
	const cfg = getConfig() as Record<string, unknown>;
	const candidates = ((cfg.ssoApiEnv as undefined | { codeWechatAppId?: string })?.codeWechatAppId ?? "") as string;
	wechatAppId.value = candidates;
	return candidates;
}

async function ensureWeChatAppId() {
	if (wechatAppId.value) return wechatAppId.value;
	const existing = resolveWeChatAppId();
	if (existing) return existing;
	await fetchConfig();
	return resolveWeChatAppId();
}

function buildWeChatOauthAuthorizeUrl(redirectUrl: string) {
	const base = "https://open.weixin.qq.com/connect/oauth2/authorize";
	const state = `venus_scan_${Date.now()}`;
	const u = new URL(base);
	const appId = wechatAppId.value || resolveWeChatAppId();
	if (!appId) return "";
	u.searchParams.set("appid", appId);
	u.searchParams.set("redirect_uri", redirectUrl);
	u.searchParams.set("response_type", "code");
	u.searchParams.set("scope", "snsapi_base");
	u.searchParams.set("state", state);
	return `${u.toString()}#wechat_redirect`;
}

async function exchangeCodeToOpenId(code: string) {
	try {
		const appId = await ensureWeChatAppId();
		showLoadingToast({ message: "加载中...", forbidClick: true, duration: 0 });
		const res = await exchangeOpenIdByCode({ code, appId, state: "snsapi_base" });
		closeToast();
		const anyRes = res as any;
		return String(anyRes?.openId ?? anyRes?.openid ?? anyRes?.data?.openId ?? anyRes?.data?.openid ?? "");
	} catch {
		return "";
	}
}

async function fetchQrByOpenId(params: {
	carConditionCode: string;
	exp: string;
	liveCode: string;
	nonce: string;
	openId: string;
	saUserId: string;
	signature: string;
}) {
	phase.value = "loading";
	message.value = "正在获取群二维码";
	try {
		showLoadingToast({ message: "加载中...", forbidClick: true, duration: 0 });
		const res = await getScanLivecodeQrcode({
			liveCode: params.liveCode,
			exp: params.exp,
			nonce: params.nonce,
			saUserId: params.saUserId,
			signature: params.signature,
			carConditionCode: params.carConditionCode,
			openid: params.openId,
		});
		closeToast();
		const { code, data, msg } = res as unknown as { code: number; data?: Record<string, unknown>; msg?: string };

		if (code !== 0) {
			phase.value = "error";
			message.value = msg || "";
			return showToast(msg);
		}
		// qrCodeUrl.value = String((data as any)?.qrCodeUrl || "");
		// 关闭当前页面打开https://work.weixin.qq.com/gm/daf0ecda6f29bc09fded8735f80ada3f
		window.location.replace(data?.qrCodeUrl);
		phase.value = "done";
		message.value = "";
	} catch (error: unknown) {
		phase.value = "error";
		const msg = error instanceof Error ? error.message : String(error);
		message.value = msg;
	}
}

async function loadQr() {
	const env = isWeChatOrWeCom.value;
	if (!env.isWeChat) {
		phase.value = "error";
		message.value = "请使用微信扫码打开";
		return;
	}

	await ensureWeChatAppId();

	const liveCode = getFirstQueryValue(["liveCode", "livecode"]);
	const signature = getFirstQueryValue(["signature"]);
	const exp = getFirstQueryValue(["exp"]);
	const nonce = getFirstQueryValue(["nonce"]);
	const saUserId = getFirstQueryValue(["saUserId", "sa_user_id"]);
	const carConditionCode = getFirstQueryValue(["carConditionCode", "car_condition_code"]);
	const code = getFirstQueryValue(["code"]);
	const openIdFromUrl = getFirstQueryValue(["openId", "openid"]);

	if (!liveCode || !signature || !exp || !nonce || !saUserId || !carConditionCode) {
		phase.value = "error";
		message.value = "链接参数不完整,请重新扫码进入";
		return;
	}

	if (openIdFromUrl) {
		await fetchQrByOpenId({
			openId: openIdFromUrl,
			liveCode,
			signature,
			exp,
			nonce,
			saUserId,
			carConditionCode,
		});
		return;
	}

	if (!code) {
		const backUrl = removeQueryKeys(window.location.href, ["openId", "openid", "code", "state"]);
		const oauthUrl = buildWeChatOauthAuthorizeUrl(backUrl);
		if (!oauthUrl) {
			phase.value = "error";
			message.value = "未配置公众号 appId";
			return;
		}
		phase.value = "auth";
		message.value = "";
		window.location.replace(oauthUrl);
		return;
	}

	phase.value = "loading";
	message.value = "";
	const openId = await exchangeCodeToOpenId(code);
	if (!openId) {
		phase.value = "error";
		message.value = "获取 openid 失败,请重新扫码进入";
		return;
	}
	replaceUrlQuery((url) => {
		url.searchParams.delete("code");
		url.searchParams.delete("state");
		url.searchParams.set("openId", openId);
	});
	await fetchQrByOpenId({
		openId,
		liveCode,
		signature,
		exp,
		nonce,
		saUserId,
		carConditionCode,
	});
}

onMounted(() => {
	void loadQr();
});
</script>

<style lang="scss" scoped>
.scan-livecode-page {
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: center;
	min-height: 100vh;
	padding: 16px;
	background: #f4f6f8;
}

.scan-only-tip {
	font-size: 16px;
	color: #666;
	text-align: center;
}

.scan-card {
	width: 100%;
	max-width: 520px;
	padding: 16px;
	text-align: center;
	border-radius: 12px;
}

.scan-result {
	display: flex;
	flex-direction: column;
	gap: 12px;
	align-items: center;
	padding: 12px 0 8px;
}

.scan-qrcode {
	width: 220px;
	height: 220px;
	pointer-events: auto;
	object-fit: cover;
	border-radius: 8px;
	-webkit-touch-callout: default;
}

.scan-message {
	font-size: 14px;
	color: #666;
	text-align: center;
}
</style>