赞
踩
1、安装weixinsdk
npm install weixin-js-sdk
2、引入
import wx from "weixin-js-sdk";
3、点击扫一扫获取微信签名
- //点击扫一扫
- onScan() {
- this.getWxSign();
- },
-
- // 获取微信签名
- getWxSign() {
- let that = this;
- let signUrl = window.location.href.split("#")[0];
- if (window.signUrl !== undefined) {
- signUrl = window.signUrl;
- }
- let params = {
- url: encodeURIComponent(signUrl),
- // url: encodeURIComponent('https://octopus.zhangyukanghu.com/'),
- };
-
- getWxSign(params).then((res) => {
- if (res.code == 200) {
- wx.config({
- debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印
- appId: res.data.appId, // 必填,公众号的唯一标识
- timestamp: parseFloat(res.data.timestamp), // 必填,生成签名的时间戳
- nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
- signature: res.data.sign, // 必填,签名
- jsApiList: ["checkJsApi", "scanQRCode", "chooseWXPay"], // 必填,需要使用的JS接口列表
- });
- // 通过ready接口处理成功验证
- wx.ready(function () {
- wx.checkJsApi({
- jsApiList: ["scanQRCode"],
- success: function (res1) {
- if (res1.checkResult.scanQRCode === true) {
- wx.scanQRCode({
- needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
- scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
- success: function (res2) {
- var result = res2.resultStr; //当needResult 为 1 时,扫码返回的结果
- //需要加setTimeout,否则获取不到结果
- setTimeout(() => {
- if (result != "" && result != undefined) {
- //验卷接口
- that.scanCode(result);
- } else {
- alert("未扫描到卷码");
- }
- }, 500);
- },
- });
- } else {
- alert("当前登录环境不支持扫码,请切换微信环境");
- }
- },
- fail: function (e) {
- alert("当前登录环境不支持扫码,请切换微信环境");
- },
- });
-
- // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中
- });
- // 通过error接口处理失败验证
- wx.error(function (res) {
- console.warn(res);
- // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
- });
- }
- });
- },
- scanCode(result) {
- let params = {
- couponsId: result,
- typeId: this.type,
- payAmount: 0,
- optId: this.userId,
- };
- API.getScan(params).then((res) => {
- if (res.code == 200) {
- Dialog.alert({
- title: "扫码成功",
- message: result,
- confirmButtonColor: "#3ab295",
- }).then(() => {
- // on close
- });
- this.getListData();
- } else {
- this.$notify({
- type: "error",
- duration: 2000,
- message: res.msg,
- });
- }
- });
- },

4.需要注意⚠️
报错原因,从登陆页到扫一扫页面,路由跳转了,但是url地址没有变更,导致签名地址不一致,安卓机不报错,ios报错~
解决方法:
window.open(url,'_self');或者window.location.href=url;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。