当前位置:网站首页>YYGH-6-微信登录
YYGH-6-微信登录
2022-06-28 05:41:00 【小赵呢】
微信登录
OAuth2
OAuth主要角色
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-12GDjZFr-1655189829138)(C:\Users\86157\AppData\Local\Temp\1655184328495.png)]](/img/05/8b2108fff58f828a0b9e99b8c6f7d2.png)
现代微服务中系统微服务化以及应用的形态和设备类型增多,不能用传统的登录方式
核心的技术不是用户名和密码,而是token,由AuthServer颁发token,用户使用token进行登录
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BIXwbTIQ-1655189829140)(C:\Users\86157\AppData\Local\Temp\1655184374095.png)]](/img/c6/45bc4d6d1edd66239952c6a7994b50.png)
前期准备
这个是微信登录的开发平台
微信开放平台:https://open.weixin.qq.com
授权的流程
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pxwqopxv-1655189829140)(C:\Users\86157\AppData\Local\Temp\1655184453682.png)]](/img/f6/94930b23dffff68f57e20053e4855d.png)
我们现在需要将二维码内嵌到网页当中
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QGBk33YD-1655189829141)(C:\Users\86157\AppData\Local\Temp\1655184628715.png)]](https://img-blog.csdnimg.cn/5cae0fed6f5c4a8d8e9246f6d9b3e667.png)
生成二维码
getLoginParam() {
return request({
url: `${
api_name}/getLoginParam`,
method: `get`,
})
}
这是发送请求的js
后端写一个接口来接收这个
//1.生成微信二维码
//返回生成二维码需要的参数
@GetMapping("getLoginParam")
@ResponseBody
public Result getQrConnect() {
try {
Map<String, Object> map = new HashMap<>();
map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
map.put("scope", "snsapi_login");
String wxOpenRedirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
map.put("redirectUri", wxOpenRedirectUrl);
map.put("state", System.currentTimeMillis() + "");
return Result.ok(map);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
Controller用到的帮助类
@Component
public class ConstantWxPropertiesUtils implements InitializingBean {
@Value("${wx.open.app_id}")
private String appId;
@Value("${wx.open.app_secret}")
private String appSecret;
@Value("${wx.open.redirect_url}")
private String redirectUrl;
@Value("${yygh.baseUrl}")
private String yyghBaseUrl;
public static String WX_OPEN_APP_ID;
public static String WX_OPEN_APP_SECRET;
public static String WX_OPEN_REDIRECT_URL;
public static String YYGH_BASE_URL;
@Override
public void afterPropertiesSet() throws Exception {
WX_OPEN_APP_ID = appId;
WX_OPEN_APP_SECRET = appSecret;
WX_OPEN_REDIRECT_URL = redirectUrl;
YYGH_BASE_URL = yyghBaseUrl;
}
}
properties配置类
# 微信登录的配置文件
wx.open.app_id=wxed9954c01bb89b47
wx.open.app_secret=a7482517235173ddb4083788de60b90e
wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
yygh.baseUrl=http://localhost:3000
vue前端
weixinLogin() {
this.dialogAtrr.showLoginType = 'weixin'
weixinApi.getLoginParam().then(response => {
var obj = new WxLogin({
self_redirect:true,
id: 'weixinLogin', // 需要显示的容器id
appid: response.data.appid, // 公众号appid wx*******
scope: response.data.scope, // 网页默认即可
redirect_uri: response.data.redirectUri, // 授权成功后回调的url
state: response.data.state, // 可设置为简单的随机数加session用来校验
style: 'black', // 提供"black"、"white"可选。二维码的样式
href: '' // 外部css文件url,需要https
})
})
},
这样就可以生成二维码了
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LCHV9bvZ-1655189829142)(C:\Users\86157\AppData\Local\Temp\1655185533504.png)]](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
虽然说现在有二维码了但是现在在手机上登录之后也不好进行校验,会报错404
登录逻辑
第一步从回调url中取出code
wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
通过配置文件当中的这个描述我们可以知道现在在扫描完二维码之后会回调这个方法,于是我们来写一下这个方法.
我们的需求是扫描以后获得用户昵称,还有openid存放到数据库中
在官方文档当中我们知道了,回调函数是通过Get请求提交的,同时还附带了2个参数code和state
code=CODE&state=STATE
于是我们的方法就写成这样
//0.微信扫描后回调的方法
@GetMapping("callback")
public String callback(String code, String state) throws UnsupportedEncodingException {
}
第二步通过code获取access_token
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7B1TeQbY-1655189829143)(C:\Users\86157\AppData\Local\Temp\1655186508267.png)]](/img/8c/709ae96e34a94f04f138d179a5caed.png)
第三步通过access_token获取登录人的信息
下面我们来在业务层中实现这些
//0.微信扫描后回调的方法
@GetMapping("callback")
public String callback(String code, String state) throws UnsupportedEncodingException {
log.info("code为" + code);
log.info("state为" + state);
//获取code
//拿着code和微信id和密钥,请求微信的固定地址
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code";
String accesstokenInfo = restTemplate.getForObject(url, String.class, ConstantWxPropertiesUtils.WX_OPEN_APP_ID, ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET, code);
log.info("accesstokenInfo为" + accesstokenInfo);
//把accesstokenInfo封装成一个json对象
JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
String accessToken = jsonObject.getString("access_token");
String openid = jsonObject.getString("openid");
UserInfo userInfo = userInfoService.selectByOpenid(openid);
//判断现在是否已经有了这个微信用户
if (userInfo == null) {
//拿着accessToken,openid请求微信地址得到扫描人的信息
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}";
String userVoInfo = restTemplate.getForObject(userInfoUrl, String.class, accessToken, openid);
log.info(userVoInfo);
JSONObject userVoObject = JSONObject.parseObject(userVoInfo);
//用户昵称
String nickname = userVoObject.getString("nickname");
//用于昵称是windows1252格式转换为utf-8
nickname = new String(nickname.getBytes("windows-1256"),"UTF-8");
log.info("nickname为" + nickname);
//用户头像
String headimgurl = jsonObject.getString("headimgurl");
userInfo = new UserInfo();
userInfo.setNickName(nickname);
userInfo.setOpenid(openid);
//返回name和token字符串
userInfo.setStatus(1);
userInfoService.save(userInfo);
}
Map<String, Object> map = new HashMap<>();
String name = userInfo.getName();
if (StringUtils.isEmpty(name)) {
name = userInfo.getNickName();
}
if (StringUtils.isEmpty(name)) {
name = userInfo.getPhone();
}
map.put("name", name);
//判断是否有手机号,如果手机号为空,返回openid
//如果手机号不为空返回openid值为空字符串
//前端判断,如果openid不为空需要绑定手机号,如果openid为空不需要绑定手机号
if (StringUtils.isEmpty(userInfo.getPhone())) {
map.put("openid", userInfo.getOpenid());
} else {
map.put("openid", "");
}
//使用jwt生成token
String token = JwtHelper.createToken(userInfo.getId(), name);
map.put("token", token);
return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?token=" + map.get("token") + "&openid=" + map.get("openid") + "&name=" + URLEncoder.encode((String) map.get("name"), "utf-8");
}
userInfoservice也做了一定的调整
@Override
public UserInfo selectByOpenid(String openid) {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("openid", openid);
UserInfo userInfo = baseMapper.selectOne(queryWrapper);
return userInfo;
}
在进行登录接口保存用户时也需要根据openid来判断用户是微信用户还是邮箱用户如果是微信登录那么也是需要绑定微信的.
//绑定手机号
UserInfo userInfo = null;
if (!StringUtils.isEmpty(loginVo.getOpenid())) {
userInfo = this.selectByOpenid(loginVo.getOpenid());
if (null != userInfo) {
userInfo.setPhone(loginVo.getPhone());
this.updateById(userInfo);
} else {
throw new YyghException(ResultCodeEnum.DATA_ERROR);
}
}
这样就实现了我们的功能
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6kG3tr4N-1655189829143)(C:\Users\86157\AppData\Local\Temp\1655189775650.png)]](/img/88/0bcb819ddf0d4adc34398f54501173.png)
边栏推荐
- Video tutorial on website operation to achieve SEO operation [21 lectures]
- 1404. 将二进制表示减到1的步骤数
- WordPress zibll sub theme 6.4.1 happy version is free of authorization
- Filecoin黑客松开发者大赛
- jq图片放大器
- 2022 new version NFT source code source code of China meta universe digital collection art trading platform
- PS effect understanding record 2 color_ dodge color_ burn
- Animation de ligne
- JSP connecting Oracle to realize login and registration
- Install fmpefg
猜你喜欢

