微信授權實現跨平台(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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM