微信授权实现跨平台(PC+公众号+小程序+APP)登录(unionid+手机号)

 官方文档:PC  公众号  小程序  APP

辅助工具:

PC

登录:

1.引进SDK

<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

2.内嵌二维码容器

<div id="login_container"></div>

3.初始化

var obj = new WxLogin({
  self_redirect: false,
  id: "login_container",
  appid: "网站应用AppID",
  scope: "snsapi_login",
  redirect_uri: "UrlEncode编码回调地址",
  state: “”,
  style: "",
  href: ""
});

手机扫码登录后在回调地址页中获取code值 this.$route.query.code

4.后台

GET请求 https://api.weixin.qq.com/sns/oauth2/access_token?appid=网站应用AppID&secret=网站应用AppSecret&code=code&grant_type=authorization_code

返回 unionid

公众号

登录:

1.跳转微信链接并获取code回调,回调地址需添加在 公众号设置>功能设置>网页授权域名 中并进行UrlEncode编码

location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=公众号AppID&redirect_uri=回调地址&response_type=code&scope=snsapi_userinfo#wechat_redirect'

在回调地址页中获取code值 this.$route.query.code

2.后台GET请求 https://api.weixin.qq.com/sns/oauth2/access_token?appid=公众号AppID&secret=公众号AppSecret&code=code&grant_type=authorization_code

返回公众号唯一标识openid,开放平台唯一标识unionid(跨端唯一标识,需将 公众号,小程序,app 添加到微信开放平台中),获取用户信息所需字段access_token

3.真机调试,打印可复制信息,辅助代码

let debug = document.createElement("debug")
debug.innerHTML = `<div style="position: fixed; top: 0;"><textarea>${code值要打印复制的变量}</textarea><a href="javascript:document.body.removeChild(document.getElementsByTagName('debug')[0])">close</a></div>`
document.body.appendChild(debug)

 

用户信息:

1.登录后,后台GET请求 https://api.weixin.qq.com/sns/userinfo?access_token=access_token&openid=openid&lang=zh_CN

返回用户昵称nickname,头像headimgurl

小程序

用户信息+唯一标识登录+手机号登录:

1.调用接口 wx.login 获取code

2.用户点击开放标签<button openType="getUserInfo" bindgetuserinfo="getUserInfo">获取用户信息</button>

执行方法 getUserInfo(e) 回调用户昵称e.detail.userInfo.nickName,头像e.detail.userInfo.avatarUrl,算法向量e.detail.iv,解密数据e.detail.encryptedData

3.后台GET请求 https://api.weixin.qq.com/sns/jscode2session?appid=小程序AppID&secret=小程序AppSecret&js_code=code&grant_type=authorization_code

返回小程序唯一标识openid,会话密钥session_key

4.使用小程序AppID,session_keyencryptedDataiv,解密数据(服务端解密demo下载),返回开放平台唯一标识unionId

5.用户点击开放标签<button openType="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>

执行方法 getPhoneNumber(e) 回调新算法向量e.detail.iv,解密数据e.detail.encryptedData

调用接口 wx.login 获取新code值,后台执行第3第4步,解密返回手机号phoneNumber

 

posted @ 2020-12-03 18:25  动听小林  阅读(1051)  评论(0编辑  收藏  举报