This commit is contained in:
admin
2024-05-08 21:21:29 +08:00
parent 2919029b81
commit 5838b2df35
138 changed files with 2861 additions and 1179 deletions

View File

@@ -3,7 +3,7 @@ package com.starry.admin.common.aspect;
import java.lang.annotation.*;
/**
* 陪登录注解
* 陪登录注解
*
* @author ruoyi
*/

View File

@@ -2,8 +2,8 @@ package com.starry.admin.common.aspect;
import com.starry.admin.common.conf.ThreadLocalRequestDetail;
import com.starry.admin.common.exception.ServiceException;
import com.starry.admin.modules.clear.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clear.service.impl.PlayClerkUserInfoServiceImpl;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.service.impl.PlayClerkUserInfoServiceImpl;
import com.starry.admin.modules.weichat.service.WxTokenService;
import com.starry.common.constant.Constants;
import com.starry.common.constant.HttpStatus;

View File

@@ -1,7 +1,7 @@
package com.starry.admin.common.conf;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.starry.admin.modules.clear.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
/**
@@ -9,35 +9,35 @@ import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
* @since : 2024/4/2 12:10 AM
*/
public class ThreadLocalRequestDetail {
private static final TransmittableThreadLocal<Object> threadLocal = new TransmittableThreadLocal<>();
private static final TransmittableThreadLocal<Object> THREAD_LOCAL = new TransmittableThreadLocal<>();
/**
* 设置请求信息到当前线程中
*/
public static void setRequestDetail(Object data) {
threadLocal.set(data);
THREAD_LOCAL.set(data);
}
/**
* 从当前线程中获取请求信息
*/
public static Object getRequestDetail() {
return threadLocal.get();
return THREAD_LOCAL.get();
}
public static PlayClerkUserInfoEntity getClerkUserInfo() {
return (PlayClerkUserInfoEntity) threadLocal.get();
return (PlayClerkUserInfoEntity) THREAD_LOCAL.get();
}
public static PlayCustomUserInfoEntity getCustomUserInfo() {
return (PlayCustomUserInfoEntity) threadLocal.get();
return (PlayCustomUserInfoEntity) THREAD_LOCAL.get();
}
/**
* 销毁
*/
public static void remove() {
threadLocal.remove();
THREAD_LOCAL.remove();
}
}

View File

