新聞中心
這篇文章主要介紹ajax如何實(shí)現(xiàn)微信網(wǎng)頁授權(quán)登錄,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
項(xiàng)目背景
因?yàn)轫?xiàng)目采用前后端完全分離方案,所以,無法使用常規(guī)的微信授權(quán)登錄作法,需要采用 ajax 實(shí)現(xiàn)微信授權(quán)登錄。
需求分析
因?yàn)楸救耸且粋€(gè)phper ,所以,微信開發(fā)采用的是 EasyWeChat ,所以實(shí)現(xiàn)的方式是基于EW的。
其實(shí)實(shí)現(xiàn)這個(gè)也麻煩,在實(shí)現(xiàn)之前,我們需要了解一下微信授權(quán)的整個(gè)流程。
引導(dǎo)用戶進(jìn)入授權(quán)頁面同意授權(quán),獲取code
通過code換取網(wǎng)頁授權(quán)access_token(與基礎(chǔ)支持中的access_token不同)
如果需要,開發(fā)者可以刷新網(wǎng)頁授權(quán)access_token,避免過期
通過網(wǎng)頁授權(quán)access_token和openid獲取用戶基本信息(支持UnionID機(jī)制)
其實(shí)說白了,前端只需要干一件事兒,引導(dǎo)用戶發(fā)起微信授權(quán)頁面,然后得到code,然后跳轉(zhuǎn)到當(dāng)前頁面,然后再請求后端換取用戶以及其他相關(guān)信息。
功能實(shí)現(xiàn)
引導(dǎo)用戶喚起微信授權(quán)確認(rèn)頁面
這里需要我們做兩件事,第一去配置jsapi域名,第二配置微信網(wǎng)頁授權(quán)的回調(diào)域名
構(gòu)建微信授權(quán)的url "https://open.weixin.qq.com/connect/oauth3/authorize?appid=" + appId + "&redirect_uri=" + location.href.split('#')[0] + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
我們從連接中看到有兩個(gè)變量,appId,以及 redirect_uri。appId 不用多說,就是咱們將要授權(quán)的微信公眾號(hào)的appId,另一方個(gè)回調(diào)URL,其實(shí)就是我們當(dāng)前頁面的URL。
用戶微信登錄授權(quán)以后回調(diào)過來的URL 會(huì)攜帶兩個(gè)參數(shù) ,第一個(gè)是code,另一個(gè)就是 state。才是我們需要做的一件事兒就是將code獲取到然后傳給后端,染后端通過code 獲取用戶基本信息。
后端得到code 以后,獲取用戶基本信息,并返回相關(guān)其他信息給前端,前端獲取到然后做本地存儲(chǔ)或者其他。
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/oauth3/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) } }) }
以上是“ajax如何實(shí)現(xiàn)微信網(wǎng)頁授權(quán)登錄”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章名稱:ajax如何實(shí)現(xiàn)微信網(wǎng)頁授權(quán)登錄-創(chuàng)新互聯(lián)
網(wǎng)站URL:http://www.dlmjj.cn/article/doeojd.html