天天看点

微信公众号获取openid(vue)

export default {
   created () {
     this.page= (this.getUrlParam("page")===null)?this.getUrlParam("state"):this.getUrlParam("page");
     this.getCode();
   },
   data(){
     return {
       //由于是通过微信公众号不同菜单点击进入页面,需要判断
       page:'',
     };
   },
   methods: {
     getCode () { // 非静默授权,第一次有弹框
       const code = this.getUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
       if (code == null || code === '') {
         window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+this.sv.APP_ID+'&redirect_uri=' + encodeURIComponent(this.sv.LOCAL) + '&response_type=code&scope=snsapi_base&state='+this.page+'#wechat_redirect'
       } else {
         this.getOpenId(code) //把code传给后台获取用户信息
       }
     },
     getOpenId (code) { // 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口
       let _this = this
       this.$ajax.post(this.$apiList.isRegist, {code: code,appid:this.sv.APP_ID,secret:this.sv.SECRET,hosnum:this.sv.HOSNUM,page:this.page}, true,{}).then(function (data) {
         let _data=data.data;
         //如果是没有注册过的用户进入到注册页面//210990198808097896
         if (_data.status === -1 ) {
           _this.$router.push("/about?openid="+_data.openid+"&page="+_this.page);
         }
         //如果是注册过的用户(0-his,1-体检)
         else if(_data.status ==='0'){
           _this.$router.push("/his?openid="+_data.openid);
         }else if(_data.status==='1'){
           _this.$router.push("/amedical?openid="+_data.openid);
         }
       }, function (err) {
         console.log(err);
       });
     },
     getUrlParam(name) {
       let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
       let r = window.location.search.substr(1).match(reg);
       if (r != null) return unescape(r[2]);
       return null;
     }
   },
 }