项目背景
项目采用前后端完全分离方案,因此无法使用常规的微信授权登录作法。
功能实现
引导用户唤起微信授权确认页面
前提配置
第一、去配置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:授权的微信公众号的appId
redirect_uri:当前页面的URL
前后逻辑
1、用户在微信浏览器访问前端页面,自动跳转到微信登录授权页面,授权成功后回调过来的URL会携带两个参数 ,第一个是code,另一个就是 state。
2、将code获取到然后传给后端,后端得到code 以后,获取用户基本信息,并返回相关其他信息给前端,前端获取到然后做本地存储或者其他。
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)
}
})
}
}相关技术: