基于微信浏览器调取微信sdk接口

因为公司项目是一套基于微信公众平台的webapp项目,故多处需要调取微信接口完成支付,拍照,本地图册以及录音功能接口,自己也翻了很多文档,看了很多博客,但是也会有很多坑,所以整理下自己在做的时候的思路,希望以后能用到。

首先要做的是你的公众号要在微信上申请收付款的功能等,重中之重。

引入微信sdk:

cdn引入:

直接在vue项目的一级目录中的index.html中引入微信sdk的js文件

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script>

npm 安装微信sdk模块

安装命令:

npm install weixin-js-sdk --save-dev

然后在main.js中全局配置,也可以在单页面中局部配置

import wx from 'weixin-js-sdk';

//或者

import wx from 'weixin-js-sdk';
Vue.prototype.wx = wx

配置微信接口

使用"WeixinJSBridgeReady"在页面中拉起微信支付(不需要通过config接口注入权限验证配置,直接调用方法就可以在页面上拉起支付)

// 拉起微信支付的关键
    onBridgeReady: function(data) {
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称,由商户传入
          timeStamp: data.timeStamp, //时间戳,自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式:
          paySign: data.sign //微信签名
        },
        function(res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            alert("支付成功");
          }
          if (res.err_msg == "get_brand_wcpay_request:cancel") {
            alert("交易取消");
          }
          if (res.err_msg == "get_brand_wcpay_request:fail") {
            alert("支付失败");
          }
        }
      );
    }
    
// 检测
if (typeof WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
        document.addEventListener("WeixinJSBridgeReady", this.onBridgeReady(weChatPayData), false);
    } else if (document.attachEvent) {
        document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(weChatPayData));
        document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady(weChatPayData));
      }
    } else {
       this.onBridgeReady(weChatPayData);
    }
} else {
    alert("登录超时,请重新登录!");
}

使用wx.config的依赖注入:

wx.config({
    beta: false,  //开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    debug: false, //是否开启调试模式,会自动弹一些消息框显示微信返回的数据
    appId: data.appId, //让后台返回appid
    timestamp: data.timestamp, //让后台返回生成证书时用的时间戳
    nonceStr: data.nonceStr, //让后台返回生成证书时用的随机串
    signature: data.signature, //让后台返回已当前URL地址生成的证书
    jsApiList: [
        "chooseImage",//选择图片
        "previewImage",//预览图片
        "uploadImage",//图片上传到微信服务器
        "downloadImage",//下载微信服务器上的图片
        "scanQRCode",//微信扫一扫
        "startRecord",//开始录音
        "stopRecord",//停止录音
        "playVoice",//开始播放录音,建议使用,音量会稍大一些
        "pauseVoice",//暂停播放录音
        "stopVoice",//停止播放录音
        "uploadVoice",//上传录音
        "downloadVoice",//下载录音
        "onVoicePlayEnd"//监听录音播放停止 
    ]
});
wx.ready(function() {
    // console.log("Msg:配置成功!");
});
wx.error(function() {
    // console.log("ErrMsg:配置失败!");
});

然后下面就是需要用到的方法

