您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)怎么在Vue中使用abp實(shí)現(xiàn)一個(gè)微信掃碼登錄功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
生成登錄二維碼#
在vue登錄頁(yè)面嵌入登錄二維碼,根據(jù)官方文檔,在頁(yè)面中放入一個(gè)div元素,二維碼就放在此元素中,注意var obj = new WxLogin必須放在mounted方法中執(zhí)行,此時(shí)vue才會(huì)把dom元素初始化掛載到dom樹,可以參見(jiàn)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)訪問(wèn)前一步提供的redirect_uri,這里要監(jiān)控微信回調(diào),并用微信返回的code請(qǐng)求后端,在后端再去訪問(wèn)微信服務(wù)器獲取token及用戶openID
在回調(diào)頁(yè)面中監(jiān)控路由改變事件以監(jiān)控微信回調(diào)(因?yàn)槲业亩S碼和回調(diào)在同一個(gè)路由頁(yè)面),如果有其他更好的方法請(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)到主頁(yè) this.$router.replace({ path: "/", replace: true }); }).catch(error => { //保持當(dāng)前頁(yè)面 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/oauth3/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; } }
關(guān)于怎么在Vue中使用abp實(shí)現(xiàn)一個(gè)微信掃碼登錄功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。