由于项目采用先后端彻底分离方案,因此,没法使用常规的微信受权登陆做法,须要采用 ajax 实现微信受权登陆。php
由于本人是一个phper ,因此,微信开发采用的是 EasyWeChat
,因此实现的方式是基于EW的。
其实实现这个也麻烦,在实现以前,咱们须要了解一下微信受权的整个流程。前端
其实说白了,前端只须要干一件事儿,引导用户发起微信受权页面,而后获得code
,而后跳转到当前页面,而后再请求后端换取用户以及其余相关信息。ajax
这里须要咱们作两件事,第一去配置jsapi域名,第二配置微信网页受权的回调域名
构建微信受权的url "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + location.href.split('#')[0] + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
咱们从链接中看到有两个变量,appId,以及 redirect_uri。appId 不用多说,就是我们将要受权的微信公众号的appId,另外一方个回调URL,其实就是咱们当前页面的URL。json
function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } function wxLogin(callback) { var appId = 'xxxxxxxxxxxxxxxxxxx'; var oauth_url = 'xxxxxxxxxxxxxxxxxxx/oauth'; var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + location.href.split('#')[0] + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect" var code = getUrlParam("code"); if (!code) { window.location = url; } else { $.ajax({ type: 'GET', url: oauth_url, dataType: 'json', data: { code: code }, success: function (data) { if (data.code === 200) { callback(data.data) } }, error: function (error) { throw new Error(error) } }) } }