ajax 实现微信网页授权登录

358 阅读2分钟
原文链接: segmentfault.com

项目背景

因为项目采用前后端完全分离方案,所以,无法使用常规的微信授权登录作法,需要采用 ajax 实现微信授权登录。

需求分析

因为本人是一个phper ,所以,微信开发采用的是 EasyWeChat ,所以实现的方式是基于EW的。
其实实现这个也麻烦,在实现之前,我们需要了解一下微信授权的整个流程。

  1. 引导用户进入授权页面同意授权,获取code
  2. 通过code换取网页授权access_token(与基础支持中的access_token不同)
  3. 如果需要,开发者可以刷新网页授权access_token,避免过期
  4. 通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

其实说白了,前端只需要干一件事儿,引导用户发起微信授权页面,然后得到code,然后跳转到当前页面,然后再请求后端换取用户以及其他相关信息。

功能实现

  1. 引导用户唤起微信授权确认页面
这里需要我们做两件事,第一去配置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。

  1. 用户微信登录授权以后回调过来的URL 会携带两个参数 ,第一个是code,另一个就是 state。才是我们需要做的一件事儿就是将code获取到然后传给后端,染后端通过code 获取用户基本信息。
  2. 后端得到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)
            }
        })
    }
}