微信小程序登录接口

master
heminjian502 2 years ago
parent 67d665d02a
commit 1556d05f5e

@ -38,6 +38,23 @@
<!-- 依赖声明 --> <!-- 依赖声明 -->
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<!-- 添加MySQL数据库驱动依赖包. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- 添加mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- SpringBoot的依赖配置--> <!-- SpringBoot的依赖配置-->
<dependency> <dependency>

@ -0,0 +1,48 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.req.GetOpenidReq;
import com.ruoyi.system.domain.req.LoginForMpReq;
import com.ruoyi.system.domain.resp.GetOpenidResp;
import com.ruoyi.system.service.IWechatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
*
*/
@RestController
@RequestMapping("/wechat/login")
public class WechatLoginController {
private static final Logger logger = LoggerFactory.getLogger(WechatLoginController.class);
@Resource
private IWechatService iWechatService;
/**
* @param
* @return
*/
@PostMapping("/get/openid")
public AjaxResult getWechatLoginInfo(@RequestBody GetOpenidReq getOpenidReq, HttpServletRequest request) {
logger.info("mp获取openid, req = [{}]", getOpenidReq);
GetOpenidResp resp = iWechatService.getOpenid(getOpenidReq, request);
return AjaxResult.success(resp);
}
@PostMapping("/for/mp")
public AjaxResult loginForMp(@RequestBody @Validated LoginForMpReq req) {
String token = iWechatService.loginForMp(req);
return AjaxResult.success(token);
}
}

@ -2,7 +2,7 @@
spring: spring:
datasource: datasource:
type: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver driverClassName: com.mysql.jdbc.Driver
druid: druid:
# 主库数据源 # 主库数据源
master: master:

@ -121,3 +121,7 @@ xss:
excludes: /system/notice excludes: /system/notice
# 匹配链接 # 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/* urlPatterns: /system/*,/monitor/*,/tool/*
wx:
mpAppId: wxcf05e06d4ab81582
mpSecret: 252594e6b980bc2bfc74bbaad92b5e7b

@ -0,0 +1,75 @@
package com.ruoyi.common.core.domain.entity;
import com.alibaba.fastjson.annotation.JSONField;
import java.io.Serializable;
public class AccessTokenVo implements Serializable {
private static final long serialVersionUID = -4331247900203620881L;
@JSONField(name = "access_token")
private String accessToken;
@JSONField(name = "expires_in")
private Integer expiresIn;
@JSONField(name = "errcode")
private Integer errCode;
@JSONField(name = "errmsg")
private String errMsg;
@JSONField(name = "userid")
private String userId;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public Integer getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
public Integer getErrCode() {
return errCode;
}
public void setErrCode(Integer errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "AccessTokenVo{" +
"accessToken='" + accessToken + '\'' +
", expiresIn=" + expiresIn +
", errCode=" + errCode +
", errMsg='" + errMsg + '\'' +
", userId='" + userId + '\'' +
'}';
}
}

@ -0,0 +1,9 @@
package com.ruoyi.common.utils.wechat;
public class WechatKeys {
public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
public static String MP_ACCESS_TOKEN_REDIS_KEY = "redis:mp:access:token:key";
public static String MP_CODE_TO_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
}

@ -0,0 +1,58 @@
package com.ruoyi.common.utils.wechat;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.AccessTokenVo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Component
public class WechatUtils {
private static final Logger logger = LoggerFactory.getLogger(WechatUtils.class);
/**
* AppID
*/
@Value("${wx.mpAppId}")
private String appId;
/**
* AppSecret
*/
@Value("${wx.mpSecret}")
private String appSecret;
@Autowired
private RedisCache redisCache;
/**
* access_token
* @return
*/
public String getMpAccessToken() {
String accessToken = redisCache.getCacheObject(WechatKeys.MP_ACCESS_TOKEN_REDIS_KEY);
if (StringUtils.isBlank(accessToken)) {
String accessTokenUrl = String.format(WechatKeys.ACCESS_TOKEN_URL, appId, appSecret);
String result = HttpUtils.sendGet(accessTokenUrl);
JSONObject jsonObject = JSONObject.parseObject(result);
AccessTokenVo accessTokenVo = JSONObject.toJavaObject(jsonObject, AccessTokenVo.class);
if (Objects.nonNull(accessTokenVo) && StringUtils.isNotBlank(accessTokenVo.getAccessToken())) {
accessToken = accessTokenVo.getAccessToken();
redisCache.setCacheObject(WechatKeys.MP_ACCESS_TOKEN_REDIS_KEY, accessTokenVo.getAccessToken(), accessTokenVo.getExpiresIn(), TimeUnit.SECONDS);
}
}
return accessToken;
}
}

