/** * 摄像头扫码 * * 需求: * - 侧键扫码继续走输入框,这里只处理摄像头 * - 仿照 ZL-MES-UNIAPP /pages/rollingScan 使用 uni.scanCode 打开摄像头扫码 * * 做法: * - 摄像头走 uni.scanCode * - 原有支付宝 mPaaS 原生插件(Mpaas-Scan-Module)方法已注释保留 */ function isAppPlus() { return typeof plus !== "undefined"; } function isCancelError(err) { if (!err) return false; if (err.cancelled) return true; if ( err.code === 8 || err.code === "8" || err.code === 10 || err.code === "10" ) return true; const msg = String( err.errMsg || err.message || err.resp_message || err || "", ); return /cancel|取消/i.test(msg); } export function normalizeScanText(raw) { if (raw == null) return ""; let text = String(raw); text = text.replace(/^/, ""); text = text.replace(/\u0000/g, ""); text = text.replace(/^[\r\n\u0003\u0004]+/, ""); text = text.replace(/[\r\n\u0003\u0004]+$/, ""); return text.trim(); } // ========== 以下为原有支付宝 mPaaS 原生插件扫码,已注释保留 ========== /* function scanByMpaas() { return new Promise((resolve, reject) => { try { const mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module"); if (!mpaasScanModule || typeof mpaasScanModule.mpaasScan !== "function") { reject(new Error("Mpaas-Scan-Module unavailable")); return; } mpaasScanModule.mpaasScan( { scanType: ["qrCode", "barCode"], hideAlbum: false, }, (ret) => { if (!ret) { reject(new Error("mpaas empty response")); return; } if (ret.resp_code === 1000) { resolve(normalizeScanText(ret.resp_result)); return; } reject({ code: ret.resp_code, message: ret.resp_message, cancelled: ret.resp_code === 10, }); }, ); } catch (err) { reject(err); } }); } */ export function scanByCamera() { return new Promise((resolve) => { const done = (text) => { const value = normalizeScanText(text); if (!value) { uni.showToast({ title: "扫码内容为空", icon: "none", }); resolve(""); return; } resolve(value); }; const cancel = () => resolve(""); const failToast = () => { uni.showToast({ title: "扫码失败", icon: "none", }); resolve(""); }; if (!isAppPlus()) { failToast(); return; } // 仿照 ZL-MES-UNIAPP /pages/rollingScan 的 uni.scanCode 用法 uni.scanCode({ // 是否只能从相机扫码,不允许从相册选择图片 onlyFromCamera: false, // 扫码识别类型 scanType: ["qrCode", "barCode"], // 是否启用自动放大 autoZoom: true, // 是否隐藏相册 hideAlbum: false, success: (res) => { done(res && res.result); }, fail: (err) => { if (isCancelError(err)) { cancel(); return; } failToast(); }, }); }); } export function scanByCameraCompat(_options, callback) { scanByCamera().then((text) => { if (typeof callback !== "function") return; if (!text) { callback({ resp_code: 10, resp_message: "用户取消", resp_result: "", }); return; } callback({ resp_code: 1000, resp_message: "成功", resp_result: text, }); }); }