详解在vue使用weixin-js-sdk常见使用方法

链接:https://qydev.weixin.qq.com/wiki/index.php?title=%E5%BE%AE%E4%BF%A1JS-SDK%E6%8E%A5%E5%8F%A3#.E6.AD.A5.E9.AA.A4.E4.B8.80.EF.BC.9A.E5.BC.95.E5.85.A5JS.E6.96.87.E4.BB.B6

1.导入依赖包

npm install weixin-js-sdk

2.判断是否是在微信浏览器中

env.js

<script>
var ua = navigator.userAgent.toLowerCase();
var isWeixin = ua.indexOf(\'micromessenger\') != -1;
var isAndroid = ua.indexOf(\'android\') != -1;
var isIos = (ua.indexOf(\'iphone\') != -1) || (ua.indexOf(\'ipad\') != -1);
if(!isWeixin) {
 document.head.innerHTML = \'<title>抱歉,出错了</title><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=0\"><link rel=\"stylesheet\" type=\"text/css\" href=\"https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css\" rel=\"external nofollow\" >\';
 document.body.innerHTML = \'<div class=\"weui_msg\"><div class=\"weui_icon_area\"><i class=\"weui_icon_info weui_icon_msg\"></i></div><div class=\"weui_text_area\"><h4 class=\"weui_msg_title\">请在微信客户端打开链接</h4></div></div>\';
} 

在main.js中引用:

import env from \"./env\";//运行环境

微信登录,通过code换取openid,在起始页使用该方法:

<script>
methods:{
 // 微信登陆
    wxLogin() {
      var that = this;
      axios
        .get(\"/common/loginAuth\")
        .then(function(res) {
          console.log(\"后台返回的链接地址\", res.data);
          window.location.href = res.data;//跳转后台返回的链接地址
        })
        .catch(function(error) {});
    },
//换取用户信息
    postCode(res) {
      var that = this;
      axios
        .post(\"/common/getUserInfo\", {
          code: res
        })
        .then(function(res) {
          cookie.set(\"openid\", res.data.openid);//code像后台换取openid并存入
        })
        .catch(function(error) {
          console.log(error);
        });
    }},
created() {
    var r = window.location.href;//获取当前链接,拆分当前链接
    //当前链接地址为后台返回的参数,有拆分得到链接中的code,通过postCode()方法获取openid,没有则通过wxLogin()方法开始微信登录
    if (r.indexOf(\"?\") != -1) {
      r = r.split(\"?\");
      r = r[1].split(\"&\");
      r = r[0].split(\"=\");
      r = r[1];
    } else {
      this.wxLogin();
    }
    if (r) {
      this.postCode(r);
    } else {
      this.wxLogin();
    }
  },
</script>

3.前端页面使用

import wx from \'weixin-js-sdk\'
this.axios({
  method: \'post\',
  url: \'url\',
  data:{ url:location.href.split(\'#\')[0] } //向服务端提供授权url参数,并且不需要#后面的部分
}).then((res)=>{
  wx.config({
    debug: true, // 开启调试模式,
    appId: res.appId, // 必填,企业号的唯一标识,此处填写企业号corpid
    timestamp: res.timestamp, // 必填,生成签名的时间戳
    nonceStr: res.nonceStr, // 必填,生成签名的随机串
    signature: res.signature,// 必填,签名,见附录1
    jsApiList: [\'scanQRCode\'] // 必填,需要使用的JS接口列表,所有JS接口列
  });
})
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容