@@ -77,29 +77,6 @@ public class HttpUtils {
return null;
}
// /**
// * 向指定 URL 发送POST方法的请求
// *
// * @param url 发送请求的 URL
// * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
// * @return 所代表远程资源的响应结果
// */
// public static String sendPost(String url, String param) {
// URLConnection conn = getConnection(url);
// StringBuilder result = new StringBuilder();
// try (PrintWriter out = new PrintWriter(conn.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
// out.print(param);
// out.flush();
// String line;
// while ((line = in.readLine()) != null) {
// result.append(line);
// }
// } catch (Exception e) {
// log.error("sendPost error", e);
// }
// return result.toString();
// }
public static String sendPost(String requestUrl, String outputStr) throws IOException {
HttpURLConnection conn = getConnection(requestUrl);

View File

@@ -1,5 +1,10 @@
package com.starry.admin.common.play.wx;
/**
* 位置支付常量
*
* @author admin
*/
public class WeChatConstants {
public enum SignType {
@@ -11,7 +16,7 @@ public class WeChatConstants {
/**
* 支付成功回调地址
*/
public static String NOTIFY_URL = "http://8.142.116.233:8001/pay/wxpay/callback";
public static String NOTIFY_URL = "https://july.hucs.top/api/wx/pay/jsCallback";
/**
@@ -22,8 +27,8 @@ public class WeChatConstants {
/**
* 微信 trade_type 参数
*/
public static final String TRADE_TYPE_JSAPI = "JSAPI";//JSAPI支付 例如 : 直接调用微信支付
public static final String TRADE_TYPE_NATIVE = "NATIVE";//Native支付 例如 : 扫码支付
public static final String TRADE_TYPE_JSAPI = "JSAPI";// JSAPI支付 例如 : 直接调用微信支付
public static final String TRADE_TYPE_NATIVE = "NATIVE";// Native支付 例如 : 扫码支付
/**
* 统一下单

View File

@@ -1,8 +1,10 @@
package com.starry.admin.common.play.wx;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import com.github.wxpay.sdk.WXPayUtil;
import com.starry.admin.common.exception.CustomException;
import com.starry.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -22,13 +24,17 @@ import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
/**
* 微信支付辅助类
*
* @author admin
*/
@Slf4j
public class WxPlayUtils {
public class WxCustomPayUtils {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
@@ -36,45 +42,52 @@ public class WxPlayUtils {
/**
* 获取微信支付请求参数map格式
*
* @param openId 微信公众号ID
* @param appid 用户ID
* @param mchId 商户ID
* @param orderId 订单ID
* @param nonceStr 订单ID
* @param spBillCreateIp 终端设备ID
* @param body 商品描述
* @param totalFee 商品金额
* @param attach 附加数据在查询API和支付通知中原样返回可作为自定义参数使用传入租户ID
* @return
* @throws Exception
*/
public static String unifiedOrderJSAPI(String openId, String appid, String mchId, String orderId, String spBillCreateIp, String body, String attach, int totalFee) throws Exception {
Map<String, String> playRequestParameters = new HashMap<>();
public static Map<String, String> getPayRequestParameters(String openId, String appid, String mchId, String orderId, String nonceStr, String spBillCreateIp, String body, String attach, long totalFee) {
Map<String, String> playRequestParameters = new HashMap<>(16);
playRequestParameters.put("openId", openId);
playRequestParameters.put("appid", appid);
playRequestParameters.put("mch_id", mchId);
playRequestParameters.put("nonce_str", IdUtil.fastSimpleUUID());
playRequestParameters.put("nonce_str", nonceStr);
playRequestParameters.put("body", body);
playRequestParameters.put("attach", attach);
playRequestParameters.put("out_trade_no", orderId);
playRequestParameters.put("total_fee", String.valueOf(totalFee));
playRequestParameters.put("spbill_create_ip", spBillCreateIp);
playRequestParameters.put("notify_url", WxPlayProperties.RETURN_URL);
playRequestParameters.put("notify_url", WeChatConstants.NOTIFY_URL);
playRequestParameters.put("trade_type", "JSAPI");
playRequestParameters.put("openId", openId);
String nonce_str = IdUtil.fastSimpleUUID();
//生成签名, 统一下单
log.debug("paraMap------------{}", playRequestParameters);
String sign = WXPayUtil.generateSignature(playRequestParameters, orderId);
log.debug("sign:{}", sign);
playRequestParameters.put("sign", sign);
String xml = WXPayUtil.mapToXml(playRequestParameters);//将所有参数(map)转xml格式
String new_xml = new String(xml.getBytes(StandardCharsets.UTF_8));
log.debug("xml:{}", new_xml);
//发送post请求"统一下单接口"返回预支付id:prepay_id
String xmlStr = HttpUtils.sendPost(WeChatConstants.UNIFIEDORDER_URL, generateSignedXml(playRequestParameters, orderId));
// String xmlStr = HttpUtils.sendPost(WeChatConstants.UNIFIEDORDER_URL, generateSignedXml(playRequestParameters, orderId));
log.debug("xmlStr:{}", xmlStr);
Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
return playRequestParameters;
}
/**
* @param playRequestParameters 微信支付请求参数
* @param orderId 订单ID
* @param sign 签名信息
*/
public static String unifiedOrderJsApi(Map<String, String> playRequestParameters, String orderId, String sign) throws Exception {
playRequestParameters.put("sign", sign);
// 将所有参数(map)转xml格式
String xml = WXPayUtil.mapToXml(playRequestParameters);
String newXml = new String(xml.getBytes(StandardCharsets.UTF_8));
log.error("xml:{}", newXml);
// 发送post请求"统一下单接口"返回预支付id:prepay_id
String xmlStr = HttpUtils.sendPost(WeChatConstants.UNIFIEDORDER_URL, newXml);
log.info("xmlStr:{}", xmlStr);
if (StringUtils.isBlank(xmlStr)) {
throw new CustomException("微信支付返回信息为空");
}
Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
// 如果预支付返回状态码为不为SUCCESS,说明预支付接口调用失败(通讯业务失败),抛出异常,业务进行处理
if (!map.get("return_code").equals("SUCCESS")) {
throw new CustomException(map.get("return_msg"));
@@ -97,16 +110,16 @@ public class WxPlayUtils {
* @throws Exception
*/
public static Map<String, String> orderQuery(String wechat_appid, String wechat_mchid, String wechat_seckey, String out_trade_no) throws Exception {
//拼接 参数
// 拼接 参数
Map<String, String> paraMap = new HashMap<String, String>();
paraMap.put("appid", wechat_appid);
paraMap.put("mch_id", wechat_mchid);
paraMap.put("nonce_str", IdUtil.fastSimpleUUID());
paraMap.put("out_trade_no", out_trade_no);//订单号
paraMap.put("out_trade_no", out_trade_no);// 订单号
String sign = WXPayUtil.generateSignature(paraMap, wechat_seckey);
paraMap.put("sign", sign);
String xml = WXPayUtil.mapToXml(paraMap);//将所有参数(map)转xml格式
String xmlStr = HttpUtils.sendPost(WeChatConstants.ORDERQUERY_URL, xml);//发送post请求"统一下单接口"返回预支付id:prepay_id
String xml = WXPayUtil.mapToXml(paraMap);// 将所有参数(map)转xml格式
String xmlStr = HttpUtils.sendPost(WeChatConstants.ORDERQUERY_URL, xml);// 发送post请求"统一下单接口"返回预支付id:prepay_id
return WXPayUtil.xmlToMap(xmlStr);
}
@@ -286,7 +299,7 @@ public class WxPlayUtils {
}
sb.append("key=").append(key);
if (WeChatConstants.SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
return MD5.create().digestHex(sb.toString()).toUpperCase();
} else if (WeChatConstants.SignType.HMACSHA256.equals(signType)) {
return HmacSHA256(sb.toString(), key);
} else {
@@ -309,21 +322,21 @@ public class WxPlayUtils {
}
/**
* 生成 MD5
*
* @param data 待处理数据
* @return MD5结果
*/
public static String MD5(String data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
}
return sb.toString().toUpperCase();
}
// /**
// * 生成 MD5
// *
// * @param data 待处理数据
// * @return MD5结果
// */
// public static String MD5(String data) throws Exception {
// MessageDigest md = MessageDigest.getInstance("MD5");
// byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// for (byte item : array) {
// sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
// }
// return sb.toString().toUpperCase();
// }
/**
* 生成 HmacSHA256
@@ -351,4 +364,5 @@ public class WxPlayUtils {
public static long getCurrentTimestamp() {
return System.currentTimeMillis() / 1000;
}
}

View File

@@ -2,11 +2,12 @@ package com.starry.admin.common.security.filter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.starry.admin.common.component.JwtToken;
import com.starry.admin.common.domain.LoginUser;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.clear.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clear.service.impl.PlayClerkUserInfoServiceImpl;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.service.impl.PlayClerkUserInfoServiceImpl;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.impl.PlayCustomUserInfoServiceImpl;
import com.starry.admin.modules.platform.entity.SysTenantEntity;
@@ -15,6 +16,8 @@ import com.starry.admin.modules.weichat.service.WxTokenService;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.constant.Constants;
import com.starry.common.redis.RedisCache;
import com.starry.common.result.R;
import com.starry.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -25,11 +28,14 @@ import org.springframework.web.servlet.HandlerExceptionResolver;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author admin
@@ -62,105 +68,116 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
private RedisCache redisCache;
/**
* 不需要登录的的路径
*/
Set<String> noLoginPathRequired = new HashSet<>(Arrays.asList("/wx/common/area/tree", "/wx/common/file/upload", "/wx/common/audio/upload", "/wx/oauth2/getConfigAddress", "/wx/clerk/user/queryByPage", "wx/clerk/user/queryGiftById", "/wx/clerk/user/queryPriceById", "/wx/clerk/user/queryTrendsById", "wx/clerk/user/queryEvaluateById"));
@Override
protected void doFilterInternal(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) {
protected void doFilterInternal(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) throws ServletException, IOException {
log.info("url = {}", httpServletRequest.getRequestURI());
try {
// 微信公众号的请求,必须存在tenantkey,否则抛出异常
if (httpServletRequest.getServletPath().startsWith("/wx/")) {
String tenantKey = httpServletRequest.getHeader("tenantkey");
if (StrUtil.isBlank(tenantKey)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("tenantkey不能为空"));
// 微信公众号的请求必须存在tenantkey否则抛出异常
if (httpServletRequest.getServletPath().startsWith("/wx/")) {
String tenantKey = httpServletRequest.getHeader("tenantkey");
if (StrUtil.isBlank(tenantKey)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("tenantkey不能为空"));
return;
}
if (noLoginPathRequired.contains(httpServletRequest.getServletPath())) {
//非必须登录的请求,验证租户信息是否正常
String tenantId;
try {
tenantId = getTenantId(null, null, tenantKey);
} catch (Exception e) {
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().println(JSONUtil.parse(R.error(ResultCodeEnum.UNAUTHORIZED.getCode(), ResultCodeEnum.UNAUTHORIZED.getMessage())));
httpServletResponse.getWriter().flush();
return;
//返回401
//
// return;
// throw new RuntimeException("token验证失败,需要重新登录");
}
if (!checkTenantId(tenantId)) {
//返回500
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
Map<String, String> notLoginUrls = new HashMap<>();
notLoginUrls.put("/wx/common/area/tree", "1");
notLoginUrls.put("/wx/common/file/upload", "1");
notLoginUrls.put("/wx/common/audio/upload", "1");
notLoginUrls.put("/wx/oauth2/getConfigAddress", "1");
notLoginUrls.put("/clerk/level/queryAll", "1");
notLoginUrls.put("/wx/clerk/class/queryAll", "1");
notLoginUrls.put("/wx/clerk/user/queryByPage", "1");
notLoginUrls.put("/wx/clerk/user/queryGiftById", "1");
notLoginUrls.put("/wx/clerk/user/queryPriceById", "1");
notLoginUrls.put("/wx/clerk/user/queryTrendsById", "1");
notLoginUrls.put("/wx/clerk/user/queryEvaluateById", "1");
if (notLoginUrls.containsKey(httpServletRequest.getServletPath())) {
String tenantId = getTenantId(null, null, tenantKey);
if (!checkTenantId(tenantId)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
SecurityUtils.setTenantId(tenantId);
} else {
String clerkToken = httpServletRequest.getHeader(Constants.CLERK_USER_LOGIN_TOKEN);
String customToken = httpServletRequest.getHeader(Constants.CUSTOM_USER_LOGIN_TOKEN);
String tenantId = getTenantId(clerkToken, customToken, tenantKey);
if (!checkTenantId(tenantId)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
SecurityUtils.setTenantId(tenantId);
}
SecurityUtils.setTenantId(tenantId);
} else {
// 管理端的请求
LoginUser jwtUser = jwtToken.getNewLoginUser(httpServletRequest);
if (null != jwtUser && null == SecurityContextHolder.getContext().getAuthentication()) {
jwtToken.verifyToken(jwtUser);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
String clerkToken = httpServletRequest.getHeader(Constants.CLERK_USER_LOGIN_TOKEN);
String customToken = httpServletRequest.getHeader(Constants.CUSTOM_USER_LOGIN_TOKEN);
String tenantId;
try {
tenantId = getTenantId(clerkToken, customToken, tenantKey);
} catch (Exception e) {
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().println(JSONUtil.parse(R.error(ResultCodeEnum.UNAUTHORIZED.getCode(), ResultCodeEnum.UNAUTHORIZED.getMessage())));
httpServletResponse.getWriter().flush();
//返回401
return;
// throw new CustomException("token验证失败,需要重新登录");
}
if (!checkTenantId(tenantId)) {
//返回500
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
SecurityUtils.setTenantId(tenantId);
}
} else {
// 管理端的请求
LoginUser jwtUser = jwtToken.getNewLoginUser(httpServletRequest);
if (null != jwtUser && null == SecurityContextHolder.getContext().getAuthentication()) {
jwtToken.verifyToken(jwtUser);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
} catch (Exception e) {
log.error("系统异常", e);
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户及授权验证失败"));
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
/**
* 微信公众号端访问时获取当前用户租户ID
* 如果用户(陪或客户已登录从token中获取租户ID
* 如果用户(陪或客户已登录从token中获取租户ID
* 如果用户未登录从tenantKey中获取租户ID
*
* @param clerkToken 陪登录Key
* @param clerkToken 陪登录Key
* @param customToken 客户登录key
* @param tenantKey 租户标识
*/
public String getTenantId(String clerkToken, String customToken, String tenantKey) {
String tenantId = "";
try {
//如果用户陪玩或客户已登录从token中获取租户ID
if (StrUtil.isNotBlank(clerkToken) || StrUtil.isNotBlank(customToken)) {
String userId = tokenService.getWxUserIdByToken(StrUtil.isNotBlank(clerkToken) ? clerkToken : customToken);
String redisKey = "TENANT_INFO:" + userId;
SecurityUtils.setTenantId(redisCache.getCacheObject(redisKey));
if (clerkToken != null) {
PlayClerkUserInfoEntity entity = clerkUserInfoService.selectById(userId);
if (entity == null) {
log.error("当前登录陪玩不存在,clerkToken={}tenantKey={}", clerkToken, tenantKey);
}
tenantId = entity != null ? entity.getTenantId() : "";
} else {
PlayCustomUserInfoEntity entity = customUserInfoService.selectById(userId);
if (entity == null) {
log.error("当前登录顾客不存在,customToken={}tenantKey={}", customToken, tenantKey);
}
tenantId = entity != null ? entity.getTenantId() : "";
//如果用户陪聊或客户已登录从token中获取租户ID
if (StrUtil.isNotBlank(clerkToken) || StrUtil.isNotBlank(customToken)) {
String userId = tokenService.getWxUserIdByToken(StrUtil.isNotBlank(clerkToken) ? clerkToken : customToken);
String redisKey = "TENANT_INFO:" + userId;
SecurityUtils.setTenantId(redisCache.getCacheObject(redisKey));
if (clerkToken != null) {
PlayClerkUserInfoEntity entity = clerkUserInfoService.selectById(userId);
if (entity == null) {
log.error("当前登录陪聊不存在,clerkToken={}tenantKey={}", clerkToken, tenantKey);
throw new CustomException("用户不存在");
}
return entity.getTenantId();
} else {
// 如果用户未登录从tenantKey中获取租户ID然后验证租户ID是否存在以及租户是否过期等
SysTenantEntity entity = sysTenantService.selectByTenantKey(tenantKey);
if (entity != null) {
tenantId = entity.getTenantId();
PlayCustomUserInfoEntity entity = customUserInfoService.selectById(userId);
if (entity == null) {
log.error("当前登录顾客不存在,customToken={}tenantKey={}", customToken, tenantKey);
throw new CustomException("用户不存在");
}
return entity.getTenantId();
}
} else {
// 如果用户未登录从tenantKey中获取租户ID然后验证租户ID是否存在以及租户是否过期等
SysTenantEntity entity = sysTenantService.selectByTenantKey(tenantKey);
if (entity != null) {
return entity.getTenantId();
}
} catch (Exception e) {
log.error("获取tenantKey异常clerkToken={},customToken={},tenantKey = {}", clerkToken, customToken, tenantKey, e);
}
return tenantId;
}