项目背景
因为项目采用前后端完全分离方案,所以,无法使用常规的微信授权登录作法,需要采用 ajax 实现微信授权登录。
需求分析
因为本人是一个phper ,所以,微信开发采用的是 EasyWeChat ,所以实现的方式是基于EW的。
其实实现这个也麻烦,在实现之前,我们需要了解一下微信授权的整个流程。
其实说白了,前端只需要干一件事儿,引导用户发起微信授权页面,然后得到code,然后跳转到当前页面,然后再请求后端换取用户以及其他相关信息。
功能实现
引导用户唤起微信授权确认页面
这里需要我们做两件事,第一去配置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。
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)
}
})
}