前言
集成微信扫码登录的话,需要把项目的账号和微信账号进行绑定,然后才可以进行扫码登录
本篇内容是项目绑定微信
还需要申请一个微信开放平台账号
微信公众平台申请(测试平台)-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);@Autowiredprivate RedisTemplate<String,String> redisTemplate;@Autowiredprivate TokenService tokenService;@Autowiredprivate ISysUserService sysUserService;@Autowiredprivate 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;}/*** 微信授权回调接口* @param request* @param response* @throws Exception*/@RequestMapping(value = "/wx.do")public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {logger.error("WechatController ---- WechatController");System.out.println("========WechatController========= ");logger.info("请求进来了...");Enumeration pNames = request.getParameterNames();while (pNames.hasMoreElements()) {String name = (String) pNames.nextElement();String value = request.getParameter(name);String log = "name =" + name + " value =" + value;logger.error(log);}String signature = request.getParameter("signature");/// 微信加密签名String timestamp = request.getParameter("timestamp");/// 时间戳String nonce = request.getParameter("nonce"); /// 随机数String echostr = request.getParameter("echostr"); // 随机字符串PrintWriter out = response.getWriter();out.print(echostr);out.close();}}
service层实现getOpenid方法和updateUserOpenid方法
@Overridepublic SysUser getOpenid(String code) {RestTemplate restTemplate = new RestTemplate();JSONObject jsonData = null;// 构建获取access_token的URLString 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<String> 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<String> 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;}@Overridepublic int updateUserOpenid(SysUser sysUser) {int i = userMapper.updateUser(sysUser);return i;}
在配置文件中配置微信公众号信息
# 公众号配置
wechat:# 应用IDappid:# 应用密钥secret:
serviceImpl实现层新增属性
@Value("${wechat.appid}")
private String appId;@Value("${wechat.secret}")
private String secret;
mapper.xml更新
<resultMap type="com.ruoyi.system.domain.SysUser" id="SysUserResult">... <result property="wxNickName" column="wx_nick_name" /><result property="openid" column="openid" />...</resultMap><update id="updateUser" parameterType="SysUser">...<if test="openid != null and openid != ''">openid = #{openid},</if><if test="wxNickName != null and wxNickName != ''">wx_nick_name = #{wxNickName},</if>...
</update>
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/**
前端
修改ruoyi-ui/src/views/system/user/profile/userInfo.vue
<el-form-item label="微信"><span class="mr10">{{form.wxnickname || '未绑定'}}</span><el-button v-if="form.openid == '' || form.openid == null" :loading="bindloading" size="medium" type="primary" class="btn" @click.stop="wxBind()">绑 定</el-button><el-button v-else :loading="bindloading" size="medium" type="primary" class="btn" @click.stop="unBind()">解绑</el-button></el-form-item><el-dialog title="绑定微信" custom-class="bind-dialog" class="new-common-dialog" :visible.sync="bindWxVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="wxLoginClose" width="320px"><div class="qr-code"><vue-qr :text="qrUrl" :size="280"></vue-qr></div></el-dialog></el-form>
这里需要下载一个二维码的插件
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 = codeUrlconsole.log(this.qrUrl)this.bindWxVisible = truelet that = thisthis.timer = setInterval(function() {getUUid({uuid: key}).then((res) => {console.log(res)if (res.status === 1) {that.bindWxVisible = falsethat.form.openid = res.openidthat.form.wxnickname = res.wxnicknamethat.$message({type: 'success',message: '操作成功',})clearTimeout(this.timer)}}).catch((err) => {clearTimeout(that.timer)})}, 1000)},wxLoginClose() {this.timer && clearTimeout(this.timer)},
注意:回调地址一定要写对,公众号的回调地址要和这个保持一致,域名和开放接口也要和这个保持一致