最近系统中要使用微信扫码登录,根据微信官方文档和网络搜索相关文献实现了。分享给需要的人,也作为自己的一个笔记。后端系统是基于ABP的,所以部分代码直接使用了abp的接口,直接拷贝代码编译不通过。
注册微信开放平台账号
在微信开放平台注册,注意是开放平台不是公众平台,这里需要300元,然后申请网站应用。审核通过后获取到AppID和AppSecret以及登记的网站url。只有此url下的地址微信扫码后才能回调。 具体申请条件见官方文档。
生成登录二维码
在vue登录页面嵌入登录二维码,根据官方文档,在页面中放入一个div元素,二维码就放在此元素中,注意var obj = new WxLogin必须放在mounted方法中执行,此时vue才会把dom元素初始化挂载到dom树,可以参见vue官方文档生命周期介绍。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<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的样式路径,这里将样式内容加密base64,可以避免使用https,如果你的网站是https的可以直接使用安官方文档使用css文件路径
const appid = "你第一步申请的Appid";
const redirect_uri = encodeURIComponent("http://*/#/login");
var obj = new WxLogin({
id: "login", //div的id
appid: appid,
scope: "snsapi_login",//固定内容
redirect_uri: redirect_uri, //回调地址
// href: "http://*/static/UserCss/WeChart.css" //自定义样式链接,第三方可根据实际需求覆盖默认样式。
href: "data:text/css;base64," + ba64Css
// state: "", //参数,可带可不带
// style: "", //样式 提供"black"、"white"可选,默认为黑色文字描述
});
}
}
};
</script>
注册回调事件
用户扫码后微信会回调访问前一步提供的redirect_uri,这里要监控微信回调,并用微信返回的code请求后端,在后端再去访问微信服务器获取token及用户openID 在回调页面中监控路由改变事件以监控微信回调(因为我的二维码和回调在同一个路由页面),如果有其他更好的方法请告诉我。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Watch("$route")
async RouteChange(newVal, oldVal) {
await this.weixinRedirect();
}
// 请求微信后台
async weixinRedirect() {
let code = this.$route.query.code;
let state = this.$route.query.state;
if (code) {
let wxTo = {
code,
state
};
//请求后台
this.$http("*/WeixinRedirect",data:wxTo).then((token)=>{
//登录成功,把token写入cookie
//跳转到主页
this.$router.replace({ path: "/", replace: true });
}).catch(error => {
//保持当前页面
this.$router.replace({ path: "/login", replace: true });
});
}
}
}
后端接收code请求token
在appsettings.json中配置AppId和AppSecret
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
[HttpPost]
public async Task<AuthenticateResultModel> WeixinRedirect(string code, string state)
{
if (code.IsNullOrEmpty())
{
throw new UserFriendlyException("微信授权失败,请重新授权");
}
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{
//如果微信授权返回失败这里序列化不成功
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 = //根据openID获取用户id,我们系统要求用户提前把微信和用户关联绑定,所以这里可以根据微信用户的openID获取到户农户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("微信尚未绑定账号,请使用账号登录后绑定微信。");
}
WeiXinAccess_tokenResponse类型
1
2
3
4
5
6
7
8
9
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; }
}
本文会经常更新,请阅读原文: https://dashenxian.github.io/post/Vue+abp%E5%BE%AE%E4%BF%A1%E6%89%AB%E7%A0%81%E7%99%BB%E5%BD%95 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com) 。