Uniapp开发h5在微信浏览器打开摄像头扫码

2025年09月26日 Uniapp

有个项目需要使用h5 的 api 在微信里打开时调用扫码功能,如何加载配置h5打开扫码按钮,需要注意一些规则,成功记录以备后用

安装weixin-js-sdk

npm库:https://www.npmjs.com/package/weixin-js-sdk

Github:https://github.com/yanxi123-com/weixin-js-sdk

npm install weixin-js-sdk
or
pnpm add weixin-js-sdk

使用

// commonjs
var wx = require('weixin-js-sdk');

// es module
import wx from 'weixin-js-sdk'

配置

检测是不微信浏览器环境

export const isWxBrowser = () => {
  // 判断是否H5微信环境,true为微信浏览器
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes("micromessenger");
};
export const isIos = () => {
  // 是否IOS true为ios
  let u = navigator.userAgent;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  return isIOS ? true : false;
};

需要后端去微信接口拿到appId、timestamp、nonceStr、signature,页面显示的时候就要拿到相应配置,wx.config 的时候需要时间,在调用前保持配置已拿到。

import { isWxBrowser } from "@/utils/env";
import { findSign} "@/http/modules/match";
const startScan = async () => {
  if (!isWxBrowser()) {
    uni.showToast({ title: "请在微信中使用此功能", icon: "none" });
    return;
  }
  getfindSign();
  try {
    wx.config({
      debug: false,
      appId: params.value.appId,
      timestamp: params.value.timestamp,
      nonceStr: params.value.nonceStr,
      signature: params.value.signature,
      jsApiList: ["scanQRCode"],
    });
    wx.ready(async () => {
      wx.scanQRCode({
        debug: false,
        needResult: 1,
        scanType: ["qrCode"],
        success: (res) => {
          getticketWriteOff(res.resultStr);
        },
        fail: (res) => {
          uni.showToast({ title: res.errMsg, icon: "none" });
          console.log("🚀 ~ startScan ~ res:", res);
        },
      });
    });
  } catch (error) {
    console.log("🚀 ~ startScan ~ error:", error);
  }
};

onShow(async () => {
  await getfindSign();
});

如果其它页面跳转到此页面建议使用 window.href 来

window.location.href = "/pages/me/scan?code=" + code.value;
0%