Vue+abp微信掃碼登錄的實(shí)現(xiàn)代碼示例
最近系統(tǒng)中要使用微信掃碼登錄,根據(jù)微信官方文檔和網(wǎng)絡(luò)搜索相關(guān)文獻(xiàn)實(shí)現(xiàn)了。分享給需要的人,也作為自己的一個(gè)筆記。后端系統(tǒng)是基于ABP的,所以部分代碼直接使用了abp的接口,直接拷貝代碼編譯不通過。
注冊(cè)微信開放平臺(tái)賬號(hào)#
在微信開放平臺(tái)注冊(cè),注意是開放平臺(tái)不是公眾平臺(tái),這里需要300元,然后申請(qǐng)網(wǎng)站應(yīng)用。審核通過后獲取到AppID和AppSecret以及登記的網(wǎng)站url。只有此url下的地址微信掃碼后才能回調(diào)。
具體申請(qǐng)條件見官方文檔。
生成登錄二維碼#
在vue登錄頁面嵌入登錄二維碼,根據(jù)官方文檔,在頁面中放入一個(gè)div元素,二維碼就放在此元素中,注意var obj = new WxLogin必須放在mounted方法中執(zhí)行,此時(shí)vue才會(huì)把dom元素初始化掛載到dom樹,可以參見vue官方文檔生命周期介紹。
<template> <div id="login" class="login"></div> </template> <script> export default { name: "WXLogin", data: function() { return {}; }, mounted() { this.wechatHandleClick(); document.getElementsByTagName("iframe")[0].height="320"; document.getElementsByTagName("iframe")[0].style.marginLeft="30px"; }, methods: { wechatHandleClick() { let ba64Css = "css代碼base64編碼";// 微信需要https的樣式路徑,這里將樣式內(nèi)容加密base64,可以避免使用https,如果你的網(wǎng)站是https的可以直接使用安官方文檔使用css文件路徑 const appid = "你第一步申請(qǐng)的Appid"; const redirect_uri = encodeURIComponent("http://*/#/login"); var obj = new WxLogin({ id: "login", //div的id appid: appid, scope: "snsapi_login",//固定內(nèi)容 redirect_uri: redirect_uri, //回調(diào)地址 // href: "http://*/static/UserCss/WeChart.css" //自定義樣式鏈接,第三方可根據(jù)實(shí)際需求覆蓋默認(rèn)樣式。 href: "data:text/css;base64," + ba64Css // state: "", //參數(shù),可帶可不帶 // style: "", //樣式 提供"black"、"white"可選,默認(rèn)為黑色文字描述 }); } } }; </script>
注冊(cè)回調(diào)事件#
用戶掃碼后微信會(huì)回調(diào)訪問前一步提供的redirect_uri,這里要監(jiān)控微信回調(diào),并用微信返回的code請(qǐng)求后端,在后端再去訪問微信服務(wù)器獲取token及用戶openID
在回調(diào)頁面中監(jiān)控路由改變事件以監(jiān)控微信回調(diào)(因?yàn)槲业亩S碼和回調(diào)在同一個(gè)路由頁面),如果有其他更好的方法請(qǐng)告訴我。
@Watch("$route") async RouteChange(newVal, oldVal) { await this.weixinRedirect(); } // 請(qǐng)求微信后臺(tái) async weixinRedirect() { let code = this.$route.query.code; let state = this.$route.query.state; if (code) { let wxTo = { code, state }; //請(qǐng)求后臺(tái) this.$http("*/WeixinRedirect",data:wxTo).then((token)=>{ //登錄成功,把token寫入cookie //跳轉(zhuǎn)到主頁 this.$router.replace({ path: "/", replace: true }); }).catch(error => { //保持當(dāng)前頁面 this.$router.replace({ path: "/login", replace: true }); }); } } }
后端接收code請(qǐng)求token#
在appsettings.json中配置AppId和AppSecret
[HttpPost] public async Task<AuthenticateResultModel> WeixinRedirect(string code, string state) { if (code.IsNullOrEmpty()) { throw new UserFriendlyException("微信授權(quán)失敗,請(qǐng)重新授權(quán)"); } var appid = configuration["Authentication:Wechat:AppId"]; var secret = configuration["Authentication:Wechat:AppSecret"]; var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code=[code]&grant_type=authorization_code"; var httpClient = httpClientFactory.CreateClient(); httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); httpClient.Timeout = TimeSpan.FromMinutes(3); var resstr = await httpClient.GetStringAsync(url); try{ //如果微信授權(quán)返回失敗這里序列化不成功 var res = JsonSerializationHelper.DeserializeWithType<WeiXinAccess_tokenResponse>(resstr); }catch (Exception e) { throw new UserFriendlyException("獲取微信access_token失敗"); } if (res == null || res.openid.IsNullOrEmpty()) { throw new UserFriendlyException("獲取微信access_token失敗"); } var userId = //根據(jù)openID獲取用戶id,我們系統(tǒng)要求用戶提前把微信和用戶關(guān)聯(lián)綁定,所以這里可以根據(jù)微信用戶的openID獲取到戶農(nóng)戶id; //使用用戶直接登錄 if (!userId.IsNullOrEmpty()&&long.TryParse(userId, out long id)) { var user = await _userManager.GetUserByIdAsync(id); var loginResult = await _logInManager.LoginByUser(user); string accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)); return new AuthenticateResultModel { AccessToken = accessToken, EncryptedAccessToken = GetEncrpyedAccessToken(accessToken), ExpireInSeconds = (int)_tokenConfiguration.Expiration.TotalSeconds, UserId = loginResult.User.Id }; } throw new UserFriendlyException("微信尚未綁定賬號(hào),請(qǐng)使用賬號(hào)登錄后綁定微信。"); }
WeiXinAccess_tokenResponse類型
public class WeiXinAccess_tokenResponse { public string access_token { get; set; } public int expires_in { get; set; } public string refresh_token { get; set; } public string openid { get; set; } public string scope { get; set; } public string unionid { get; set; } }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
瀏覽器事件循環(huán)與vue nextTicket的實(shí)現(xiàn)
這篇文章主要介紹了瀏覽器事件循環(huán)(結(jié)合vue nextTicket)的實(shí)現(xiàn)方法,需要的朋友可以參考下2019-04-04解決removeEventListener 無法清除監(jiān)聽的問題
這篇文章主要介紹了解決removeEventListener 無法清除監(jiān)聽的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-10-10Vue中實(shí)現(xiàn)父子組件雙向數(shù)據(jù)流的三種方案分享
通常情況下,父子組件的通信都是單向的,或父組件使用props向子組件傳遞數(shù)據(jù),或子組件使用emit函數(shù)向父組件傳遞數(shù)據(jù),本文將嘗試講解Vue中常用的幾種雙向數(shù)據(jù)流的使用,需要的朋友可以參考下2023-08-08Vue2組件tree實(shí)現(xiàn)無限級(jí)樹形菜單
這篇文章主要為大家詳細(xì)介紹了Vue2組件tree實(shí)現(xiàn)無限級(jí)樹形菜單,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03vue自定義密碼輸入框解決瀏覽器自動(dòng)填充密碼的問題(最新方法)
這篇文章主要介紹了vue自定義密碼輸入框解決瀏覽器自動(dòng)填充密碼的問題,通過將密碼輸入框的type設(shè)置為text,修改樣式上的顯示,來實(shí)現(xiàn)既可以讓瀏覽器不自動(dòng)填充密碼,又可以隱藏密碼的效果,需要的朋友可以參考下2023-04-04Vue 2.0的數(shù)據(jù)依賴實(shí)現(xiàn)原理代碼簡析
本篇文章主要介紹了Vue 2.0的數(shù)據(jù)依賴實(shí)現(xiàn)原理代碼簡析,主要從初始化的數(shù)據(jù)層面上分析了Vue是如何管理依賴來到達(dá)數(shù)據(jù)的動(dòng)態(tài)響應(yīng),有興趣的可以了解一下2017-07-07Vue中如何點(diǎn)擊獲取當(dāng)前元素下標(biāo)
這篇文章主要介紹了Vue中如何點(diǎn)擊獲取當(dāng)前元素下標(biāo)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05