H5/web app/第三方網頁 微信授權登入 調研
微信登入:
使用者可使用微信帳號快速登入你的網站,
同一使用者使用微信登入你的不同應用和公眾帳號,會對應同一個UnionID,以便進行不同業務間的帳號統一
微信授權登入可分為:
- 掃碼登入(一般用於 PC 網頁)- 微信開放平臺
- 跳轉 APP 授權登入(第三方 APP 使用)- 微信開放平臺
- 微信內建瀏覽器內登入(一般用於移動端網站,公眾號登入)- 微信公眾平臺
- 微信小程式內微信登入(小程式內部)- 微信公眾平臺
公司專案登入場景描述:
只限於在微信客戶端開啟的網頁應用,在微信訊息列表直接給好友傳送一個網頁的URL,使用者收到直接點選URL直接開啟頁面
結論:雲學院為移動端網站,使用第三種登入方式,微信網頁授權
網頁授權的兩種方式:
1.靜默授權:
使用者感知的就是直接進入了回撥頁(往往是業務頁面)
req.scope = @"snsapi_base"
只能獲取access_token和openID
2.非靜默授權:
需要使用者手動同意,並且由於使用者同意過
req.scope = @"snsapi_userinfo"
獲取更詳細的使用者資料,比如頭像、暱稱、性別等
結論:使用非靜默授權
實現步驟:
1、登陸【杏樹林公眾號】後可以檢視到【appId】和【appsecret】資訊
2、公眾平臺官網中的“開發 - 介面許可權 - 網頁服務 - 網頁帳號 - 網頁授權獲取使用者基本資訊”的配置選項中,修改授權回撥域名
3、引導使用者進入授權頁面同意授權,此時會呼叫微信api獲取code
4、 授權通過後會帶上code引數請求回撥地址
5、 後臺獲取code,再次呼叫微信介面換取網頁授權access_token和openid
6、通過網頁授權access_token和openid獲取使用者基本資訊(如果有unionid還會獲取到unionid引數)
示例程式碼:
async function wxAuth(req, res) { //解析querystring獲取URL中的code值 let code = req.query.code; //通過拿到的code和appID、app_serect獲取返回資訊 let resObj = await getAccessToken(code); //解析得到access_token和open_id let access_token = resObj.access_token; let open_id = resObj.openid; //通過上一步獲取的access_token和open_id獲取userInfo即使用者資訊 let userObj = await getUserInfo(access_token, open_id); console.log(userObj); res.render(path.resolve(__dirname,'userInfo.ejs'), {userObj: userObj}); // res.send(userObj);} //通過拿到的code和appID、app_serect獲取access_token和open_id function getAccessToken(code) { return new Promise( (resolve, reject) => { let getAccessUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=` + `${appID}&secret=${appSerect}&code=${code}&grant_type=authorization_code`; https.get(getAccessUrl, (res) => { var resText = ""; res.on('data', (d) => { resText += d; }); res.on('end', () => { var resObj = JSON.parse(resText); resolve(resObj); }); }).on('error', (e) => { console.error(e); }); }); } //通過上一步獲取的access_token和open_id獲取userInfo即使用者資訊 function getUserInfo(access_token, open_id) { return new Promise( (resolve, reject) => { let getUserUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${open_id}⟨=zh_CN`; https.get(getUserUrl, (res) => { var resText = ""; res.on('data', (d) => { resText += d; }); res.on('end', () => { var userObj = JSON.parse(resText); resolve(userObj); }); }).on('error', (e) => { console.error(e); }); })}
demo:
文件:微信網頁授權