項目背景
因為項目采用前后端完全分離方案,所以,無法使用常規的微信授權登錄作法,需要采用 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) } }) }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選