项目背景
因为项目采用前后端完全分离方案,所以,无法使用常规的微信授权登录作法,需要采用 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) } }) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
荐 http中status状态为canceled牵扯出的ajax一些问题
网友评论