webpack. vue.js 获取微信openid和昵称信息

var vue = new Vue({
    el:"#app",
    data: {
        getopenid_url : "https://xxx/getcode/openid.php",
        getuserdata_url:"https://xxx/getcode/get_userdata.php",
        openid:'',
        nickname:'',
        headimgurl:'',
    
    },
  created() {

      this.getWxCode();

    },

method:{
    


      isWechat:function(){
        return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
     
      },
      // 判断公众号截取code
      getUrlParam:function(name){
          let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
          let r = window.location.search.substr(1).match(reg);
          if (r != null) {
              return unescape(r[2]);
          }
          return null;
      }, 
      getuserdata:function(openid,access_token){
        $.ajax({
            url : this.getuserdata_url,
            type : "POST",
            cache: false,
            async : true,//同步请求用false,异步请求true
            dataType : "json",
            contentType:"application/x-www-form-urlencoded;charset=UTF-8",
            crossDomain: true,
            data:{
                openid:openid,
                access_token:access_token,
            },
            xhrFields: {
                withCredentials: true    // 此字段标识要跨域传数据
            },
            headers: {
                'Access-Control-Allow-Origin': '*',
                accept: 'application/json',
            },
            success : function(data) {
                console.log(data);
            
                vue.nickname = data.nickname;
                vue.headimgurl = data.headimgurl;
                /*      let image = new Image();
                    // 解决跨域 Canvas 污染问题
                        image.setAttribute("crossOrigin", "anonymous");
                        image.src = data.headimgurl;
                        image.onload = function() {
                            document.write("<img src='"+image.src+"'>")
                    };
                */
    
            },
    
        });
    
    },
    
      getWxCode:function(){
        if (this.isWechat()) {
            let appid = "wx0471452b79f04219"; //appid
            let SECRET = "10ad71e05581e47f6f0d0bbfb3dc682c";
            let code = this.getUrlParam("code"); //是否存在code
            let local = window.location.href;
            let wx_url = "https://open.weixin.qq.com/connect/oauth2";
            let wx_apiUrl = "https://api.weixin.qq.com/sns/oauth2";
            if (code == null || code === "") {
                //不存在就打开上面的地址进行授权
                window.location.href=`${wx_url}/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
             
            }else{
                // this.code = code
                $.ajax({
                    url : this.getopenid_url,
                    type : "POST",
                    cache: false,
                    async : true,//同步请求用false,异步请求true
                    dataType : "json",
                    contentType:"application/x-www-form-urlencoded;charset=UTF-8",
                    crossDomain: true,
                    data:{
                        appid:appid,
                        secret:SECRET,
                        code:code,
                    },
                    xhrFields: {
                        withCredentials: true    // 此字段标识要跨域传数据
                    },
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        accept: 'application/json',
                    },
                    success : function(data) {
                        vue.openid = data.openid;
                        vue.getuserdata(data.openid,data.access_token)
                    },
                    error : function(data, textstatus) {
                        //请求不成功返回的提示
                        console.log(data,textstatus)
                    }
                });
    
    
            }
        }else{
            console.log("请在微信环境下打开");
          //  window.close();
        }
    },
    
  




}
});

  

posted @ 2021-12-16 09:45  Lyapeng  阅读(4)  评论(0)    收藏  举报