export default {
  data() {
    return {
      //通过config接口注入权限验证配置
      START: null,
      END: null,
      recordTime: 0,
      recordTimer: null,
      // 保存微信服务器上的图片地址
      mediaId: "",
    }
  },
methods: {
    // 获取服务器上的图片
    downloadImage: function(e) {
    //注意,这里需要将this实例化,有时调用this实例中的方法会报undefined
      let _this = this;
      wx.downloadImage({
        serverId: e.mediaId, // 需要下载的图片的服务器端ID,由uploadImage接口获得
        isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function(res) {
          // var localId = res.localId; // 返回图片下载后的本地ID
          var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
          localData = localData.replace("jgp", "jpeg"); //iOS 系统里面得到的数据,类型为 image/jgp,因此需要替换一下
        },
        fail: function(error) {
          alert(error);
        }
      });
    },
    //上传图片接口
    wxuploadImage: function(e) {
      //注意,这里需要将this实例化,有时调用this实例中的方法会报undefined
      let _this = this;
      //同上,实例化this.$route.query,否则会报query为undefined
      let _query = this.$route.query;
      wx.uploadImage({
        localId: e, // 需要上传的图片的本地ID,由chooseImage接口获得
        isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function(res) {
          console.log(
            "图片已上传到微信服务器,返回的数据为 : " + JSON.stringify(res)
          );
          //_this.mediaId = res.serverId; // 返回图片的服务器端ID

          // 在这里把上传到微信服务器的图片的地址传给后台,根据自己实际项目,也可以在其他位置上传
          //不要直接使用this.axios.post,会报post不是一个方法
          _this.axios
            .post("/api/chatLog", {
              messageContent: res.serverId,
              messageType: 2, //图片
            })
            .then(
              function(result) {
                console.log(result.data.data);
              }.bind(this)
            )
            .catch(function(error) {
              console.log(error);
              alert(error);
            });

          _this.downloadImage(res);
        },
        fail: function(error) {
          picPath = "";
          localIds = "";
          alert(JSON.stringify(error));
        }
      });
    },
    //这里调用微信的接口拍照
    userCamera: function() {
      event.preventDefault();
      let _this = this;
      //通过ready接口处理成功验证
      // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后
      //拍照或从手机相册中选图接口
      wx.chooseImage({
        count: 1,//设置图片的数量,按自己需求更改
        needResult: 1,
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图,默认二者都有
        sourceType: ["camera"], // 可以指定来源是相机,或者是本地相册,我这里是分开写的
        //sourceType: ["camera","album"],//合起来的写法
        success: function(data) {
            //因为在前面我是设置的只能传一张图片,如选择多张,返回的图片本地id则是一个数组
         var localIds = data.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
          _this.wxuploadImage(localIds);
        },
        fail: function(res) {
          alterShowMessage(
            "操作提示",
            JSON.stringify(res),
            "1",
            "确定",
            "",
            "",
            ""
          );
        }
      });
    },
    //<----------------------------------------------------微信音频分割线------------------------------------------------------------------------->
    //微信录音的接口

    // 开始录音
    wxStartRecord: function() {
      this.openRecordBtn = true;
      event.preventDefault();
      // 开启录音
      this.START = new Date().getTime();
      wx.startRecord({
        success: function() {
          localStorage.rainAllowRecord = "true";
          //console.log('成功调起录音')
          this.recordTimer = setInterval(() => {
            this.recordTime++;
          }, 1000);
        },
        cancel: function() {
          localStorage.rainAllowRecord = "false";
          alert("用户拒绝授权录音");
        }
      });
    },
    // 结束录音
    wxEndRecord: function() {
      this.openRecordBtn = false;
      event.preventDefault();
      let _this = this;
      // 结束录音
      this.END = new Date().getTime();

      if (this.END - this.START < 300) {
        this.END = 0;
        this.START = 0;
        //小于300ms,不录音
        alert("时间太短了,请重新录音!");
        clearInterval(this.recordTimer);
      } else {
        wx.stopRecord({
          success: function(res) {
            alert(res.localId);
            //暂停成功
            var localId = res.localId;
            _this.uploadVoice(localId);
            clearInterval(this.recordTimer);
          },
          fail: function(res) {
            alert("Errmsg:" + res);
          }
        });
      }
    },
    //上传录音
    uploadVoice: function(e) {
      let _this = this;
      let _query = this.$route.query;
      //调用微信的上传录音接口把本地录音先上传到微信的服务器
      //不过,微信只保留3天,而我们需要长期保存,我们需要把资源从微信服务器下载到自己的服务器
      wx.uploadVoice({
        localId: e, // 需要上传的音频的本地ID,由stopRecord接口获得
        isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function(res) {
          //把录音在微信服务器上的id(res.serverId)发送到自己的服务器供下载。
          _this.axios
            .post("/api/chatLog", {
              messageContent: res.serverId,
              messageType: 1, //音频
            })
            .then(
              function(result) {
                  console.log(result.data.data);
              }.bind(this)
            )
            .catch(function(error) {
              console.log(error);
              alert(error);
            });

          _this.downloadVoice(res.serverId);
        }
      });
    },
    // 下载录音
    downloadVoice: function(e) {
      wx.downloadVoice({
        serverId: e, // 需要下载的音频的服务器端ID,由uploadVoice接口获得
        isShowProgressTips: 0, // 默认为1,显示进度提示
        success: function(res) {
          // var localId2 = res.localId; // 返回音频的本地ID
          console.log("已经下载了该音频" + JSON.stringify(res.localId));
        }
      });
    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值