Files
kangyuan-mobile/utils/qrScanner.js
T

154 lines
4.0 KiB
JavaScript

function isH5Runtime() {
return typeof window !== 'undefined' && typeof document !== 'undefined';
}
function toast(text) {
uni.showToast({ title: text, icon: 'none' });
}
export function extractInviteCode(text) {
const raw = String(text || '').trim();
if (!raw) return '';
try {
const url = new URL(raw);
const params = url.searchParams;
return (
params.get('inviteCode') ||
params.get('code') ||
params.get('invite') ||
params.get('shareId') ||
params.get('bindUserId') ||
''
);
} catch (e) {}
const m = raw.match(/[?&](inviteCode|code|invite|shareId|bindUserId)=([^&#]+)/i);
if (m?.[2]) {
try {
return decodeURIComponent(m[2]);
} catch (e) {
return m[2];
}
}
return raw;
}
function scanFromCamera({ scanType = ['qrCode'] } = {}) {
return new Promise((resolve) => {
uni.scanCode({
onlyFromCamera: false,
scanType,
success: (res) => resolve(String(res?.result || '')),
fail: (err) => resolve(err?.errMsg === 'scanCode:fail cancel' ? '' : ''),
});
});
}
function pickSingleImageFileH5() {
return new Promise((resolve) => {
if (!isH5Runtime()) {
resolve(null);
return;
}
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = () => resolve((input.files && input.files[0]) || null);
input.click();
});
}
async function barcodeDetectQrFromFileH5(file) {
if (!file) return '';
if (!isH5Runtime()) return '';
const Detector = window.BarcodeDetector;
if (!Detector) return '';
try {
const detector = new Detector({ formats: ['qr_code'] });
if (window.createImageBitmap) {
const bitmap = await window.createImageBitmap(file);
const codes = await detector.detect(bitmap);
return String(codes?.[0]?.rawValue || '');
}
const img = new Image();
const url = URL.createObjectURL(file);
const text = await new Promise((resolve) => {
img.onload = async () => {
try {
const codes = await detector.detect(img);
resolve(String(codes?.[0]?.rawValue || ''));
} catch (e) {
resolve('');
} finally {
URL.revokeObjectURL(url);
}
};
img.onerror = () => {
URL.revokeObjectURL(url);
resolve('');
};
img.src = url;
});
return text;
} catch (e) {
return '';
}
}
export async function scanQrCode({
scanType = ['qrCode'],
allowCamera = true,
allowAlbum = true,
toastOnError = true,
} = {}) {
if (!isH5Runtime()) {
const raw = await scanFromCamera({ scanType });
if (!raw && toastOnError) toast('扫码失败');
return raw;
}
if (allowAlbum && !allowCamera) {
const file = await pickSingleImageFileH5();
if (!file) return '';
const raw = await barcodeDetectQrFromFileH5(file);
if (!raw && toastOnError) toast('当前浏览器不支持图片识别');
return raw;
}
if (!allowAlbum && allowCamera) {
const raw = await scanFromCamera({ scanType });
if (!raw && toastOnError) toast('扫码失败');
return raw;
}
const action = await new Promise((resolve) => {
uni.showActionSheet({
itemList: ['相机扫码', '相册识别'],
success: (res) => resolve(res?.tapIndex),
fail: () => resolve(-1),
});
});
if (action === 0) {
const raw = await scanFromCamera({ scanType });
if (!raw && toastOnError) toast('扫码失败');
return raw;
}
if (action === 1) {
const file = await pickSingleImageFileH5();
if (!file) return '';
const raw = await barcodeDetectQrFromFileH5(file);
if (!raw && toastOnError) toast('当前浏览器不支持图片识别,请用相机扫码');
return raw;
}
return '';
}
export async function scanInviteCode({ toastOnError = true, allowCamera = true, allowAlbum = true } = {}) {
const raw = await scanQrCode({ toastOnError, allowCamera, allowAlbum });
const code = extractInviteCode(raw);
if (!code && toastOnError) toast('未识别到邀请码');
return code;
}