现在的网站开发,都绕不开微信登录(毕竟微信已经成为国民工具)。虽然文档已经写得很详细,但是对于没有经验的开发者还是容易踩坑。
所以,专门记录一下微信网页认证的交互逻辑,也方便自己日后回查:
微信网页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。
新闻热点
疑难解答