@ -112,6 +112,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
.antMatchers("/webjars/**").anonymous() .antMatchers("/webjars/**").anonymous()
.antMatchers("/*/api-docs").anonymous() .antMatchers("/*/api-docs").anonymous()
.antMatchers("/druid/**").anonymous() .antMatchers("/druid/**").anonymous()
.antMatchers("/wechat/login/**").anonymous()
// 除上面外的所有请求全部需要鉴权认证 // 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()

@ -23,6 +23,47 @@
<artifactId>ruoyi-common</artifactId> <artifactId>ruoyi-common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
</dependencies> </dependencies>
<build>
<plugins>
<!--mybatis自动生成代码插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
<configuration>
<!--配置文件的位置-->
<configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>

@ -0,0 +1,125 @@
package com.ruoyi.system.domain;
import java.util.Date;
public class TWechatUser {
private Long id;
private Date lastLoginTime;
private String lastLoginIp;
private String nickname;
private String mobile;
private String avatar;
private String openid;
private String unionid;
private Byte status;
private Date addTime;
private Date updateTime;
private Long userId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp == null ? null : lastLoginIp.trim();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname == null ? null : nickname.trim();
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar == null ? null : avatar.trim();
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid == null ? null : openid.trim();
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid == null ? null : unionid.trim();
}
public Byte getStatus() {
return status;
}
public void setStatus(Byte status) {
this.status = status;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}

@ -0,0 +1,41 @@
package com.ruoyi.system.domain.req;
import java.io.Serializable;
/**
* @Description:
* @Author: chy
* @Date: 2022/5/24
**/
public class GetOpenidReq implements Serializable {
private static final long serialVersionUID = -1185015143654744140L;
private String nickName;
private String avatarUrl;
private String code;
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}

