官方文檔:PC 公眾號 小程序 APP
輔助工具:
PC
登錄:
1.引進SDK
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<div id="login_container"></div>
3.初始化
手機掃碼登錄后在回調地址頁中獲取code值 this.$route.query.code
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_key,encryptedData,iv,解密數據(服務端解密demo下載),返回開放平台唯一標識unionId
5.用戶點擊開放標簽<button openType="getPhoneNumber" bindgetphonenumber="getPhoneNumber">獲取手機號</button>
執行方法 getPhoneNumber(e) 回調新算法向量e.detail.iv,解密數據e.detail.encryptedData
調用接口 wx.login 獲取新code值,后台執行第3第4步,解密返回手機號phoneNumber