Commit ee40adaa authored by 廖旭伟's avatar 廖旭伟

等保三级

parent 7816fad7
package com.mortals.xhx.base.system.user.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.base.system.user.model.UserPwdRecordEntity;
/**
* 用户密码修改记录Dao
* 用户密码修改记录 DAO接口
*
* @author zxfei
* @date 2023-07-26
*/
public interface UserPwdRecordDao extends ICRUDDao<UserPwdRecordEntity,Long>{
}
package com.mortals.xhx.base.system.user.dao.ibatis;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import com.mortals.xhx.base.system.user.dao.UserPwdRecordDao;
import com.mortals.xhx.base.system.user.model.UserPwdRecordEntity;
import org.springframework.stereotype.Repository;
/**
* 用户密码修改记录DaoImpl DAO接口
*
* @author zxfei
* @date 2023-07-26
*/
@Repository("userPwdRecordDao")
public class UserPwdRecordDaoImpl extends BaseCRUDDaoMybatis<UserPwdRecordEntity,Long> implements UserPwdRecordDao {
}
package com.mortals.xhx.base.system.user.model;
import com.mortals.xhx.base.system.user.model.vo.UserPwdRecordVo;
import lombok.Data;
/**
* 用户密码修改记录实体对象
*
* @author zxfei
* @date 2023-07-26
*/
@Data
public class UserPwdRecordEntity extends UserPwdRecordVo {
private static final long serialVersionUID = 1L;
/**
* 用户ID,主键,自增长
*/
private Long userId;
/**
* 登录名
*/
private String loginName;
/**
* 登录密码,使用md5双次加密
*/
private String loginPwd;
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof UserPwdRecordEntity) {
UserPwdRecordEntity tmp = (UserPwdRecordEntity) obj;
if (this.getId() == tmp.getId()) {
return true;
}
}
return false;
}
public void initAttrValue(){
this.userId = -1L;
this.loginName = "";
this.loginPwd = "";
}
}
\ No newline at end of file
package com.mortals.xhx.base.system.user.model.vo;
import com.mortals.framework.model.BaseEntityLong;
import lombok.Data;
/**
* 用户密码修改记录视图对象
*
* @author zxfei
* @date 2023-07-26
*/
@Data
public class UserPwdRecordVo extends BaseEntityLong {
}
\ No newline at end of file
package com.mortals.xhx.common.code;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.IBaseEnum;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 设计类型
*/
public enum DesignTypeEnum implements IBaseEnum {
PICTURES(1,"图片", SysConstains.STYLE_DEFAULT),
VIDEOS(2,"视频", SysConstains.STYLE_DEFAULT),
;
private int value;
private String desc;
private String style;
DesignTypeEnum(int value, String desc, String style) {
this.value = value;
this.desc = desc;
this.style = style;
}
@Override
public int getValue() {
return this.value;
}
@Override
public String getDesc() {
return this.desc;
}
@Override
public String getStyle() {
return this.style;
}
public static DesignTypeEnum getByValue(int value) {
for (DesignTypeEnum e : DesignTypeEnum.values()) {
if (e.getValue() == value) {
return e;
}
}
return null;
}
public static Map<String,String> getEnumMap(int... eItem) {
Map<String,String> resultMap= new LinkedHashMap<String,String>();
for (DesignTypeEnum item : DesignTypeEnum.values()) {
try{
boolean hasE = false;
for (int e : eItem){
if(item.getValue()==e){
hasE = true;
break;
}
}
if(!hasE){
resultMap.put(item.getValue()+"", item.getDesc());
}
}catch(Exception ex){
}
}
return resultMap;
}
}
\ No newline at end of file
package com.mortals.xhx.common.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;
public class LoginAESUtil {
/**
* 加密模式之 ECB,算法/模式/补码方式
*/
public static final String AES_ECB = "AES/ECB/PKCS5Padding";
/**
* 加密模式之 CBC,算法/模式/补码方式
*/
public static final String AES_CBC = "AES/CBC/PKCS5Padding";
/**
* 加密模式之 CFB,算法/模式/补码方式
*/
public static final String AES_CFB = "AES/CFB/PKCS5Padding";
/**
* AES 中的 IV 必须是 16 字节(128位)长
*/
public static final Integer IV_LENGTH = 16;
/***
* <h2>空校验</h2>
* @param str 需要判断的值
*/
public static boolean isEmpty(Object str) {
return null == str || "".equals(str);
}
/***
* <h2>String 转 byte</h2>
* @param str 需要转换的字符串
*/
public static byte[] getBytes(String str) {
if (isEmpty(str)) {
return null;
}
try {
return str.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/***
* <h2>初始化向量(IV),它是一个随机生成的字节数组,用于增加加密和解密的安全性</h2>
*/
public static String getIV() {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < IV_LENGTH; i++) {
int number = random.nextInt(str.length());
sb.append(str.charAt(number));
}
return sb.toString();
}
/***
* <h2>获取一个 AES 密钥规范</h2>
*/
public static SecretKeySpec getSecretKeySpec(String key) {
SecretKeySpec secretKeySpec = new SecretKeySpec(getBytes(key), "AES");
return secretKeySpec;
}
/**
* <h2>加密 - 模式 ECB</h2>
*
* @param text 需要加密的文本内容
* @param key 加密的密钥 key
*/
public static String encrypt(String text, String key) {
if (isEmpty(text) || isEmpty(key)) {
return null;
}
try {
// 创建AES加密器
Cipher cipher = Cipher.getInstance(AES_ECB);
SecretKeySpec secretKeySpec = getSecretKeySpec(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 加密字节数组
byte[] encryptedBytes = cipher.doFinal(getBytes(text));
// 将密文转换为 Base64 编码字符串
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <h2>解密 - 模式 ECB</h2>
*
* @param text 需要解密的文本内容
* @param key 解密的密钥 key
*/
public static String decrypt(String text, String key) {
if (isEmpty(text) || isEmpty(key)) {
return null;
}
// 将密文转换为16字节的字节数组
byte[] textBytes = Base64.getDecoder().decode(text);
try {
// 创建AES加密器
Cipher cipher = Cipher.getInstance(AES_ECB);
SecretKeySpec secretKeySpec = getSecretKeySpec(key);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// 解密字节数组
byte[] decryptedBytes = cipher.doFinal(textBytes);
// 将明文转换为字符串
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <h2>加密 - 自定义加密模式</h2>
*
* @param text 需要加密的文本内容
* @param key 加密的密钥 key
* @param iv 初始化向量
* @param mode 加密模式
*/
public static String encrypt(String text, String key, String iv, String mode) {
if (isEmpty(text) || isEmpty(key) || isEmpty(iv)) {
return null;
}
try {
// 创建AES加密器
Cipher cipher = Cipher.getInstance(mode);
SecretKeySpec secretKeySpec = getSecretKeySpec(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(getBytes(iv)));
// 加密字节数组
byte[] encryptedBytes = cipher.doFinal(getBytes(text));
// 将密文转换为 Base64 编码字符串
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <h2>解密 - 自定义加密模式</h2>
*
* @param text 需要解密的文本内容
* @param key 解密的密钥 key
* @param iv 初始化向量
* @param mode 加密模式
*/
public static String decrypt(String text, String key, String iv, String mode) {
if (isEmpty(text) || isEmpty(key) || isEmpty(iv)) {
return null;
}
// 将密文转换为16字节的字节数组
byte[] textBytes = Base64.getDecoder().decode(text);
try {
// 创建AES加密器
Cipher cipher = Cipher.getInstance(mode);
SecretKeySpec secretKeySpec = getSecretKeySpec(key);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(getBytes(iv)));
// 解密字节数组
byte[] decryptedBytes = cipher.doFinal(textBytes);
// 将明文转换为字符串
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String text = "Scsmile@2022";
String key = "0000000671595991";
// 16字节的密钥
String iv = "tdrdadq59tbss5n7";
String encryptTextEBC = encrypt(text, key);
System.out.println("EBC 加密后内容:" + encryptTextEBC);
System.out.println("EBC 解密后内容:" + decrypt(encryptTextEBC, key));
System.out.println();
String encryptTextCBC = encrypt(text, key, iv, AES_CBC);
System.out.println("CBC 加密IV:" + iv);
System.out.println("CBC 加密后内容:" + encryptTextCBC);
System.out.println("CBC 解密后内容:" + decrypt(encryptTextCBC, key, iv, AES_CBC));
System.out.println();
String encryptTextCFB = encrypt(text, key, iv, AES_CFB);
System.out.println("CFB 加密IV:" + iv);
System.out.println("CFB 加密后内容:" + encryptTextCFB);
System.out.println("CFB 解密后内容:" + decrypt(encryptTextCFB, key, iv, AES_CFB));
}
}
package com.mortals.xhx.common.utils;
public class Solution {
//判断输入是否为数字
public static boolean isNumber(char s) {
return s >= '0' && s <= '9';
}
//判断输入是否为大写字母
public static boolean isUpper(char s) {
return s >= 'A' && s <= 'Z';
}
//判断输入是否为小写字母
public static boolean isLower(char s) {
return s >= 'a' && s <= 'z';
}
//判断输入是否为特殊字符
public static boolean isCharacter(char s) {
return (s < 'a' || s > 'z') && (s < 'A' || s > 'Z') && (s < '0' || s > '9');
}
//判断输入长度是否合法
public static boolean lengthOK(String s, int length) {
return s.length() >= length;
}
//判断是否有连续相同输入
public static boolean isSample(char[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 1 && (arr[i] == arr[i + 1])) {
return false;
}
}
return true;
}
//判断密码是否是强密码
public static boolean strongPasswordCheckerII(String password) {
//以五个boolean变量记录是否包含其指定字符,若包含,将对应值置为true
boolean isSample = false, isNumber = false, isUpper = false, isLower = false, isCharacter = false;
//首先判断长度,若长度不符,return false
if (lengthOK(password, 8)) {
//将输入转为数组,便于操作
char[] arr = password.toCharArray();
//判断是否有连续相同输入,若有则isSample=false
isSample = isSample(arr);
for (char c : arr) {
//判断是否包含数字,若有则isNumber=true
if (!isNumber) {
isNumber = isNumber(c);
}
//判断是否包含大写字母,若有则isUpper=true
if (!isUpper) {
isUpper = isUpper(c);
}
//判断是否包含小写字母,若有则isLower=true
if (!isLower) {
isLower = isLower(c);
}
//判断是否包含特殊字符,若有则isCharacter=true
if (!isCharacter) {
isCharacter = isCharacter(c);
}
}
}
//若满足强密码所有条件,则返回true
return isNumber && isUpper && isLower && isCharacter && isSample;
}
}
package com.mortals.xhx.module.customer.dao;
import com.mortals.framework.dao.ICRUDDao;
import com.mortals.xhx.module.customer.model.CustomerPwdRecordEntity;
public interface CustomerPwdRecordDao extends ICRUDDao<CustomerPwdRecordEntity,Long> {
}
package com.mortals.xhx.module.customer.dao.ibatis;
import com.mortals.framework.dao.ibatis.BaseCRUDDaoMybatis;
import com.mortals.xhx.module.customer.dao.CustomerPwdRecordDao;
import com.mortals.xhx.module.customer.model.CustomerPwdRecordEntity;
import org.springframework.stereotype.Repository;
@Repository("customerPwdRecordDao")
public class CustomerPwdRecordDaoImpl extends BaseCRUDDaoMybatis<CustomerPwdRecordEntity,Long> implements CustomerPwdRecordDao {
}
package com.mortals.xhx.module.customer.model;
import com.mortals.xhx.base.system.user.model.UserPwdRecordEntity;
import com.mortals.xhx.module.customer.model.vo.CustomerPwdRecordVo;
import lombok.Data;
@Data
public class CustomerPwdRecordEntity extends CustomerPwdRecordVo {
private static final long serialVersionUID = 1L;
/**
* 用户ID,主键,自增长
*/
private Long userId;
/**
* 登录名
*/
private String loginName;
/**
* 登录密码,使用md5双次加密
*/
private String loginPwd;
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof CustomerPwdRecordEntity) {
CustomerPwdRecordEntity tmp = (CustomerPwdRecordEntity) obj;
if (this.getId() == tmp.getId()) {
return true;
}
}
return false;
}
public void initAttrValue(){
this.userId = -1L;
this.loginName = "";
this.loginPwd = "";
}
}
package com.mortals.xhx.module.customer.model.vo;
import lombok.Data;
/**
* 用户分类统计
*/
@Data
public class CustomerCensusVo {
/**
* 会员等级,,0:未开启,1:试用客户,2:VIP,3:设计师,默认0
*/
private Integer memberLevel;
/** 统计结果 **/
private Integer customerCount;
}
package com.mortals.xhx.module.customer.model.vo;
import lombok.Data;
/**
* 用户作品统计
*/
@Data
public class CustomerDesignCensusVo {
/** 图片数 **/
private Integer picturesCount;
/** 视频数 **/
private Integer videosCount;
}
package com.mortals.xhx.module.customer.model.vo;
import com.mortals.framework.model.BaseEntityLong;
public class CustomerPwdRecordVo extends BaseEntityLong {
}
package com.mortals.xhx.module.thirdlog.sms;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.base.login.web.LoginForm;
import com.mortals.xhx.module.customer.model.CustomerEntity;
import com.mortals.xhx.module.customer.service.CustomerService;
import com.mortals.xhx.module.thirdlog.sms.pdu.SMSLoginPdu;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("sms")
public class SMSLoginController extends BaseJsonBodyController {
@Autowired
private CustomerService customerService;
@Autowired
private IAuthTokenService authTokenService;
@PostMapping({"send"})
@UnAuth
public Rest<Object> sendSmsVerifyCode(@RequestBody SMSLoginPdu smsLoginPdu){
Rest<Object> ret = new Rest();
Map<String, Object> model = new HashMap();
Context context = this.getContext();
String busiDesc = "发送手机验证码";
int code=1;
try {
customerService.sendSmsVerifyCode(smsLoginPdu.getMobileNumber());
model.put("message_info", busiDesc + "成功");
this.recordSysLog(this.request, busiDesc + " 【成功】");
} catch (Exception var9) {
code = -1;
this.doException(this.request, busiDesc, model, var9);
}
ret.setCode(code);
ret.setData(model);
ret.setDict(model.get("dict"));
ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
return ret;
}
@PostMapping("login")
@UnAuth
public String login(@RequestBody SMSLoginPdu smsLoginPdu) throws Exception {
JSONObject ret = new JSONObject();
Map<String, Object> data = new HashMap<>();
String ip = super.getRequestIP(request);
CustomerEntity customerEntity = null;
try {
customerEntity = customerService.doSmsLogin(smsLoginPdu.getMobileNumber(), smsLoginPdu.getVerifyCode(), ip);
customerEntity.setLastLoginAddress(ip);
customerEntity.setLoginTime(System.currentTimeMillis());
customerEntity.setToken(IdUtil.fastSimpleUUID());
customerEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
String token = authTokenService.createToken(customerEntity);
data.put("token", token);
data.put("customer", customerEntity);
recordSysLog(request, customerEntity, "客户登录系统成功!");
ret.put(KEY_RESULT_DATA, data);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
return ret.toJSONString();
} catch (Exception e) {
log.error("login error ", e);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
}
package com.mortals.xhx.module.thirdlog.sms.pdu;
import lombok.Data;
@Data
public class SMSLoginPdu {
/** 手机号码 */
private String mobileNumber;
/** 验证码 */
private String verifyCode;
}
package com.mortals.xhx.module.thirdlog.wechat;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.common.utils.StringUtils;
import com.mortals.xhx.module.customer.model.CustomerEntity;
import com.mortals.xhx.module.customer.service.CustomerService;
import com.mortals.xhx.module.thirdlog.sms.pdu.SMSLoginPdu;
import com.mortals.xhx.module.thirdlog.wechat.utils.WeChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 微信扫码登录
*/
@RestController
@RequestMapping("wechat")
public class WeChatLoginController extends BaseJsonBodyController {
@Autowired
private CustomerService customerService;
@Autowired
private ICacheService cacheService;
private static String WX_VERIFY_CODE_KEY ="login:wx:verify:";
/**
* 微信appId
*/
@Value("${WeChat.pc.appID:wx55400ca31cbbe7fb}")
private String APP_ID;
/**
* 微信appSecret
*/
@Value("${WeChat.pc.appSecret:22555d29a9f914bac0400af5cf63d6b3}")
private String APP_SECRET;
@RequestMapping(
value = {"getLoginSoleCode"},
method = {RequestMethod.POST, RequestMethod.GET}
)
@UnAuth
public Rest<Object> sendSmsVerifyCode(){
Rest<Object> ret = new Rest();
Map<String, Object> model = new HashMap();
String busiDesc = "获取微信登录验证码";
int code=1;
try {
String vCode = RandomUtil.randomNumbers(11);
cacheService.setnx(WX_VERIFY_CODE_KEY+vCode,vCode,90);
model.put("data",vCode);
model.put("message_info", busiDesc + "成功");
} catch (Exception var9) {
code = -1;
this.doException(this.request, busiDesc, model, var9);
}
ret.setCode(code);
ret.setData(model.get("data"));
ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
return ret;
}
@RequestMapping(
value = {"wxLoginOAuth"},
method = {RequestMethod.POST, RequestMethod.GET}
)
@UnAuth
public String wxLoginOAuth(HttpServletRequest request, HttpServletResponse response){
JSONObject ret = new JSONObject();
Map<String, Object> data = new HashMap<>();
try {
// 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
String loginCode = request.getParameter("code");
//前端扫码登入传来的时间戳
String loginState = request.getParameter("state");
//用户拒绝授权时code为空,微信也不会请求该接口。为了防止非法请求,若code为空则返回
if (StringUtils.isEmpty(loginCode)) {
throw new AppException("登入请求被拒绝");
}
if (StringUtils.isEmpty(loginState)) {
throw new AppException("请求状态异常");
}
String vCode = cacheService.get(WX_VERIFY_CODE_KEY + loginState);
if (StringUtils.isEmpty(vCode)){
throw new AppException("微信登录验证码失效");
}
Map<String,String> accessTokenMap = WeChatUtils.getAccessToken(loginCode,APP_ID,APP_SECRET);
String access_token = accessTokenMap.get("access_token");//接口调用凭证,登录后右上角展示数据需要该值去获取
String openid = accessTokenMap.get("openid");//授权用户唯一标识
String ip = super.getRequestIP(request);
CustomerEntity customerEntity = customerService.doWeChatLogin(openid,ip);
customerEntity.setLastLoginAddress(ip);
customerEntity.setLoginTime(System.currentTimeMillis());
customerEntity.setToken(IdUtil.fastSimpleUUID());
customerEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
String token = authTokenService.createToken(customerEntity);
data.put("token", token);
data.put("customer", customerEntity);
recordSysLog(request, customerEntity, "客户扫码登录系统成功!");
ret.put(KEY_RESULT_DATA, data);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
return ret.toJSONString();
} catch (Exception e) {
log.error("login error ", e);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
@RequestMapping(
value = {"bind"},
method = {RequestMethod.POST, RequestMethod.GET}
)
@UnAuth
public String bind(HttpServletRequest request, HttpServletResponse response){
JSONObject ret = new JSONObject();
Map<String, Object> data = new HashMap<>();
try {
// 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
String loginCode = request.getParameter("code");
//前端扫码登入传来的时间戳
String loginState = request.getParameter("state");
//用户拒绝授权时code为空,微信也不会请求该接口。为了防止非法请求,若code为空则返回
if (StringUtils.isEmpty(loginCode)) {
throw new AppException("登入请求被拒绝");
}
if (StringUtils.isEmpty(loginState)) {
throw new AppException("请求状态异常");
}
String vCode = cacheService.get(WX_VERIFY_CODE_KEY + loginState);
if (StringUtils.isEmpty(vCode)){
throw new AppException("微信登录验证码失效");
}
Map<String,String> accessTokenMap = WeChatUtils.getAccessToken(loginCode,APP_ID,APP_SECRET);
String access_token = accessTokenMap.get("access_token");//接口调用凭证,登录后右上角展示数据需要该值去获取
String openid = accessTokenMap.get("openid");//授权用户唯一标识
data.put("openId", openid);
ret.put(KEY_RESULT_DATA, data);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, "微信扫码成功!");
return ret.toJSONString();
} catch (Exception e) {
log.error("bind error ", e);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
}
package com.mortals.xhx.module.thirdlog.wechat.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* description: json工具类 <br>
* version: 1.0 <br>
* @date: 2019/7/20 0019 上午 10:17 <br>
* @author: William <br>
*/
public class JsonUtils {
public static final ObjectMapper MAPPER = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String serialize(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出错:" + obj, e);
return null;
}
}
public static <T> T parse(String json, Class<T> tClass) {
try {
return MAPPER.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <E> List<E> parseList(String json, Class<E> eClass) {
try {
return MAPPER.readValue(json, MAPPER.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <K, V> Map<K, V> parseMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return MAPPER.readValue(json, MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
package com.mortals.xhx.module.thirdlog.wechat.utils;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import java.util.Map;
/**
* description: WeChatUtils 微信获取用户工具类<br>
*
* @date: 2021/8/19 0019 上午 10:05 <br>
* @author: William <br>
* version: 1.0 <br>
*/
public class WeChatUtils {
/**
* 获取微信accessToken路径
*/
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
/**
* 微信appId
*/
@Value("${WeChat.pc.appID:wx55400ca31cbbe7fb}")
private static String APP_ID;
/**
* 微信appSecret
*/
@Value("${WeChat.pc.appSecret:22555d29a9f914bac0400af5cf63d6b3}")
private static String APP_SECRET;
/**
* description: getAccessToken 根据code获取accessToken<br>
* version: 1.0 <br>
* @date: 2021/8/19 0019 上午 10:10 <br>
* @author: William <br>
* @param code 微信用户授权code
* @return java.util.Map<java.lang.String,java.lang.String>
*/
public static Map<String,String> getAccessToken(String code){
return getAccessToken(code,APP_ID,APP_SECRET);
}
/**
* description: getAccessToken 根据code获取微信用户信息,返回map如果正确map包含access_token ,如果错误则包含:errcode<br>
* version: 1.0 <br>
* @date: 2021/8/19 0019 上午 10:11 <br>
* @author: William <br>
* @param code 微信授权code
* @param appId 微信appId
* @param appSecret 微信appSecret
* @return java.util.Map<java.lang.String,java.lang.String>
*/
public static Map<String,String> getAccessToken(String code,String appId,String appSecret){
//判断所有字段不能为空
if(isAnyBlank(code,appId,appSecret)){
throw new IllegalArgumentException("参数错误");
}
String requestUrl = GET_ACCESS_TOKEN_URL.replace("APPID",appId)
.replace("SECRET",appSecret).replace("CODE",code);
String result = HttpUtil.get(requestUrl);
return JsonUtils.parseMap(result, String.class, String.class);
}
/**
* description: isAnyBlank 判断是否存在空字符串,Hutool未编写<br>
* version: 1.0 <br>
* @date: 2021/8/19 0019 上午 10:25 <br>
* @author: William <br>
* @param strs 字符串
* @return java.lang.Boolean
*/
public static Boolean isAnyBlank(CharSequence... strs){
//如果为空直接返回true
if (ArrayUtil.isEmpty(strs)) {
return true;
}
for (CharSequence str : strs) {
if (StrUtil.isBlank(str)) {
return true;
}
}
return false;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment