98022b936f
Co-authored-by: Cursor <cursoragent@cursor.com>
52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
import { getRuntimePlatform } from './env';
|
|
import { ensureJssdkReady } from './jssdk';
|
|
import type { WeixinSdkConfig } from './types';
|
|
|
|
/** 调起扫码(返回二维码/条码内容,失败返回 null) */
|
|
export async function scanQrCode(config: WeixinSdkConfig): Promise<string | null> {
|
|
const platform = getRuntimePlatform();
|
|
|
|
if (platform === 'mini' && window.wx?.scanCode) {
|
|
return new Promise((resolve) => {
|
|
window.wx!.scanCode!({
|
|
onlyFromCamera: true,
|
|
scanType: ['qrCode', 'barCode'],
|
|
success: (res) => resolve(res.result || null),
|
|
fail: () => resolve(null),
|
|
});
|
|
});
|
|
}
|
|
|
|
if (platform === 'wechat-h5') {
|
|
await ensureJssdkReady({
|
|
apiBase: config.apiBase ?? '/api/v1',
|
|
clientApp: config.clientApp,
|
|
getAccessToken: config.getAccessToken,
|
|
});
|
|
if (!window.wx?.scanQRCode) {
|
|
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
|
}
|
|
return new Promise((resolve, reject) => {
|
|
window.wx!.scanQRCode!({
|
|
needResult: 1,
|
|
scanType: ['qrCode', 'barCode'],
|
|
success: (res) => resolve(res.resultStr || null),
|
|
fail: (res) => {
|
|
const msg = res.errMsg || '扫码失败';
|
|
if (/cancel/i.test(msg)) {
|
|
resolve(null);
|
|
return;
|
|
}
|
|
if (/permission|auth|denied|授权|拒绝|camera/i.test(msg)) {
|
|
reject(new Error('相机权限未开启,请在微信设置中允许使用摄像头'));
|
|
return;
|
|
}
|
|
reject(new Error(msg));
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
throw new Error('请在微信内打开以使用扫码核销');
|
|
}
|