web-view 调用微信小程序的方法

1.1api文件夹下新建api.js
/获取微信公众号配置授权—后端提供接口/

  initConfig: url => {
    return API.GET('/api/getJsapiSignature?url=' + url);
  },

1.2 utils文件夹下新建一个js 文件,放置小程序的方法

import api from '@/api/api'
export default {
  /**
   *
   *
   * @memberof WxMpApiService
   */
  initConfig(url) {
    this.wx = window['wx'];
    let href = '';
    if (url) { // 自定义地址
      href = url;
    } else {
      href = window.location.href.split('#')[0];
    }
    api.initConfig(encodeURIComponent(href)).then(config => {
      this.initWXConfig(config);
    });
  },

  /**
   *打开相册  选择图片
   *
   * @param {(url: string) => void} callBallck
   * @memberof WxMpApiService
   */
  chooseImage() {
    return new Promise(function (resolve, reject) {
      this.wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 'original' compressed
        sourceType: ['album'], // 可以指定来源是相册还是相机,默认二者都有
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          console.log(tempFilePaths);
          resolve(tempFilePaths);
        }
      });
    })
  },
  /**
   *扫二维码
   *
   * @param {(resultStr: string) => void} callBallck
   * @memberof WxMpApiService
   */
  scanQRCode() {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.wx.scanQRCode({
        needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有 'qrCode',"barCode"
        success: (res) => {
          resolve(res.resultStr);
        }
      });
    })
  },
  //
  // openLocation(param: OpenLocationModel) {
  //   this.wx.openLocation({
  //     latitude: param.latitude, // 纬度,浮点数,范围为90 ~ -90
  //     longitude: param.longitude, // 经度,浮点数,范围为180 ~ -180。
  //     name: param.name, // 位置名
  //     address: param.address, // 地址详情说明
  //     scale: param.scale, // 地图缩放级别,整形值,范围从1~28。默认为最大
  //     infoUrl: param.infoUrl // 在查看位置界面底部显示的超链接,可点击跳转
  //   });
  // },
  //
  // getLocation(fs: (res: any) => void) {
  //   this.wx.getLocation({
  //     type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
  //     success: (res) => {
  //       // alert('成功回调:' + JSON.stringify(res));
  //       const latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
  //       const longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
  //       const result = {lng: longitude, lat: latitude, exceptionStatus: 0}
  //       fs(result);
  //     },
  //     fail: (res) => {
  //       // alert('失败回调:' + JSON.stringify(res));
  //       const result = {lng: null, lat: null, exceptionStatus: 1, exceptionMsg: res.errMsg};
  //       fs(result);
  //     }
  //   });
  // },
  //
  initWXConfig(config) {
    this.wx.config({
      beta: true,
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: config.appId, // 必填,公众号的唯一标识
      timestamp: config.timestamp, // 必填,生成签名的时间戳
      nonceStr: config.nonceStr, // 必填,生成签名的随机串
      signature: config.signature, // 必填,签名
      jsApiList: [
        'checkJsApi',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'scanQRCode',
      ] // 必填,需要使用的JS接口列表
    });
  },
  //
  // getEnv(): Promise<boolean> {
  //   let result = false;
  //   this.log(window.navigator.userAgent);
  //   const ua: string = window.navigator.userAgent.toLowerCase();
  //   if (ua.match(/MicroMessenger/i)) {
  //     result = true;
  //   } else {
  //     result = false;
  //   }
  //   const promise = new Promise<boolean>(resolve => {
  //     resolve(result);
  //   });
  //   return promise;
  // },
  //
  // login(returnUrl: string) {
  //   const redirectUrl = window.location.origin + environment.wxAuthorizUri
  //     + encodeURIComponent(window.location.origin + returnUrl);
  //   // + encodeURIComponent(window.location.origin + window.location.pathname + '/#' + returnUrl);
  //   window.location.href = redirectUrl;
  // },
  //
  // isMiniProgram(): boolean {
  //   // 小程序环境
  //   return window['__wxjs_environment'] === 'miniprogram';
  // },
  // pay(param: PayModel) {
  //   return new Promise(resolve => {
  //     // @ts-ignore
  //     WeixinJSBridge.invoke(
  //       "getBrandWCPayRequest",
  //       {
  //         "appId": param['appId'],     //公众号名称,由商户传入
  //         "timeStamp": param['timeStamp'], //时间戳,自1970年以来的秒数
  //         "nonceStr": param['nonceStr'], //随机串
  //         "package": param['package'],
  //         "signType": param['signType'], //微信签名方式:
  //         "paySign": param['paySign'] //微信签名
  //       },
  //       function (res) {
  //         if (res.err_msg == "get_brand_wcpay_request:ok") {
  //           return resolve({
  //             code: 1,
  //             payDetailId: param['payDetailId']
  //           });
  //           // 使用以上方式判断前端返回,微信团队郑重提示:
  //           //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
  //         } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
  //           return resolve({
  //             code: 0,
  //             payDetailId: null
  //           });
  //         } else if (res.err_msg == "get_brand_wcpay_request:fail") {
  //           // @ts-ignore
  //           WeixinJSBridge.call('closeWindow');
  //           return resolve({
  //             code: -1,
  //             payDetailId: null
  //           });
  //         }
  //       }
  //     );
  //   })
  // },
  // // 微信支付
  // WeixinJs() {
  //   // @ts-ignore
  //   if (typeof WeixinJSBridge == "undefined") {
  //     if (document.addEventListener) {
  //       // @ts-ignore
  //       document.addEventListener(
  //         "WeixinJSBridgeReady",
  //         this.pay(null),
  //         false
  //       );
  //       // @ts-ignore
  //     } else if (document.attachEvent) {
  //       // @ts-ignore
  //       document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady());
  //       // @ts-ignore
  //       document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady());
  //     }
  //   } else {
  //     this.pay(null);
  //   }
  // },
  // openMapLocation(param: MapLocationModel) {
  //   super.openMapLocation(param);
  // },
}

1.3 H5页面使用
<template #button>
<van-button size=“small” type=“info” @click=“sweep” native-type=“button”>扫一扫

import WX from ‘@/views/utils/wx-mp’
mounted() {
WX.initConfig();
}
methods:{
async sweep() {
let val = await WX.scanQRCode();
this.code = val //赋值扫到的码
console.log(this.code);
},
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值