微信H5授权登录

1.情景:我们会碰到做的H5页面放到微信内部打开,用到微信h5支付或者用到微信用户的头像,昵称这些信息.这时候我们就只能苦逼调用微信H5授权登录了(且必须)
2.直接放全部代码,后面再划重点,折腾了几天的经验,微信api乱七八糟你懂得.

   //微信环境下授权登录,获取用户头像
      async vwInit() {
        if (typeof WeixinJSBridge != 'undefined') {
          if (!this.code) {
            let redirect_uri = window.location.href;
            redirect_uri = encodeURIComponent(redirect_uri)
            var url =
              `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`

            window.location.href = url;
          } else {

            //  let urlTwo = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的公众号appid&secret=你的公众号appsecret&code=${this.code}&grant_type=authorization_code`
            // let urlTwo =
            //   `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appid}&secret=${this.secret}&code=${this.code}&grant_type=authorization_code`
            // POST /getWeChatOpenid

            let res = await this.$http.post('/getWeChatOpenid', {
              wxCode: this.code
            })
            console.log(res);
            sessionStorage.openid = res.openid
            sessionStorage.access_token = res.access_token
            let url3 =
              `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${res.access_token}&openid=${res.openid}&lang=zh_CN`

            let res3 = await this.$http.get(url3)
            console.log(res3);
            // 微信用户头像
            alert('微信用户头像:' + res3.headimgurl)
            sessionStorage.headimgurl = res3.headimgurl

          }
        }
      },

3-1 第一步获取code

let redirect_uri = window.location.href;
redirect_uri = encodeURIComponent(redirect_uri)
var url =
 `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
window.location.href = url;
//注意一定要location.href 来跳转
//跳转返回//www.greatytc.com/?code=123456

3-2 第二部获取openid和access_token

let url2 =
`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appid}&secret=${this.secret}&code=${this.code}&grant_type=authorization_code`
// 公众号appid+公众号secret+第一步获取的code
let res2 = await this.$http.get(url2 )
//上面全部代码那里考虑到secret字段信息安全问题,由后端做请求返回openid 和access_token,就是两种方式辣,一样的必不可少的流程
//'微信用户头像:' + res2.headimgurl,其他返回字段请参考微信api辣
           

--by Affandi ⊙▽⊙

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。