Vue项目中实现网页授权

       今天突然要做微信公众号项目,第一次接触就要做一个 微信网页授权 的功能,看文档看了半天,懵逼的进去懵逼的出来,后来找度娘,看各种博客,终于明白了一些,然后知道了微信网页授权分两种,第一种是snsapi_base(静默授权,用户无感知),第二种是snsapi_userinfo(第一次授权需要用户点击登录确认)。静默授权只需要两步就能拿到开发者需要的openID,而第二种授权方式,一共需要四步,可以拉取到用户信息(昵称、头像等)。

       本人愚昧,到目前为止,我只做到了前两步,附上代码

<template>
    <div></div>
</template>

<script>
  import $ from "jquery"
    export default {
        name: "testDemo",
      data(){
        return{

        }
      },
      methods:{
        getCode(){
          //    snsapi_base  snsapi_userinfo 第一步用户授权,跳转目标页,在下一页得到code
          var AppId = "wxd26bda82d18b5926";//公众号的唯一标识,开发者ID
          var redirect_urls= encodeURIComponent("http://www.shapeui.com");
          var urls =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AppId+"&redirect_uri="+redirect_urls+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
          window.location.href = urls;

          console.log(window.location.href)
        },
        getQueryString(name){
          var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
          var r = window.location.search.substr(1).match(reg);
          if (r != null) {
            return unescape(r[2]);
          }else {
            return null;
          }
        },
        GetCodeDemo(){
          var code = this.getQueryString('code')
          console.log(code)
          if(code != null){
            var parameters = {};
            parameters.appid = "wxd26bda82d18b5926";
            parameters.secret = "f48c3c9dcf342904ef41941c0be75071";
            parameters.code = code;
            parameters.grant_type="authorization_code"
            $.ajax({
              type: 'POST',
              data:parameters,
              url:"http://weixin3.szfangle.com/wxapp/mobileApi/submitWxcode.fgl?",
              success: function(res){
                console.log(res)

              },error:function(res){
                console.log(res)
              }
            });
          }
        }
      },
      created(){
        this.getCode();
        this.GetCodeDemo();
      }
    }
</script>

<style scoped>

</style>

效果图
效果图

猜你喜欢

转载自blog.csdn.net/qq_43271452/article/details/88701340
今日推荐