h5在小程序中调用微信扫码功能

39 篇文章 0 订阅
21 篇文章 0 订阅
文章描述了一个H5页面通过引入微信SDK实现调用微信小程序的扫码功能。当用户在H5的A页面点击扫码后,跳转至小程序的B扫码页面,扫描完成后,小程序将结果带回到H5的A页面,并根据扫码结果查询列表数据。
摘要由CSDN通过智能技术生成

目前扫码模块是用原生小程序写的页面,登录和之后跳转的页面都是通过webView嵌套在小程序里面的h5。

  • 需求:h5页面扫码,拿到扫码后的结果,去查询列表的数据。
  • 方案:在h5中引入微信的sdk,在A页面跳转进入原生小程序的B扫码页面,在B扫码页面拿到扫码结果,再跳转回原来的A页面,并且在路由上携带扫码的结果

1.安装依赖

npm install weixin-js-sdk

2.h5使用依赖进行跳转

A.vue

<template>
  <van-col class="scan" span="3" @click="gotoScan">
     <van-icon class="scanIcon" name="scan" />
   </van-col>
</template>
<script>
import wx from "weixin-js-sdk";
export default {
  created() {
    // 获取传递回来的数据,token是要继续传回来的,因为扫码回来的跳转是调不同体系的页面了
    let { result, token, username } = this.$route.query || {};
    if (result) {//如果扫码结果存在
      localStorage.setItem("token", this.$route.query.token);
      localStorage.setItem("username", this.$route.query.username);
      //扫码失败
      if (result === "error") {
        return Toast("扫码失败!");
      } else {
        // 扫码成功
        this.queryValue = result;
        // 编码不存在
	    if (!result|| result=== "undefined") {
	        Toast("名称或编码不存在!");
	      } else {
	        Toast("扫码结果:" + result);
	        this.msgFun();
	     }
      }
    } else {
      // 如果路由没有参数,就直接查询列表
      this.msgFun();
    }
  },
  methods: {
    // 跳转到小程序的“扫一扫”页面
    gotoScan() {
      let that = this;
      if (navigator.userAgent.toLowerCase().indexOf("miniprogram") !== -1) {
        // 判断是否是微信环境
        // 微信环境 如果不是Vue导入方式,需要写成window.wx.miniProgram.getEnv()
        wx.miniProgram.getEnv(function (res) {
          if (res.miniprogram) {
            // 小程序环境下逻辑,跳转到小程序的页面地址,并且携带参数过去
 			wx.miniProgram.navigateTo({
              url:
                "../scan/scan?token=" +
                localStorage.getItem("token") +
         		"&username=" +
                localStorage.getItem("userName") +
                `&pageName=index`,
            });
          }
        });
      }  else {
        if (
          navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1
        ) {
          Toast("微信内置浏览器");
        } else Toast("非微信环境逻辑");
         // 非微信环境逻辑,比如在浏览器下,可以在这里写一些事件
     }
    },
        
    // 查询列表
    msgFun() {
      service
        .findTransportationTaskNew({ queryValue: this.queryValue })
        .then((res) => {
        	//----
        })
    }
}
</script>

3.小程序扫码

3.1 配置页面

app.json

{
    "pages": [
        "pages/index/index",
        "pages/scan/scan"
    ],
    "window": {
        "backgroundTextStyle": "light",
        "navigationBarBackgroundColor": "#fff",
        "navigationBarTitleText": "Weixin",
        "navigationBarTextStyle": "black"
    },
    "style": "v2",
    "sitemapLocation": "sitemap.json"
}

3.2 扫码页面

pages/scan/scan.js

// 注意,这里扫码后回跳转到首页去
Page({
    data: {},//页面的初始数据
    onLoad: function(options) {//生命周期函数--监听页面加载
        this.setData({
            token: options.token,
            id: options.id,
            username: options.username
        })
        //兼容ios微信无法立即调起扫一扫
        setTimeout(function () {
            wx.scanCode({//调用扫一扫
                onlyFromCamera: false,
                success: function (res) {//扫码成功的回调函数
                    wx.reLaunch({//失败的话,重定向到页面中,并且携带miniType参数和result参数
                        url: '../index/index?id=' + options.id + '&result=' + res.result + '&username=' + options.username + '&token=' + options.token + '&type=wechat'
                    })
                },
                error: function (err) {//扫码失败的回调函数
                    console.log('err');
                    wx.reLaunch({//失败的话,重定向到页面中,并且携带miniType参数和result参数
                        url: '../index/index?id=' + options.id + '&result=error&username=' + options.username + '&token=' + options.token + '&type=wechat'
                    })
                },
                fail: function(res) {//取消扫一扫
                    wx.reLaunch({//失败的话,重定向到页面中,并且携带miniType参数和result参数
                        url: '../index/index?id=' + options.id + '&result=error&username=' + options.username + '&token=' + options.token + '&type=wechat'
                    })
                }
            })
        }, 50)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})

pages/scan/scan.js

<view class="scan">数据加载中...</view>

3.3 首页(嵌套容器页面)

pages/index/index.js

// 获取应用实例
const app = getApp()

Page({
  data: {
    pathUrl: ''//嵌入web-view的地址
  },
  // 事件处理函数
  bindViewTap() {},
  onLoad(options) {
    //options为路由跳转携带的参数
    if (Object.keys(options) && Object.keys(options).length > 0) {
        if (options.result) {
            // 最终又跳回到h5的列表页(实际都通过)
            this.setData({
                pathUrl: '/#/h5/index?result=' + options.result + '&username=' + options.username + '&token=' + options.token + '&type=wechat'
            })
        } else this.setData({
            pathUrl: '/#/barCodeDetail' + '?' + options.scene
        })
    }
  },
})

pages/index/index.wxml

<view class="container">
	<!--通过{{}}绑定变量-->
	<web-view src="{{'https://xxx.com'+pathUrl}}"></web-view>
</view>

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值