現在的網站開發,都繞不開微信登錄(畢竟微信已經成為國民工具)。雖然文檔已經寫得很詳細,但是對于沒有經驗的開發者還是容易踩坑。
所以,專門記錄一下微信網頁認證的交互邏輯,也方便自己日后回查:
微信網頁SDK加載
在多人團隊協作中,加載資源的代碼需要格外小心。因為可能會有多個開發者在同一業務邏輯下調用,這會造成資源的重復加載。
處理方法有兩種,第一種是對外暴露多余接口,專門check是否重復加載。但是考慮到調用者每次在加載前,都需要顯式調用check()方法進行檢查,難免會有遺漏。
所以采用第二種方法--設計模式中的緩存模式,代碼如下:
// 備忘錄模式: 防止重復加載export const loadWeChatJs = (() => { let exists = false; // 打點 const src = '//res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'; // 微信sdk網址 return () => new Promise((resolve, reject) => { // 防止重復加載 if(exists) return resolve(window.WxLogin); let script = document.createElement('script'); script.src = src; script.type = 'text/javascript'; script.onerror = reject; // TODO: 失敗時候, 可以移除script標簽 script.onload = () => { exists = true; resolve(window.WxLogin); }; document.body.appendChild(script); });})();
繪制登陸二維碼
根據《微信登陸開發指南》,將參數傳遞給window.WxLogin()即可。
// 微信默認配置const baseOption = { self_redirect: true, // true: 頁內iframe跳轉; false: 新標簽頁打開 id: 'wechat-container', appid: 'wechat-appid', scope: 'snsapi_login', redirect_uri: encodeURIComponent('//1.1.1.1/'), state: '',};export const loadQRCode = (option, intl = false, width, height) => { const _option = {...baseOption, ...option}; return new Promise((resolve, reject) => { try { window.WxLogin(_option); const ele = document.getElementById(_option['id']); const iframe = ele.querySelector('iframe'); iframe.width = width? width : '300'; iframe.height = height? height : '420'; // 處理國際化 intl && (iframe.src = iframe.src + '&lang=en'); resolve(true); } catch(error) { reject(error); } });};
在需要使用的業務組件中,可以在周期函數componentDidMount調用,下面是demo代碼:
componentDidMount() { const wxOption = { // ... }; loadWeChatJs() .then(WxLogin => loadQRCode(wxOption)) .catch(error => console.log(`Error: ${error.message}`)); }
回調網址與iframe通信
這一塊我覺得是微信登陸交互中最復雜和難以理解的一段邏輯。開頭有講過,微信二維碼渲染有2中方式,一種是打開新的標簽頁,另一種是在指定id的容器中插入iframe。
毫無疑問,第二種交互方式更友好,因為要涉及不同級層的頁面通信,代碼處理也更具挑戰。
為了方便說明,請先看模擬的數據配置:
// redirect 地址會被后端拿到, 后端重定向到此地址, 前端會訪問此頁面// redirect 地址中的參數, 是前端人員留給自己使用的; 后端會根據業務需要, 添加更多的字段, 然后一起返回前端const querystr = '?' + stringify({ redirect: encodeURIComponent(`${window.location.origin}/account/redirect?` + stringify({ to: encodeURIComponent(window.location.origin), origin: encodeURIComponent(window.location.origin), state: 'login' })), type: 'login'});const wxOption = { id: 'wechat-container', self_redirect: true, redirect_uri: encodeURIComponent(`//1.1.1.1/api/socials/weixin/authorizations${querystr}`) // 微信回調請求地址};
前后端、微信服務器、用戶端交互邏輯
按照上面的配置,我描述一下前端、用戶端、微信服務器和后端交互的邏輯:
跨Iframe通信
前面流程走完了,現在的情況是頁面中iframe的二維碼區域,已經被替換成了/account/redirect?...的內容。
為了實現通信,需要在頁面的周期中監聽message事件,并在組件卸載時,卸載此事件:
componentDidMount() { // ... ... window.addEventListener('message', this.msgReceive, false);}componentWillUnmount() { window.removeEventListener('message', this.msgReceive);}msgReceive(event) { // 監測是否是安全iframe if(!event.isTrusted) { return; } console.log(event.data); // 獲取iframe中傳來的數據, 進一步進行邏輯處理}
而在/account/redirect?...路由對應的組件中,我們需要解析路由中的params參數,按照業務邏輯檢查后,將結果傳遞給前面的頁面:
componentDidMount() { // step1: 獲取url中params參數 const querys = getQueryVariable(this.props.location.search); // step2: 檢查querys中的數據是否符合要求 ... // step3: 向頂級頁面傳遞消息 return window.parent && window.parent.postMessage('data', '*');}
至此,微信網頁認證的流程完成。
更多:關于iframe通信的更多細節,請查看MDN的文檔
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答