vue 使用微信js-sdk

967 阅读1分钟

1. 引入

npm install weixin-js-sdk -S

2. main.js

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

3. App.vue获取签名进行注册

let params =
{
  debug: "false",
  jsApiList:
    "scanQRCode,openTagList,chooseImage,uploadImage,getLocalImgData",
  // openTagList: "wx-open-launch-app",
  url: encodeURIComponent(window.location.href.split("#")[0])
}
// 网络请求回签名信息
this.$wx.config({
  debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId, // 必填,公众号的唯一标识
  timestamp, // 必填,生成签名的时间戳
  nonceStr, // 必填,生成签名的随机串
  signature, // 必填,签名
  jsApiList // 必填,需要使用的JS接口列表
});
this.$wx.ready(() => {
  // 业务
  console.log("wx.ready");
});
this.$wx.error(err => {
  console.log("wx.error", err);
});

4. 其他页面使用(选择图片并上传到自己的服务器)

wxChooseImg(){
    this.$wx.chooseImage({
      count: 1, // 默认9
      sizeType: ["compressed"], // 可以指定是原图还是压缩图,默认二者都有 original原图
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
      success: function(res) {
        let localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
        that.$wx.getLocalImgData({
          localId: localIds[0], // 图片的localID
          success: function(r) {
            let localData = r.localData; // localData是图片的base64数据,可以用img标签显示
            that.uploadImage(localData);
          }
        });
      }
    });
},
upload(){
    let blob = convertBase64UrlToBlob(result); // 图片blob
    let formData = new FormData();
    formData.append("file", blob, new Date().getTime() + ".jpeg");
    this.$store.dispatch("common/countAdd");// 标记请求
    let res = await axios.post(
      baseUrl + "/icr/recognize_id_card",
      formData,
      {
        Headers: {
          "content-type": "multipart/form-data"
        }
      }
    );
    this.$store.dispatch("common/countReduce");// 标记请求
}