index.vue
7.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<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>