直接進入正題
文檔地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
目前還未完成網頁授權,不過已經遇到問題了,借此記錄一下問題以及解決方法
目前我知道的是,我需要拿到一個code,
微信網頁授權第一步需要 用戶同意網頁授權
widow.location.href=https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_re
服務號獲得高級接口后,默認擁有scope參數中的snsapi_base和snsapi_userinfo
snsapi_base:靜默獲取用戶信息 (不需要用戶同意)只能獲取openid
snsapi_userinfo:需要用戶同意(彈出新頁面用戶點擊同意),可以獲取openid外,還可以獲取用戶名稱以及頭像
我這里用的是靜默獲取:(前提是在微信環境哦)
var url=encodeURIComponent(window.location.href); var getCodeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${'appid'}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=1#wechat_redirect`; window.location.href = getCodeUrl;
執行上述操作后,微信會跳轉到一個新頁面,這個頁面的地址上會有code參數
http://www.xxx.cn/param1/?code=xxxaxxxyPDFw1DAzxxx0EsxxxiSZ&state=1#/query1/1
這個地址上的code值就是我們想要的code
可是我原來的頁面地址是這樣的:
http://www.xxx.cn/param1/#/query1/1
微信把#號后面的參數混淆了(位置錯亂了,這在vue項目中是嚴重的,因為vue項目把#號后面的參數當做是路由,現在微信返回的路由錯亂,肯定會出問題)
我想要微信返回的是這樣的URI地址:
http://www.xxx.cn/param1/#/query1/1?code=xxxaxxxyPDFw1DAzxxx0EsxxxiSZ&state=1
最后我決定靜默把這個地址修復成我想要的url地址,並且頁面不發生刷新(利用window.history.pushState方法,和vue的hash路由原理一樣)
//把微信打亂的url地址靜默修復 var changeUrl=`${window.location.protocol}//${window.location.host}${window.location.pathname}${window.location.hash}${window.location.search}`; window.history.pushState({},0, changeUrl);
上述處理url之后頁面的url的地址就變成:(符合vue的hash路由模式的url地址)
http://www.xxx.cn/param1/#/query1/1?code=0xxx7s1gELxxx4xxdxxxs19xw7T&state=1
這樣的一個好處是不會再增加一次頁面的刷新
然后就可以繼續往后寫業務了
上一段代碼記錄一下:
async getWinxinCodeFun(huiyi_id){//獲得微信code var self=this;if(tools.getQuery("code")){ // 拿到code值 self.code=tools.getQuery("code"); //把微信打亂的url地址靜默修復 var changeUrl=`${window.location.protocol}//${window.location.host}${window.location.pathname}${window.location.hash}${window.location.search}`; window.history.pushState({},0, changeUrl); WXAPI.wxLogin(self.code).then((sucData)=>{//調用后台的微信登錄方法 self.commonLoginFun(sucData);//調用登錄成功后的公共方法 }) return; } var winxinConfig = await WXAPI.getWinxinCode(huiyi_id);//后端接口獲取appid什么的 var url=encodeURIComponent(window.location.href); var getCodeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${winxinConfig.appId}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=1#wechat_redirect`; window.location.href = getCodeUrl; },
tools.getQuery方法:
function getQuery(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; }
需要注意的是,拿到的code值只能使用一次,比如說,調用了微信登錄方法(后端寫的接口,會用到code查詢openid)之后,這個code就失效了,比如現在的項目想在登錄之后再存儲一下openid,那么這次
存儲就不能用上一次使用的code了,需要重新獲取code,總之code只能使用一次,否則會提示已經使用過了。
那么微信網頁授權的整體步驟就是:
第一步:用戶同意授權,獲取code
第二步:通過code換取網頁授權access_token
第三步:刷新access_token(如果需要)
第四步:拉取用戶信息(需scope為 snsapi_userinfo)
而我做了靜默授權,所以只用到了前兩步
。