集成微信扫码登录的话,需要把项目的账号和微信账号进行绑定,然后才可以进行扫码登录
本篇内容是项目绑定微信
还需要申请一个微信开放平台账号
微信公众平台申请(测试平台)-CSDN博客
平台的项目回调接口可以先不写,等写完项目再填
sys_user表新增字段
CacheConstants新增常量
/**
* 微信openid redis key
*/
public static final String WX_OPENID_KEY = "wx_openid:";
在system模块下新增WXController
@RequestMapping("/wei")
@RestController
public class WXController {
private static final Logger logger = LoggerFactory.getLogger(WXController.class);
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private TokenService tokenService;
@Autowired
private ISysUserService sysUserService;
@Autowired
private ISysPermissionService iSysPermissionService;
/**
* 获取openid
*/
@GetMapping("/bind-openid")
public AjaxResult getOpenid(@RequestParam("code") String code, @RequestParam("key") String key) throws IOException
{
AjaxResult ajax = AjaxResult.success();
SysUser u = sysUserService.getOpenid(code);
logger.info("获取到的用户信息对象:{]",u);
String openid = u.getOpenid();
String s = redisTemplate.opsForValue().get(CacheConstants.LOGIN_TOKEN_KEY + key);
JSONObject jsonObject = JSONObject.parseObject(s);
String string = jsonObject.getString("sysUser");
SysUser sysUser = JSONObject.parseObject(string, SysUser.class);
SysUser user = new SysUser();
user.setUserId(sysUser.getUserId());
user.setOpenid(openid);
user.setWxNickName(u.getWxNickName());
sysUserService.updateUserOpenid(user);
ajax.put("openid", openid);
ajax.put("wxnickname", u.getWxNickName());
return ajax;
}
/**
* 已登录用户uuid查询openid
*/
@GetMapping("/uuid")
public AjaxResult getCode(@RequestParam("uuid") String uuid) throws IOException
{
AjaxResult ajax = AjaxResult.success();
String s = redisTemplate.opsForValue().get(CacheConstants.LOGIN_TOKEN_KEY + uuid);
JSONObject jsonObject = JSONObject.parseObject(s);
String string = jsonObject.getString("sysUser");
SysUser sysUser = JSONObject.parseObject(string, SysUser.class);
SysUser user = sysUserService.selectUserById(sysUser.getUserId());
System.out.println("user-openid: " + user.getOpenid());
System.out.println("user-wxnickname: " + user.getWxNickName());
if (user.getOpenid() != null) {
ajax.put("openid", user.getOpenid());
ajax.put("wxnickname", user.getWxNickName());
}
ajax.put("status", user.getOpenid() != null && !user.getOpenid().isEmpty() ? 1: 0);
return ajax;
}
}
service层实现getOpenid方法和updateUserOpenid方法
@Override
public SysUser getOpenid(String code) {
RestTemplate restTemplate = new RestTemplate();
JSONObject jsonData = null;
// 构建获取access_token的URL
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
+ "appid=" + appId
+ "&secret=" + secret
+ "&code=" + code
+ "&grant_type=authorization_code";
System.out.println("url: " + url);
ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
System.out.println("responseEntity: " + responseEntity);
if (responseEntity.getStatusCodeValue() == 200 && responseEntity.getBody() != null) {
jsonData = JSONObject.parseObject(responseEntity.getBody());
}
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN"
+ "&access_token=" + jsonData.getString("access_token")
+ "&openid=" + jsonData.getString("openid");
ResponseEntity responseUserEntity = restTemplate.getForEntity(userInfoUrl, String.class);
if (responseUserEntity.getStatusCodeValue() == 200 && responseUserEntity.getBody() != null) {
JSONObject jsonUserData = JSONObject.parseObject(new String(responseUserEntity.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
System.out.println("jsonUserData: " + jsonUserData);
SysUser user = new SysUser();
user.setOpenid(jsonUserData.getString("openid"));
user.setWxNickName(jsonUserData.getString("nickname"));
return user;
}
return null;
}
@Override
public int updateUserOpenid(SysUser sysUser) {
int i = userMapper.updateUser(sysUser);
return i;
}
在配置文件中配置微信公众号信息
# 公众号配置
wechat:
# 应用ID
appid:
# 应用密钥
secret:
serviceImpl实现层新增属性
@Value("${wechat.appid}")
private String appId;
@Value("${wechat.secret}")
private String secret;
mapper.xml更新
...
...
...
openid = #{openid},
wx_nick_name = #{wxNickName},
...
select u.user_id, u.dept_id, u.user_name, u.nick_name, u.email, u.avatar, u.phonenumber, u.password, u.sex, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark,
u.openid,u.wx_nick_name,
d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.status as dept_status,
r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status
from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
SysUser更新
/** 用户微信昵称 */
@Excel(name = "用户微信昵称")
private String wxNickName;
/** openid */
@Excel(name = "openid")
private String openid;
public String getOpenid()
{
return openid;
}
public void setOpenid(String openid)
{
this.openid = openid;
}
public String getWxNickName()
{
return wxNickName;
}
public void setWxNickName(String wxNickName)
{
this.wxNickName = wxNickName;
}
网关记得放行路径,我直接放行/wei/**
新增js方法 /api/system/wei.js
import request from '@/utils/request'
// 查询用户列表
export function getUUid(data) {
return request({
url: '/system/wei/uuid?uuid=' + data.uuid,
method: 'get'
})
}
修改ruoyi-ui/src/views/system/user/profile/userInfo.vue
{{form.wxnickname || '未绑定'}}
绑 定
解
绑
这里需要下载一个二维码的插件
npm install vue-qr --save
引入组件
components: {
vueQr,
},
导入依赖以及方法
import { updateUserProfile } from "@/api/system/user";
import { getUUid } from '@/api/system/wei'
import { getToken } from '@/utils/auth'
import vueQr from 'vue-qr'
data新增属性
timer: null,
bindWxVisible: false,
bindloading: false,
qrUrl: '',
修改user方法
user: {
handler(user) {
console.log('user', this.user)
if (user) {
this.form = {
nickName: user.nickName,
wxnickname: user.wxNickName,
phonenumber: user.phonenumber,
email: user.email,
sex: user.sex,
openid: user.openid
};
}
},
immediate: true
}
新增微信绑定方法
wxBind() {
let token = getToken()
console.log(token)
const key = JSON.parse(atob(token.split('.')[1]))['user_key'];
const redirect_uri = `${公网ip或域名}/system/wei/bind-openid?key=${key}` //回调地址
const codeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${微信公众号appid}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_userinfo&state=123456#wechat_redirect`
this.qrUrl = codeUrl
console.log(this.qrUrl)
this.bindWxVisible = true
let that = this
this.timer = setInterval(function() {
getUUid({
uuid: key
})
.then((res) => {
console.log(res)
if (res.status === 1) {
that.bindWxVisible = false
that.form.openid = res.openid
that.form.wxnickname = res.wxnickname
that.$message({
type: 'success',
message: '操作成功',
})
clearTimeout(this.timer)
}
})
.catch((err) => {
clearTimeout(that.timer)
})
}, 1000)
},
wxLoginClose() {
this.timer && clearTimeout(this.timer)
},
注意:回调地址一定要写对,公众号的回调地址要和这个保持一致,域名和开放接口也要和这个保持一致