現在的網站開發,都繞不開微信登錄(畢竟微信已經成為國民工具)。雖然文檔已經寫得很詳細,但是對于沒有經驗的開發者還是容易踩坑。
所以,專門記錄一下微信網頁認證的交互邏輯,也方便自己日后回查:
微信網頁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。
新聞熱點
疑難解答