双向电平转换电路

Drop down box for implementation

What does mysql---where 1=1 mean

Gee learning notes 3- export table data

JSP connects with Oracle to realize login and registration (simple)

Filecoin hacker song developer competition
![[C language practice - printing hollow square and its deformation]](/img/59/9122a6c8437f12bc28c97304ba9787.png)
[C language practice - printing hollow square and its deformation]

Codeworks 5 questions per day (1700 for each)

Bidirectional level conversion circuit

线条动画
随机推荐
numpy.reshape, numpy.transpose的理解
电商转化率这么抽象,到底是个啥?
函数栈帧的创建和销毁
Zzuli:1072 frog climbing well
Install kubebuilder
JSP connects with Oracle to realize login and registration (simple)
【MYSQL】所有查询表中有2千万数据--sql如何优化
UICollectionViewDiffableDataSource及NSDiffableDataSourceSnapshot使用介绍
MySQL 45 talk | 05 explain the index in simple terms (Part 2)
Video tutorial on website operation to achieve SEO operation [21 lectures]
Filecoin hacker song developer competition
Data warehouse: DWS layer design principle
Codeworks 5 questions per day (1700 for each)
马赛克数据增强 mosaic
若依实现下拉框
Ape pink ape power - Developer activity attack!
Detailed usage configuration of the shutter textbutton, overview of the shutter buttonstyle style and Practice
Introduction to uicollectionviewdiffabledatasource and nsdiffabledatasourcesnapshot
容量调度绝对值配置队列使用与避坑
jq图片放大器