@ -0,0 +1,105 @@
package com.ruoyi.system.domain.req;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
public class LoginForMpReq implements Serializable {
private static final long serialVersionUID = -5482485655738769622L;
@NotBlank
private String openId;
@NotBlank
private String name;
@NotBlank
private String phone;
@NotBlank
private String sex;
/**
* yyyy-MM-dd
*/
private String birth;
private Integer height;
private Integer weight;
private String marriage;
private String disease;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getMarriage() {
return marriage;
}
public void setMarriage(String marriage) {
this.marriage = marriage;
}
public String getDisease() {
return disease;
}
public void setDisease(String disease) {
this.disease = disease;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
}

@ -0,0 +1,37 @@
package com.ruoyi.system.domain.resp;
import java.io.Serializable;
public class GetOpenidResp implements Serializable {
private static final long serialVersionUID = -8328911573370172974L;
private String openid;
private Boolean bindFlag = false;
private String token;
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Boolean getBindFlag() {
return bindFlag;
}
public void setBindFlag(Boolean bindFlag) {
this.bindFlag = bindFlag;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

@ -2,6 +2,7 @@ package com.ruoyi.system.mapper;
import java.util.List; import java.util.List;
import com.ruoyi.system.domain.TPatient; import com.ruoyi.system.domain.TPatient;
import tk.mybatis.mapper.common.Mapper;
/** /**
* Mapper * Mapper
@ -9,7 +10,7 @@ import com.ruoyi.system.domain.TPatient;
* @author ruoyi * @author ruoyi
* @date 2022-08-03 * @date 2022-08-03
*/ */
public interface TPatientMapper public interface TPatientMapper extends Mapper<TPatient>
{ {
/** /**
* *

@ -0,0 +1,18 @@
package com.ruoyi.system.mapper;
import com.ruoyi.system.domain.TWechatUser;
import tk.mybatis.mapper.common.Mapper;
public interface TWechatUserMapper extends Mapper<TWechatUser> {
int insert(TWechatUser record);
int insertSelective(TWechatUser record);
TWechatUser selectUserByPrimaryKey(Long id);
TWechatUser selectWechatUserByOpenid(String openid);
int updateByPrimaryKeySelective(TWechatUser record);
int updateByPrimaryKey(TWechatUser record);
}

@ -0,0 +1,14 @@
package com.ruoyi.system.service;
import com.ruoyi.system.domain.req.GetOpenidReq;
import com.ruoyi.system.domain.req.LoginForMpReq;
import com.ruoyi.system.domain.resp.GetOpenidResp;
import javax.servlet.http.HttpServletRequest;
public interface IWechatService {
GetOpenidResp getOpenid(GetOpenidReq req, HttpServletRequest request);
String loginForMp(LoginForMpReq req);
}

@ -0,0 +1,226 @@
package com.ruoyi.system.service.impl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* token
*
* @author ruoyi
*/
@Component
public class UserTokenService
{
// 令牌自定义标识
@Value("${token.header}")
private String header;
// 令牌秘钥
@Value("${token.secret}")
private String secret;
// 令牌有效期默认30分钟
@Value("${token.expireTime}")
private int expireTime;
protected static final long MILLIS_SECOND = 1000;
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
@Autowired
private RedisCache redisCache;
/**
*
*
* @return
*/
public LoginUser getLoginUser(HttpServletRequest request)
{
// 获取请求携带的令牌
String token = getToken(request);
if (StringUtils.isNotEmpty(token))
{
try
{
Claims claims = parseToken(token);
// 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
LoginUser user = redisCache.getCacheObject(userKey);
return user;
}
catch (Exception e)
{
}
}
return null;
}
/**
*
*/
public void setLoginUser(LoginUser loginUser)
{
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
{
refreshToken(loginUser);
}
}
/**
*
*/
public void delLoginUser(String token)
{
if (StringUtils.isNotEmpty(token))
{
String userKey = getTokenKey(token);
redisCache.deleteObject(userKey);
}
}
/**
*
*
* @param loginUser
* @return
*/
public String createToken(LoginUser loginUser)
{
String token = IdUtils.fastUUID();
loginUser.setToken(token);
setUserAgent(loginUser);
refreshToken(loginUser);
Map<String, Object> claims = new HashMap<>();
claims.put(Constants.LOGIN_USER_KEY, token);
return createToken(claims);
}
/**
* 20
*
* @param loginUser
* @return
*/
public void verifyToken(LoginUser loginUser)
{
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
{
refreshToken(loginUser);
}
}
/**
*
*
* @param loginUser
*/
public void refreshToken(LoginUser loginUser)
{
loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
// 根据uuid将loginUser缓存
String userKey = getTokenKey(loginUser.getToken());
redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
}
/**
*
*
* @param loginUser
*/
public void setUserAgent(LoginUser loginUser)
{
UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
loginUser.setIpaddr(ip);
loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
loginUser.setBrowser(userAgent.getBrowser().getName());
loginUser.setOs(userAgent.getOperatingSystem().getName());
}
/**
*
*
* @param claims
* @return
*/
private String createToken(Map<String, Object> claims)
{
String token = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret).compact();
return token;
}
/**
*
*
* @param token
* @return
*/
private Claims parseToken(String token)
{
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
/**
*
*
* @param token
* @return
*/
public String getUsernameFromToken(String token)
{
Claims claims = parseToken(token);
return claims.getSubject();
}
/**
* token
*
* @param request
* @return token
*/
private String getToken(HttpServletRequest request)
{
String token = request.getHeader(header);
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
{
token = token.replace(Constants.TOKEN_PREFIX, "");
}
return token;
}
private String getTokenKey(String uuid)
{
return Constants.LOGIN_TOKEN_KEY + uuid;
}
}

@ -0,0 +1,159 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.wechat.WechatKeys;
import com.ruoyi.system.domain.TPatient;
import com.ruoyi.system.domain.TWechatUser;
import com.ruoyi.system.domain.req.GetOpenidReq;
import com.ruoyi.system.domain.req.LoginForMpReq;
import com.ruoyi.system.domain.resp.GetOpenidResp;
import com.ruoyi.system.mapper.TPatientMapper;
import com.ruoyi.system.mapper.TWechatUserMapper;
import com.ruoyi.system.service.IWechatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Service
public class WechatServiceImpl implements IWechatService {
private static final Logger logger = LoggerFactory.getLogger(WechatServiceImpl.class);
/**
* AppID
*/
@Value("${wx.mpAppId}")
private String appId;
/**
* AppSecret
*/
@Value("${wx.mpSecret}")
private String appSecret;
@Resource
private TWechatUserMapper tWechatUserMapper;
@Resource
private TPatientMapper tPatientMapper;
@Resource
private UserTokenService userTokenService;
@Override
public GetOpenidResp getOpenid(GetOpenidReq req, HttpServletRequest request) {
//查询openid
String openid = queryOpenid(req);
TWechatUser wechatUser = updateWechatUser(openid, req, request);
GetOpenidResp resp = new GetOpenidResp();
if (Objects.isNull(wechatUser.getUserId())) {
resp.setBindFlag(false);
} else {
// 已绑定信息 直接登录
resp.setBindFlag(true);
TPatient tPatient = tPatientMapper.selectTPatientById(wechatUser.getUserId());
String token = buildTokenByPatient(tPatient);
resp.setToken(token);
}
resp.setOpenid(openid);
return resp;
}
@Override
public String loginForMp(LoginForMpReq req) {
// 查询手机号是否存在患者信息
TPatient tPatient = new TPatient();
BeanUtils.copyProperties(req, tPatient);
Example examplePatient = new Example(TWechatUser.class);
Example.Criteria criteriaPatient = examplePatient.createCriteria();
criteriaPatient.andEqualTo("phone", tPatient.getPhone());
List<TPatient> tPatients = tPatientMapper.selectByExample(examplePatient);
TWechatUser wechatUser = new TWechatUser();
if (!CollectionUtils.isEmpty(tPatients)) {
// 存在 需要把患者信息更新 并绑定openid
TPatient currentPatient = tPatients.get(0);
BeanUtils.copyProperties(req, currentPatient);
tPatientMapper.updateByPrimaryKeySelective(currentPatient);
wechatUser.setUserId(currentPatient.getId());
tPatient.setId(currentPatient.getId());
} else {
// 不存在 患者信息入库
tPatient.setDelFlag("0");
tPatient.setCreateTime(new Date());
tPatient.setUpdateTime(new Date());
tPatientMapper.insertTPatient(tPatient);
wechatUser.setUserId(tPatient.getId());
}
// 绑定openid
wechatUser.setOpenid(req.getOpenId());
Example example = new Example(TWechatUser.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("openid", wechatUser.getOpenid());
tWechatUserMapper.updateByExampleSelective(wechatUser, example);
// 登录获取token
String token = buildTokenByPatient(tPatient);
return token;
}
private String queryOpenid(GetOpenidReq req){
String url = String.format(WechatKeys.MP_CODE_TO_OPENID_URL, appId, appSecret, req.getCode());
String json = HttpUtils.sendGet(url);
JSONObject jsonObject = JSONObject.parseObject(json);
String session_key = (String) jsonObject.get("session_key");
String openid = (String) jsonObject.get("openid");
logger.info("login openid:{},session_key:{}", openid, session_key);
if (StringUtils.isEmpty(openid)) {
throw new ServiceException("未获取到openid");
}
return openid;
}
private TWechatUser updateWechatUser(String openid, GetOpenidReq req, HttpServletRequest request){
//查询当前微信用户是否存在
TWechatUser wechatUser = tWechatUserMapper.selectWechatUserByOpenid(openid);
if (wechatUser == null){
wechatUser = new TWechatUser();
wechatUser.setOpenid(openid);
wechatUser.setAvatar(req.getAvatarUrl());
wechatUser.setNickname(req.getNickName());
wechatUser.setLastLoginTime(new Date());
wechatUser.setLastLoginIp(IpUtils.getIpAddr(request));
wechatUser.setStatus((byte) 0);
tWechatUserMapper.insert(wechatUser);
}
wechatUser.setLastLoginTime(new Date());
wechatUser.setLastLoginIp(IpUtils.getIpAddr(request));
tWechatUserMapper.updateByPrimaryKeySelective(wechatUser);
return wechatUser;
}
private String buildTokenByPatient(TPatient tPatient) {
if (Objects.isNull(tPatient)) {
return StringUtils.EMPTY;
}
LoginUser loginUser = new LoginUser();
loginUser.setUserId(tPatient.getId());
SysUser user = new SysUser();
user.setUserId(tPatient.getId());
user.setDelFlag(tPatient.getDelFlag());
user.setSex(tPatient.getSex());
user.setPhonenumber(tPatient.getPhone());
loginUser.setUser(user);
String token = userTokenService.createToken(loginUser);
return token;
}
}

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.31.187:3306/tongue" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.ruoyi.system.domain" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper.system" targetProject="src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.ruoyi.system.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="t_wechat_user"
domainObjectName="TWechatUser"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>

@ -0,0 +1,180 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ruoyi.system.mapper.TWechatUserMapper" >
<resultMap id="BaseResultMap" type="com.ruoyi.system.domain.TWechatUser" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="last_login_time" property="lastLoginTime" jdbcType="TIMESTAMP" />
<result column="last_login_ip" property="lastLoginIp" jdbcType="VARCHAR" />
<result column="nickname" property="nickname" jdbcType="VARCHAR" />
<result column="mobile" property="mobile" jdbcType="VARCHAR" />
<result column="avatar" property="avatar" jdbcType="VARCHAR" />
<result column="openid" property="openid" jdbcType="VARCHAR" />
<result column="unionid" property="unionid" jdbcType="VARCHAR" />
<result column="status" property="status" jdbcType="TINYINT" />
<result column="add_time" property="addTime" jdbcType="TIMESTAMP" />
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
<result column="user_id" property="userId" jdbcType="BIGINT" />
</resultMap>
<sql id="Base_Column_List" >
id, last_login_time, last_login_ip, nickname, mobile, avatar, openid, unionid, status,
add_time, update_time, user_id
</sql>
<select id="selectUserByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select
<include refid="Base_Column_List" />
from t_wechat_user
where id = #{id,jdbcType=BIGINT}
</select>
<insert id="insert" parameterType="com.ruoyi.system.domain.TWechatUser" >
insert into t_wechat_user (id, last_login_time, last_login_ip,
nickname, mobile, avatar,
openid, unionid, status,
add_time, update_time, user_id
)
values (#{id,jdbcType=BIGINT}, #{lastLoginTime,jdbcType=TIMESTAMP}, #{lastLoginIp,jdbcType=VARCHAR},
#{nickname,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{avatar,jdbcType=VARCHAR},
#{openid,jdbcType=VARCHAR}, #{unionid,jdbcType=VARCHAR}, #{status,jdbcType=TINYINT},
#{addTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{userId,jdbcType=BIGINT}
)
</insert>
<insert id="insertSelective" parameterType="com.ruoyi.system.domain.TWechatUser" >
insert into t_wechat_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="lastLoginTime != null" >
last_login_time,
</if>
<if test="lastLoginIp != null" >
last_login_ip,
</if>
<if test="nickname != null" >
nickname,
</if>
<if test="mobile != null" >
mobile,
</if>
<if test="avatar != null" >
avatar,
</if>
<if test="openid != null" >
openid,
</if>
<if test="unionid != null" >
unionid,
</if>
<if test="status != null" >
status,
</if>
<if test="addTime != null" >
add_time,
</if>
<if test="updateTime != null" >
update_time,
</if>
<if test="userId != null" >
user_id,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=BIGINT},
</if>
<if test="lastLoginTime != null" >
#{lastLoginTime,jdbcType=TIMESTAMP},
</if>
<if test="lastLoginIp != null" >
#{lastLoginIp,jdbcType=VARCHAR},
</if>
<if test="nickname != null" >
#{nickname,jdbcType=VARCHAR},
</if>
<if test="mobile != null" >
#{mobile,jdbcType=VARCHAR},
</if>
<if test="avatar != null" >
#{avatar,jdbcType=VARCHAR},
</if>
<if test="openid != null" >
#{openid,jdbcType=VARCHAR},
</if>
<if test="unionid != null" >
#{unionid,jdbcType=VARCHAR},
</if>
<if test="status != null" >
#{status,jdbcType=TINYINT},
</if>
<if test="addTime != null" >
#{addTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null" >
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="userId != null" >
#{userId,jdbcType=BIGINT},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.ruoyi.system.domain.TWechatUser" >
update t_wechat_user
<set >
<if test="lastLoginTime != null" >
last_login_time = #{lastLoginTime,jdbcType=TIMESTAMP},
</if>
<if test="lastLoginIp != null" >
last_login_ip = #{lastLoginIp,jdbcType=VARCHAR},
</if>
<if test="nickname != null" >
nickname = #{nickname,jdbcType=VARCHAR},
</if>
<if test="mobile != null" >
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="avatar != null" >
avatar = #{avatar,jdbcType=VARCHAR},
</if>
<if test="openid != null" >
openid = #{openid,jdbcType=VARCHAR},
</if>
<if test="unionid != null" >
unionid = #{unionid,jdbcType=VARCHAR},
</if>
<if test="status != null" >
status = #{status,jdbcType=TINYINT},
</if>
<if test="addTime != null" >
add_time = #{addTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null" >
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="userId != null" >
user_id = #{userId,jdbcType=BIGINT},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.ruoyi.system.domain.TWechatUser" >
update t_wechat_user
set last_login_time = #{lastLoginTime,jdbcType=TIMESTAMP},
last_login_ip = #{lastLoginIp,jdbcType=VARCHAR},
nickname = #{nickname,jdbcType=VARCHAR},
mobile = #{mobile,jdbcType=VARCHAR},
avatar = #{avatar,jdbcType=VARCHAR},
openid = #{openid,jdbcType=VARCHAR},
unionid = #{unionid,jdbcType=VARCHAR},
status = #{status,jdbcType=TINYINT},
add_time = #{addTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
user_id = #{userId,jdbcType=BIGINT}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectWechatUserByOpenid" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from t_wechat_user
where openid = #{openid,jdbcType=VARCHAR}
</select>
</mapper>
Loading…
Cancel
Save