refactor(payment): 统一使用标准库进行URL编解码

- 将支付宝插件中的Hutool URLEncoder替换为java.net.URLEncoder- 将支付宝插件中的Hutool URLDecoder替换为java.net.URLDecoder
- 在微信支付插件中统一使用标准库进行URL编解码
- 处理UnsupportedEncodingException异常情况- 更新相关注释和日志信息以反映变更
This commit is contained in:
pikachu1995@126.com
2025-10-11 18:50:44 +08:00
parent 33fcce1cc9
commit dedcc0a556
17 changed files with 261 additions and 213 deletions

View File

@@ -91,15 +91,16 @@ public class BuyerAuthenticationFilter extends BasicAuthenticationFilter {
try { try {
Claims claims Claims claims
= Jwts.parser() = Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(jwt).getBody(); .parseClaimsJws(jwt).getBody();
//获取存储在claims中的用户信息 // 获取存储在claims中的用户信息
String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();
AuthUser authUser = new Gson().fromJson(json, AuthUser.class); AuthUser authUser = new Gson().fromJson(json, AuthUser.class);
//校验redis中是否有权限 //校验redis中是否有权限
if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.MEMBER,authUser.getId()) + jwt)) { if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.MEMBER, authUser.getId()) + jwt)) {
//构造返回信息 //构造返回信息
List<GrantedAuthority> auths = new ArrayList<>(); List<GrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority("ROLE_" + authUser.getRole().name())); auths.add(new SimpleGrantedAuthority("ROLE_" + authUser.getRole().name()));

View File

@@ -164,7 +164,8 @@ public class GlobalControllerExceptionHandler {
if (!fieldErrors.isEmpty()) { if (!fieldErrors.isEmpty()) {
return ResultUtil.error(ResultCode.PARAMS_ERROR.code(), return ResultUtil.error(ResultCode.PARAMS_ERROR.code(),
fieldErrors.stream() fieldErrors.stream()
.map(FieldError::getDefaultMessage) // 获取每个对象的名称字段 // 获取每个对象的名称字段
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining(", "))); .collect(Collectors.joining(", ")));
} }
return ResultUtil.error(ResultCode.PARAMS_ERROR); return ResultUtil.error(ResultCode.PARAMS_ERROR);
@@ -187,6 +188,7 @@ public class GlobalControllerExceptionHandler {
ConstraintViolationException exception = (ConstraintViolationException) e; ConstraintViolationException exception = (ConstraintViolationException) e;
return ResultUtil.error(ResultCode.PARAMS_ERROR.code(), exception.getMessage()); return ResultUtil.error(ResultCode.PARAMS_ERROR.code(), exception.getMessage());
} }
/** /**
* 拼接错误消息 * 拼接错误消息
* *

View File

@@ -92,8 +92,9 @@ public class UserContext {
try { try {
//获取token的信息 //获取token的信息
Claims claims Claims claims
= Jwts.parser() = Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(accessToken).getBody(); .parseClaimsJws(accessToken).getBody();
//获取存储在claims中的用户信息 //获取存储在claims中的用户信息
String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();

View File

@@ -144,7 +144,6 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public ServletInputStream getInputStream() throws IOException { public ServletInputStream getInputStream() throws IOException {
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
InputStreamReader reader = null; InputStreamReader reader = null;
//获取输入流 //获取输入流
@@ -163,47 +162,55 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
//继续读取下一行流直到line为空 //继续读取下一行流直到line为空
line = bufferedReader.readLine(); line = bufferedReader.readLine();
} }
if (CharSequenceUtil.isNotEmpty(body) && Boolean.TRUE.equals(JSONUtil.isJsonObj(body.toString()))) {
//将body转换为map // 兼容替换:不再使用过时的 JSONUtil.isJsonObj(String),改为尝试解析并捕获异常
Map<String, Object> map = JSONUtil.parseObj(body.toString()); if (CharSequenceUtil.isNotEmpty(body)) {
//创建空的map用于存储结果 Map<String, Object> map = null;
Map<String, Object> resultMap = new HashMap<>(map.size()); try {
//遍历数组 map = JSONUtil.parseObj(body.toString());
for (Map.Entry<String, Object> entry : map.entrySet()) { } catch (Exception ignore) {
//如果map.get(key)获取到的是字符串就需要进行处理如果不是直接存储resultMap map = null;
if (map.get(entry.getKey()) instanceof String) {
resultMap.put(entry.getKey(), filterXss(entry.getKey(), entry.getValue().toString()));
} else {
resultMap.put(entry.getKey(), entry.getValue());
}
} }
if (map != null) {
//将resultMap转换为json字符串 //创建空的map用于存储结果
String resultStr = JSONUtil.toJsonStr(resultMap); Map<String, Object> resultMap = new HashMap<>(map.size());
//将json字符串转换为字节 //遍历数组
final ByteArrayInputStream resultBIS = new ByteArrayInputStream(resultStr.getBytes(StandardCharsets.UTF_8)); for (Map.Entry<String, Object> entry : map.entrySet()) {
//如果map.get(key)获取到的是字符串就需要进行处理如果不是直接存储resultMap
//实现接口 if (map.get(entry.getKey()) instanceof String) {
return new ServletInputStream() { resultMap.put(entry.getKey(), filterXss(entry.getKey(), entry.getValue().toString()));
@Override } else {
public boolean isFinished() { resultMap.put(entry.getKey(), entry.getValue());
return false; }
} }
@Override //将resultMap转换为json字符串
public boolean isReady() { String resultStr = JSONUtil.toJsonStr(resultMap);
return false; //将json字符串转换为字节
} final ByteArrayInputStream resultBIS = new ByteArrayInputStream(resultStr.getBytes(StandardCharsets.UTF_8));
@Override //实现接口
public void setReadListener(ReadListener readListener) { return new ServletInputStream() {
} @Override
public boolean isFinished() {
return false;
}
@Override @Override
public int read() { public boolean isReady() {
return resultBIS.read(); return false;
} }
};
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() {
return resultBIS.read();
}
};
}
} }
//将json字符串转换为字节 //将json字符串转换为字节

View File

@@ -65,8 +65,9 @@ public class TokenUtil {
Claims claims; Claims claims;
try { try {
claims = Jwts.parser() claims = Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(oldRefreshToken).getBody(); .parseClaimsJws(oldRefreshToken).getBody();
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException |
IllegalArgumentException e) { IllegalArgumentException e) {

View File

@@ -90,7 +90,8 @@ public abstract class BaseElasticsearchService {
request.settings(Settings.builder() request.settings(Settings.builder()
.put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards()) .put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards())
.put("index.number_of_replicas", elasticsearchProperties.getIndex().getNumberOfReplicas()) .put("index.number_of_replicas", elasticsearchProperties.getIndex().getNumberOfReplicas())
.put("index.max_result_window", 100000) //最大查询结果数 //最大查询结果数
.put("index.max_result_window", 100000)
.put("index.mapping.total_fields.limit", 2000)); .put("index.mapping.total_fields.limit", 2000));
//创建索引 //创建索引

View File

@@ -535,7 +535,8 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
try (InputStream inputStream = file.getInputStream()) { try (InputStream inputStream = file.getInputStream()) {
// 使用 WorkbookFactory.create 方法读取 Excel 文件 // 使用 WorkbookFactory.create 方法读取 Excel 文件
Workbook workbook = WorkbookFactory.create(inputStream); Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0); // 我们只读取第一个sheet // 我们只读取第一个sheet
Sheet sheet = workbook.getSheetAt(0);
// 检查第一个sheet的行数是否超过10002行 // 检查第一个sheet的行数是否超过10002行
if (sheet.getPhysicalNumberOfRows() > 10002) { if (sheet.getPhysicalNumberOfRows() > 10002) {
@@ -1039,7 +1040,8 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
// 设置下拉列表数据验证 // 设置下拉列表数据验证
DataValidationHelper validationHelper = templateSheet.getDataValidationHelper(); DataValidationHelper validationHelper = templateSheet.getDataValidationHelper();
DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(new String[]{"", ""}); DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(new String[]{"", ""});
CellRangeAddressList addressList = new CellRangeAddressList(2, 10001, 2, 2); // 从第3行到第10002行第3列 // 从第3行到第10002行第3列
CellRangeAddressList addressList = new CellRangeAddressList(2, 10001, 2, 2);
DataValidation validation = validationHelper.createValidation(constraint, addressList); DataValidation validation = validationHelper.createValidation(constraint, addressList);
validation.setSuppressDropDownArrow(true); validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true); validation.setShowErrorBox(true);

View File

@@ -131,50 +131,67 @@ public class KdniaoPlugin implements LogisticsPlugin {
StoreLogistics storeLogistics = labelOrderDTO.getStoreLogistics(); StoreLogistics storeLogistics = labelOrderDTO.getStoreLogistics();
//组装快递鸟应用级参数 //组装快递鸟应用级参数
String resultDate = "{" + String resultDate = "{"
"'OrderCode': '" + order.getSn() + "'," + //订单编码 // 订单编码
"'ShipperCode': '" + logistics.getCode() + "'," + //快递公司编码 + "'OrderCode': '" + order.getSn() + "',"
"'CustomerName': '" + storeLogistics.getCustomerName() + "'," +//客户编码 // 快递公司编码
"'CustomerPwd': '" + storeLogistics.getCustomerPwd() + "'," + //客户密码 + "'ShipperCode': '" + logistics.getCode() + "',"
"'MonthCode': '" + storeLogistics.getMonthCode() + "'," + //密钥 // 客户编码
"'SendSite': '" + storeLogistics.getSendSite() + "'," + //归属网点 + "'CustomerName': '" + storeLogistics.getCustomerName() + "',"
"'SendStaff': '" + storeLogistics.getSendStaff() + "'," + //收件快递员 // 客户密码
"'PayType': " + storeLogistics.getPayType() + "," + + "'CustomerPwd': '" + storeLogistics.getCustomerPwd() + "',"
"'ExpType': " + storeLogistics.getExpType() + "," + // 密钥
//发件人信息 + "'MonthCode': '" + storeLogistics.getMonthCode() + "',"
"'Sender': {" + // 归属网点
"'Name': '" + storeDeliverGoodsAddressDTO.getSalesConsignorName() + "'," + + "'SendSite': '" + storeLogistics.getSendSite() + "',"
"'Mobile': '" + storeDeliverGoodsAddressDTO.getSalesConsignorMobile() + "'," + // 收件快递员
"'ProvinceName': '" + consignorAddress[0] + "'," + //省 + "'SendStaff': '" + storeLogistics.getSendStaff() + "',"
"'CityName': '" + consignorAddress[1] + "'," + //市 + "'PayType': " + storeLogistics.getPayType() + ","
"'ExpAreaName': '" + consignorAddress[2] + "'," + //区 + "'ExpType': " + storeLogistics.getExpType() + ","
"'Address': '" + storeDeliverGoodsAddressDTO.getSalesConsignorDetail() + "'" + //发件人详细地址 // 发件人信息
"}," + + "'Sender': {"
//收件人信息 + "'Name': '" + storeDeliverGoodsAddressDTO.getSalesConsignorName() + "',"
"'Receiver': {" + + "'Mobile': '" + storeDeliverGoodsAddressDTO.getSalesConsignorMobile() + "',"
"'Name': '" + order.getConsigneeName() + "'," + // 省
"'Mobile': '" + order.getConsigneeMobile() + "'," + + "'ProvinceName': '" + consignorAddress[0] + "',"
"'ProvinceName': '" + ConsigneeAddress[0] + "'," + // //
"'CityName': '" + ConsigneeAddress[1] + "'," + //市 + "'CityName': '" + consignorAddress[1] + "',"
"'ExpAreaName': '" + ConsigneeAddress[2] + "'," + //区 //
"'Address': '" + order.getConsigneeDetail() + "'" + //收件人详细地址 + "'ExpAreaName': '" + consignorAddress[2] + "',"
"}," + // 发件人详细地址
//商品信息 + "'Address': '" + storeDeliverGoodsAddressDTO.getSalesConsignorDetail() + "'"
"'Commodity': ["; + "},"
// 收件人信息
+ "'Receiver': {"
+ "'Name': '" + order.getConsigneeName() + "',"
+ "'Mobile': '" + order.getConsigneeMobile() + "',"
// 省
+ "'ProvinceName': '" + ConsigneeAddress[0] + "',"
// 市
+ "'CityName': '" + ConsigneeAddress[1] + "',"
// 区
+ "'ExpAreaName': '" + ConsigneeAddress[2] + "',"
// 收件人详细地址
+ "'Address': '" + order.getConsigneeDetail() + "'"
+ "},"
// 商品信息
+ "'Commodity': [";
//子订单信息 //子订单信息
for (OrderItem orderItem : orderItems) { for (OrderItem orderItem : orderItems) {
resultDate = resultDate + "{" + resultDate = resultDate + "{"
"'GoodsName': '" + orderItem.getGoodsName() + "'," + + "'GoodsName': '" + orderItem.getGoodsName() + "',"
"'Goodsquantity': '" + orderItem.getNum() + "'" + + "'Goodsquantity': '" + orderItem.getNum() + "'"
"},"; + "},";
} }
resultDate = resultDate + "]," + resultDate = resultDate + "],"
"'Quantity': " + orderItems.size() + "," + //包裹数 // 包裹数
"'IsReturnPrintTemplate':1," + //生成电子面单模板 + "'Quantity': " + orderItems.size() + ","
"'Remark': '" + order.getRemark() + "'" +//商家备注 // 生成电子面单模板
"}"; + "'IsReturnPrintTemplate':1,"
// 商家备注
+ "'Remark': '" + order.getRemark() + "'"
+ "}";
//组织系统级参数 //组织系统级参数
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
@@ -200,9 +217,9 @@ public class KdniaoPlugin implements LogisticsPlugin {
JSONObject obj = JSONObject.parseObject(result); JSONObject obj = JSONObject.parseObject(result);
log.info("电子面单响应:{}", result); log.info("电子面单响应:{}", result);
if (!"100".equals(obj.getString("ResultCode"))) { if (!"100".equals(obj.getString("ResultCode"))) {
// resultMap.put("Reason",obj.getString("Reason")); // resultMap.put("Reason",obj.getString("Reason"));
throw new ServiceException(obj.getString("Reason")); throw new ServiceException(obj.getString("Reason"));
// return resultMap; // return resultMap;
} }
JSONObject orderJson = JSONObject.parseObject(obj.getString("Order")); JSONObject orderJson = JSONObject.parseObject(obj.getString("Order"));

View File

@@ -267,8 +267,8 @@ public class SkuPromotionRender implements CartRenderStep {
} }
} }
//设置购物车未选中
if (quantity != null && cartSkuVO.getNum() > (Integer) quantity) {//设置购物车未选中 if (quantity != null && cartSkuVO.getNum() > (Integer) quantity) {
cartSkuVO.setChecked(false); cartSkuVO.setChecked(false);
//设置失效消息 //设置失效消息
cartSkuVO.setErrorMessage("促销商品库存不足,现有库存数量[" + quantity + "]"); cartSkuVO.setErrorMessage("促销商品库存不足,现有库存数量[" + quantity + "]");

View File

@@ -1,13 +1,10 @@
package cn.lili.modules.payment.kit.plugin.alipay; package cn.lili.modules.payment.kit.plugin.alipay;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import cn.lili.common.context.ThreadContextHolder; import cn.lili.common.context.ThreadContextHolder;
import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil; import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException; import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.ApiProperties;
import cn.lili.common.properties.DomainProperties; import cn.lili.common.properties.DomainProperties;
import cn.lili.common.utils.BeanUtil; import cn.lili.common.utils.BeanUtil;
import cn.lili.common.utils.SnowFlake; import cn.lili.common.utils.SnowFlake;
@@ -40,7 +37,6 @@ import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
/** /**
@@ -90,13 +86,14 @@ public class AliPayPlugin implements Payment {
payModel.setBody(cashierParam.getTitle()); payModel.setBody(cashierParam.getTitle());
payModel.setSubject(cashierParam.getDetail()); payModel.setSubject(cashierParam.getDetail());
payModel.setTotalAmount(cashierParam.getPrice() + ""); payModel.setTotalAmount(cashierParam.getPrice() + "");
//回传数据
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8));
//3分钟超时 //3分钟超时
payModel.setTimeoutExpress("3m"); payModel.setTimeoutExpress("3m");
payModel.setOutTradeNo(outTradeNo); payModel.setOutTradeNo(outTradeNo);
payModel.setProductCode("QUICK_WAP_PAY"); payModel.setProductCode("QUICK_WAP_PAY");
try { try {
// Passback params moved into try to handle checked exception
payModel.setPassbackParams(java.net.URLEncoder.encode(BeanUtil.formatKeyValuePair(payParam), "UTF-8"));
log.info("支付宝H5支付{}", JSONUtil.toJsonStr(payModel)); log.info("支付宝H5支付{}", JSONUtil.toJsonStr(payModel));
AliPayRequest.wapPay(response, payModel, callbackUrl(alipayPaymentSetting.getCallbackUrl(), PaymentMethodEnum.ALIPAY), AliPayRequest.wapPay(response, payModel, callbackUrl(alipayPaymentSetting.getCallbackUrl(), PaymentMethodEnum.ALIPAY),
notifyUrl(alipayPaymentSetting.getCallbackUrl(), PaymentMethodEnum.ALIPAY)); notifyUrl(alipayPaymentSetting.getCallbackUrl(), PaymentMethodEnum.ALIPAY));
@@ -130,8 +127,8 @@ public class AliPayPlugin implements Payment {
//3分钟超时 //3分钟超时
payModel.setTimeoutExpress("3m"); payModel.setTimeoutExpress("3m");
//回传数据 //回传数据(替换 Hutool 的 URLEncoder 为 JDK 的 java.net.URLEncoder
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); payModel.setPassbackParams(java.net.URLEncoder.encode(BeanUtil.formatKeyValuePair(payParam), "UTF-8"));
payModel.setOutTradeNo(outTradeNo); payModel.setOutTradeNo(outTradeNo);
payModel.setProductCode("QUICK_MSECURITY_PAY"); payModel.setProductCode("QUICK_MSECURITY_PAY");
@@ -164,8 +161,8 @@ public class AliPayPlugin implements Payment {
payModel.setSubject(cashierParam.getDetail()); payModel.setSubject(cashierParam.getDetail());
payModel.setTotalAmount(cashierParam.getPrice() + ""); payModel.setTotalAmount(cashierParam.getPrice() + "");
//回传数据 //回传数据(替换 Hutool 的 URLEncoder 为 JDK 的 java.net.URLEncoder
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); payModel.setPassbackParams(java.net.URLEncoder.encode(BeanUtil.formatKeyValuePair(payParam), "UTF-8"));
payModel.setTimeoutExpress("3m"); payModel.setTimeoutExpress("3m");
payModel.setOutTradeNo(outTradeNo); payModel.setOutTradeNo(outTradeNo);
log.info("支付宝扫码:{}", payModel); log.info("支付宝扫码:{}", payModel);
@@ -314,7 +311,8 @@ public class AliPayPlugin implements Payment {
return; return;
} }
String payParamStr = map.get("passback_params"); String payParamStr = map.get("passback_params");
String payParamJson = URLDecoder.decode(payParamStr, StandardCharsets.UTF_8); // java.net.URLDecoder.decode throws UnsupportedEncodingException, add catch below
String payParamJson = java.net.URLDecoder.decode(payParamStr, "UTF-8");
PayParam payParam = BeanUtil.formatKeyValuePair(payParamJson, new PayParam()); PayParam payParam = BeanUtil.formatKeyValuePair(payParamJson, new PayParam());
@@ -331,6 +329,8 @@ public class AliPayPlugin implements Payment {
} }
} catch (AlipayApiException e) { } catch (AlipayApiException e) {
log.error("支付回调通知异常", e); log.error("支付回调通知异常", e);
} catch (java.io.UnsupportedEncodingException e) {
log.error("URL 解码异常", e);
} }
} }

View File

@@ -1,6 +1,5 @@
package cn.lili.modules.payment.kit.plugin.unionpay; package cn.lili.modules.payment.kit.plugin.unionpay;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultCode;
@@ -67,7 +66,7 @@ public class UnionPayPlugin implements Payment {
String ip = IpKit.getRealIp(request); String ip = IpKit.getRealIp(request);
//第三方付款订单 //第三方付款订单
String outOrderNo = SnowFlake.getIdStr(); String outOrderNo = SnowFlake.getIdStr();
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
Map<String, String> params = UnifiedOrderModel.builder() Map<String, String> params = UnifiedOrderModel.builder()
.service(ServiceEnum.NATIVE.toString()) .service(ServiceEnum.NATIVE.toString())
.mch_id(unionPaymentSetting.getUnionPayMachId()) .mch_id(unionPaymentSetting.getUnionPayMachId())
@@ -94,12 +93,10 @@ public class UnionPayPlugin implements Payment {
@Override @Override
public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) { public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) {
try { try {
CashierParam cashierParam = cashierSupport.cashierParam(payParam); CashierParam cashierParam = cashierSupport.cashierParam(payParam);
UnionPaymentSetting unionPaymentSetting = this.unionPaymentSetting(); UnionPaymentSetting unionPaymentSetting = this.unionPaymentSetting();
String notifyUrl = unionPaymentSetting.getUnionPayDomain().concat("/unionPay/payNotify"); String notifyUrl = unionPaymentSetting.getUnionPayDomain().concat("/unionPay/payNotify");
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
//用户ip //用户ip
String ip = IpKit.getRealIp(request); String ip = IpKit.getRealIp(request);
Map<String, String> params = UnifiedOrderModel.builder() Map<String, String> params = UnifiedOrderModel.builder()
@@ -135,9 +132,7 @@ public class UnionPayPlugin implements Payment {
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage()); log.error(e.getMessage());
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
@@ -147,10 +142,12 @@ public class UnionPayPlugin implements Payment {
String buyerId=""; String buyerId="";
CashierParam cashierParam = cashierSupport.cashierParam(payParam); CashierParam cashierParam = cashierSupport.cashierParam(payParam);
UnionPaymentSetting unionPaymentSetting = this.unionPaymentSetting(); UnionPaymentSetting unionPaymentSetting = this.unionPaymentSetting();
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); // 将 attach 的编码移动到 try 内,避免方法外部的受检异常
// String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8);
//用户ip //用户ip
String ip = IpKit.getRealIp(request); String ip = IpKit.getRealIp(request);
try { try {
String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
if (StrUtil.isEmpty(buyerLogonId) && StrUtil.isEmpty(buyerId)) { if (StrUtil.isEmpty(buyerLogonId) && StrUtil.isEmpty(buyerId)) {
log.error("buyer_logon_id buyer_id 不能同时为空"); log.error("buyer_logon_id buyer_id 不能同时为空");
return null; return null;

View File

@@ -1,7 +1,5 @@
package cn.lili.modules.payment.kit.plugin.wechat; package cn.lili.modules.payment.kit.plugin.wechat;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache; import cn.lili.cache.Cache;
import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultCode;
@@ -148,7 +146,7 @@ public class WechatPlugin implements Payment {
String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3); String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
//回传数据 //回传数据
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
@@ -157,13 +155,12 @@ public class WechatPlugin implements Payment {
throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING); throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING);
} }
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
H5Service service = new H5Service.Builder().config(config).build(); H5Service service = new H5Service.Builder().config(config).build();
@@ -181,7 +178,7 @@ public class WechatPlugin implements Payment {
prepayRequest.setSceneInfo(sceneInfo); prepayRequest.setSceneInfo(sceneInfo);
// 调用下单方法,得到应答 // 调用下单方法,得到应答
com.wechat.pay.java.service.payments.h5.model.PrepayResponse response = service.prepay(prepayRequest); com.wechat.pay.java.service.payments.h5.model.PrepayResponse response = service.prepay(prepayRequest);
updateOrderPayNo(payParam,outOrderNo); updateOrderPayNo(payParam, outOrderNo);
return ResultUtil.data(response.getH5Url()); return ResultUtil.data(response.getH5Url());
} catch (Exception e) { } catch (Exception e) {
@@ -202,7 +199,6 @@ public class WechatPlugin implements Payment {
} }
CashierParam cashierParam = cashierSupport.cashierParam(payParam); CashierParam cashierParam = cashierSupport.cashierParam(payParam);
//支付金额 //支付金额
@@ -212,7 +208,8 @@ public class WechatPlugin implements Payment {
//过期时间 //过期时间
String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3); String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); // 将 Hutool URLEncoder 替换为标准库
String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
String appid = setting.getJsapiAppId(); String appid = setting.getJsapiAppId();
@@ -220,11 +217,11 @@ public class WechatPlugin implements Payment {
throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING); throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING);
} }
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
JsapiService service = new JsapiService.Builder().config(config).build(); JsapiService service = new JsapiService.Builder().config(config).build();
@@ -246,7 +243,7 @@ public class WechatPlugin implements Payment {
prepayRequest.setPayer(payer); prepayRequest.setPayer(payer);
// 调用下单方法,得到应答 // 调用下单方法,得到应答
com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse response = service.prepay(prepayRequest); com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse response = service.prepay(prepayRequest);
updateOrderPayNo(payParam,outOrderNo); updateOrderPayNo(payParam, outOrderNo);
Map<String, String> map = WxPayKit.jsApiCreateSign(appid, response.getPrepayId(), setting.getApiclientKey()); Map<String, String> map = WxPayKit.jsApiCreateSign(appid, response.getPrepayId(), setting.getApiclientKey());
log.info("唤起支付参数:{}", map); log.info("唤起支付参数:{}", map);
@@ -271,7 +268,8 @@ public class WechatPlugin implements Payment {
//过期时间 //过期时间
String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3); String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); // 将 Hutool URLEncoder 替换为标准库
String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
String appid = setting.getJsapiAppId(); String appid = setting.getJsapiAppId();
@@ -279,11 +277,11 @@ public class WechatPlugin implements Payment {
throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING); throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING);
} }
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
AppService service = new AppService.Builder().config(config).build(); AppService service = new AppService.Builder().config(config).build();
@@ -302,14 +300,14 @@ public class WechatPlugin implements Payment {
// 调用下单方法,得到应答 // 调用下单方法,得到应答
com.wechat.pay.java.service.payments.app.model.PrepayResponse response = service.prepay(prepayRequest); com.wechat.pay.java.service.payments.app.model.PrepayResponse response = service.prepay(prepayRequest);
updateOrderPayNo(payParam,outOrderNo); updateOrderPayNo(payParam, outOrderNo);
Map<String, String> map = WxPayKit.appPrepayIdCreateSign(appid, Map<String, String> map = WxPayKit.appPrepayIdCreateSign(appid,
setting.getMchId(), setting.getMchId(),
response.getPrepayId(), response.getPrepayId(),
setting.getApiclientKey(), SignType.MD5); setting.getApiclientKey(), SignType.MD5);
log.info("唤起支付参数:{}", map); log.info("唤起支付参数:{}", map);
//修改付款单号 //修改付款单号
updateOrderPayNo(payParam,outOrderNo); updateOrderPayNo(payParam, outOrderNo);
return ResultUtil.data(map); return ResultUtil.data(map);
} catch (Exception e) { } catch (Exception e) {
log.error("支付异常", e); log.error("支付异常", e);
@@ -331,7 +329,8 @@ public class WechatPlugin implements Payment {
//过期时间 //过期时间
String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3); String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); // 将 Hutool URLEncoder 替换为标准库
String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
@@ -340,11 +339,11 @@ public class WechatPlugin implements Payment {
throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING); throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING);
} }
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
NativePayService service = new NativePayService.Builder().config(config).build(); NativePayService service = new NativePayService.Builder().config(config).build();
@@ -363,7 +362,7 @@ public class WechatPlugin implements Payment {
// 调用下单方法,得到应答 // 调用下单方法,得到应答
PrepayResponse response = service.prepay(prepayRequest); PrepayResponse response = service.prepay(prepayRequest);
updateOrderPayNo(payParam,outOrderNo); updateOrderPayNo(payParam, outOrderNo);
return ResultUtil.data(response.getCodeUrl()); return ResultUtil.data(response.getCodeUrl());
} catch (ServiceException e) { } catch (ServiceException e) {
@@ -405,15 +404,16 @@ public class WechatPlugin implements Payment {
if (StringUtils.isEmpty(appid)) { if (StringUtils.isEmpty(appid)) {
throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING); throw new ServiceException(ResultCode.WECHAT_PAYMENT_NOT_SETTING);
} }
String attach = URLEncoder.createDefault().encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8); // 将 Hutool URLEncoder 替换为标准库
String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
JsapiService service = new JsapiService.Builder().config(config).build(); JsapiService service = new JsapiService.Builder().config(config).build();
@@ -432,7 +432,7 @@ public class WechatPlugin implements Payment {
prepayRequest.setPayer(payer); prepayRequest.setPayer(payer);
// 调用下单方法,得到应答 // 调用下单方法,得到应答
com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse response = service.prepay(prepayRequest); com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse response = service.prepay(prepayRequest);
updateOrderPayNo(payParam,outOrderNo); updateOrderPayNo(payParam, outOrderNo);
Map<String, String> map = WxPayKit.jsApiCreateSign(appid, response.getPrepayId(), setting.getApiclientKey()); Map<String, String> map = WxPayKit.jsApiCreateSign(appid, response.getPrepayId(), setting.getApiclientKey());
log.info("唤起支付参数:{}", map); log.info("唤起支付参数:{}", map);
@@ -501,7 +501,6 @@ public class WechatPlugin implements Payment {
} }
//获取用户openId //获取用户openId
Connect connect = connectService.queryConnect( Connect connect = connectService.queryConnect(
ConnectQueryDTO.builder().userId(memberWithdrawApply.getMemberId()) ConnectQueryDTO.builder().userId(memberWithdrawApply.getMemberId())
@@ -510,11 +509,11 @@ public class WechatPlugin implements Payment {
//获取微信设置 //获取微信设置
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
TransferBatchService service = new TransferBatchService.Builder().config(config).build(); TransferBatchService service = new TransferBatchService.Builder().config(config).build();
@@ -544,7 +543,7 @@ public class WechatPlugin implements Payment {
log.info("微信提现响应 {}", response); log.info("微信提现响应 {}", response);
return TransferResultDTO.builder().result(response.getBatchId()!= null).build(); return TransferResultDTO.builder().result(response.getBatchId() != null).build();
//根据自身业务进行接下来的任务处理 //根据自身业务进行接下来的任务处理
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -571,23 +570,23 @@ public class WechatPlugin implements Payment {
.build(); .build();
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
NotificationConfig config=null; NotificationConfig config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config = new RSAAutoCertificateConfig.Builder() config = new RSAAutoCertificateConfig.Builder()
.merchantId(setting.getMchId()) .merchantId(setting.getMchId())
.privateKey(setting.getApiclientKey()) .privateKey(setting.getApiclientKey())
.merchantSerialNumber(setting.getSerialNumber()) .merchantSerialNumber(setting.getSerialNumber())
.apiV3Key(setting.getApiKey3()) .apiV3Key(setting.getApiKey3())
.build(); .build();
}else{ } else {
config = new RSAPublicKeyConfig.Builder() config = new RSAPublicKeyConfig.Builder()
.merchantId(setting.getMchId()) .merchantId(setting.getMchId())
.apiV3Key(setting.getApiKey3()) .apiV3Key(setting.getApiKey3())
.privateKey(setting.getApiclientKey()) .privateKey(setting.getApiclientKey())
.merchantSerialNumber(setting.getSerialNumber()) .merchantSerialNumber(setting.getSerialNumber())
.publicKeyId(setting.getPublicId()) .publicKeyId(setting.getPublicId())
.publicKey(setting.getPublicKey()) .publicKey(setting.getPublicKey())
.build(); .build();
} }
// 初始化 NotificationParser // 初始化 NotificationParser
@@ -597,8 +596,10 @@ public class WechatPlugin implements Payment {
// 以支付通知回调为例,验签、解密并转换成 Transaction // 以支付通知回调为例,验签、解密并转换成 Transaction
Transaction transaction = parser.parse(requestParam, Transaction.class); Transaction transaction = parser.parse(requestParam, Transaction.class);
String payParamJson = URLDecoder.decode(transaction.getAttach(), StandardCharsets.UTF_8); // 将 Hutool URLDecoder 替换为标准库
PayParam payParam = JSONUtil.toBean(payParamJson, PayParam.class); String payParamJson = java.net.URLDecoder.decode(transaction.getAttach(), StandardCharsets.UTF_8.name());
PayParam payParam = new Gson().fromJson(payParamJson, PayParam.class);
Double totalAmount = CurrencyUtil.reversalFen(transaction.getAmount().getTotal()); Double totalAmount = CurrencyUtil.reversalFen(transaction.getAmount().getTotal());
@@ -630,11 +631,11 @@ public class WechatPlugin implements Payment {
//获取微信设置 //获取微信设置
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
Config config =null; Config config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config=this.getCertificateConfig(setting); config = this.getCertificateConfig(setting);
}else { } else {
config=this.getPublicKeyConfig(setting); config = this.getPublicKeyConfig(setting);
} }
// 构建service // 构建service
RefundService refundService = new RefundService.Builder().config(config).build(); RefundService refundService = new RefundService.Builder().config(config).build();
@@ -646,7 +647,7 @@ public class WechatPlugin implements Payment {
request.setReason(refundLog.getRefundReason()); request.setReason(refundLog.getRefundReason());
request.setNotifyUrl(refundNotifyUrl(wechatPaymentSetting().getCallbackUrl(), PaymentMethodEnum.WECHAT)); request.setNotifyUrl(refundNotifyUrl(wechatPaymentSetting().getCallbackUrl(), PaymentMethodEnum.WECHAT));
Refund refund=refundService.create(request); Refund refund = refundService.create(request);
log.info("微信退款响应 {}", refund); log.info("微信退款响应 {}", refund);
refundLogService.save(refundLog); refundLogService.save(refundLog);
@@ -668,15 +669,15 @@ public class WechatPlugin implements Payment {
.build(); .build();
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
NotificationConfig config=null; NotificationConfig config = null;
if("CERT".equals(setting.getPublicType())){ if ("CERT".equals(setting.getPublicType())) {
config = new RSAAutoCertificateConfig.Builder() config = new RSAAutoCertificateConfig.Builder()
.merchantId(setting.getMchId()) .merchantId(setting.getMchId())
.privateKey(setting.getApiclientKey()) .privateKey(setting.getApiclientKey())
.merchantSerialNumber(setting.getSerialNumber()) .merchantSerialNumber(setting.getSerialNumber())
.apiV3Key(setting.getApiKey3()) .apiV3Key(setting.getApiKey3())
.build(); .build();
}else{ } else {
config = new RSAPublicKeyConfig.Builder() config = new RSAPublicKeyConfig.Builder()
.merchantId(setting.getMchId()) .merchantId(setting.getMchId())
.apiV3Key(setting.getApiKey3()) .apiV3Key(setting.getApiKey3())
@@ -721,10 +722,11 @@ public class WechatPlugin implements Payment {
/** /**
* 获取微信公钥配置 * 获取微信公钥配置
*
* @param setting * @param setting
* @return * @return
*/ */
private RSAPublicKeyConfig getPublicKeyConfig(WechatPaymentSetting setting){ private RSAPublicKeyConfig getPublicKeyConfig(WechatPaymentSetting setting) {
return return
new RSAPublicKeyConfig.Builder() new RSAPublicKeyConfig.Builder()
.merchantId(setting.getMchId()) .merchantId(setting.getMchId())
@@ -738,6 +740,7 @@ public class WechatPlugin implements Payment {
/** /**
* 获取微信证书配置 * 获取微信证书配置
*
* @param setting * @param setting
* @return * @return
*/ */
@@ -752,18 +755,19 @@ public class WechatPlugin implements Payment {
/** /**
* 修改订单支付单号 * 修改订单支付单号
* @param payParam 支付参数 *
* @param payParam 支付参数
* @param outOrderNo 订单号 * @param outOrderNo 订单号
*/ */
private void updateOrderPayNo(PayParam payParam,String outOrderNo ){ private void updateOrderPayNo(PayParam payParam, String outOrderNo) {
if("ORDER".equals(payParam.getOrderType())){ if ("ORDER".equals(payParam.getOrderType())) {
orderService.update(new LambdaUpdateWrapper<Order>() orderService.update(new LambdaUpdateWrapper<Order>()
.eq(Order::getSn,payParam.getSn()) .eq(Order::getSn, payParam.getSn())
.set(Order::getPayOrderNo,outOrderNo)); .set(Order::getPayOrderNo, outOrderNo));
}else if("TRADE".equals(payParam.getOrderType())){ } else if ("TRADE".equals(payParam.getOrderType())) {
orderService.update(new LambdaUpdateWrapper<Order>() orderService.update(new LambdaUpdateWrapper<Order>()
.eq(Order::getTradeSn,payParam.getSn()) .eq(Order::getTradeSn, payParam.getSn())
.set(Order::getPayOrderNo,outOrderNo)); .set(Order::getPayOrderNo, outOrderNo));
} }
} }
} }

View File

@@ -411,9 +411,12 @@ public class CouponActivityServiceImpl extends AbstractPromotionsServiceImpl<Cou
//判断优惠券的发送范围,获取会员列表 //判断优惠券的发送范围,获取会员列表
List<String> ids = new ArrayList<>(); List<String> ids = new ArrayList<>();
if (JSONUtil.isJsonArray(couponActivity.getActivityScopeInfo())) { String scopeInfo = couponActivity.getActivityScopeInfo();
JSONArray array = JSONUtil.parseArray(couponActivity.getActivityScopeInfo()); try {
JSONArray array = JSONUtil.parseArray(scopeInfo);
ids = array.toList(Map.class).stream().map(i -> i.get("id").toString()).collect(Collectors.toList()); ids = array.toList(Map.class).stream().map(i -> i.get("id").toString()).collect(Collectors.toList());
} catch (Exception ignore) {
// 非数组或格式错误时忽略,保持 ids 为空列表
} }
return memberService.listFieldsByMemberIds("id,nick_name", ids); return memberService.listFieldsByMemberIds("id,nick_name", ids);
} }

View File

@@ -863,7 +863,8 @@ public class EsGoodsIndexServiceImpl extends BaseElasticsearchService implements
// log.info("ES修改商品活动索引-原商品索引信息:{}", goodsIndex); // log.info("ES修改商品活动索引-原商品索引信息:{}", goodsIndex);
// log.info("ES修改商品活动索引-原商品索引活动信息:{}", promotionMap); // log.info("ES修改商品活动索引-原商品索引活动信息:{}", promotionMap);
//如果活动已结束 //如果活动已结束
if (promotion.getPromotionStatus().equals(PromotionsStatusEnum.END.name()) || promotion.getPromotionStatus().equals(PromotionsStatusEnum.CLOSE.name())) {//如果存在活动 //如果存在活动
if (promotion.getPromotionStatus().equals(PromotionsStatusEnum.END.name()) || promotion.getPromotionStatus().equals(PromotionsStatusEnum.CLOSE.name())) {
//删除活动 //删除活动
promotionMap.remove(key); promotionMap.remove(key);
} else { } else {

View File

@@ -105,22 +105,22 @@ public class HuaweiSmsPlugin implements SmsPlugin {
} }
// 发送短信
private void sendSms(String signName, String mobile, String param, String templateCode) throws Exception { private void sendSms(String signName, String mobile, String param, String templateCode) throws Exception {
//必填,请参考"开发准备"获取如下数据,替换为实际值 //必填,请参考"开发准备"获取如下数据,替换为实际值
String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1"; //APP接入地址(在控制台"应用管理"页面获取)+接口访问URI //APP接入地址(在控制台"应用管理"页面获取)+接口访问URI
String appKey = smsSetting.getHuaweiAppKey(); //APP_Key String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1";
String appSecret = smsSetting.getHuaweiAppSecret(); //APP_Secret String appKey = smsSetting.getHuaweiAppKey();
String sender = smsSetting.getHuaweiSender(); //国内短信签名通道号或国际/港澳台短信通道号 String appSecret = smsSetting.getHuaweiAppSecret();
String templateId = templateCode; //模板ID String sender = smsSetting.getHuaweiSender();
//条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称 // 模板ID
//国际/港澳台短信不用关注该参数 String templateId = templateCode;
String signature = smsSetting.getHuaweiSignature(); //签名名称
//必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔 // 签名名称
String receiver = mobile; //短信接收人号码 String signature = smsSetting.getHuaweiSignature();
//选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告 String receiver = mobile;
String statusCallBack = ""; String statusCallBack = "";
/** /**
@@ -130,7 +130,8 @@ public class HuaweiSmsPlugin implements SmsPlugin {
* 模板中的每个变量都必须赋值,且取值不能为空 * 模板中的每个变量都必须赋值,且取值不能为空
* 查看更多模板和变量规范:产品介绍>模板和变量规范 * 查看更多模板和变量规范:产品介绍>模板和变量规范
*/ */
String templateParas = param; //模板变量此处以单变量验证码短信为例请客户自行生成6位验证码并定义为字符串类型以杜绝首位0丢失的问题例如002569变成了2569 //模板变量此处以单变量验证码短信为例请客户自行生成6位验证码并定义为字符串类型以杜绝首位0丢失的问题例如002569变成了2569
String templateParas = param;
//请求Body,不携带签名名称时,signature请填null //请求Body,不携带签名名称时,signature请填null
String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature); String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);
@@ -179,12 +180,14 @@ public class HuaweiSmsPlugin implements SmsPlugin {
connection.connect(); connection.connect();
out = new OutputStreamWriter(connection.getOutputStream()); out = new OutputStreamWriter(connection.getOutputStream());
out.write(body); //发送请求Body参数
// 发送请求Body参数
out.write(body);
out.flush(); out.flush();
out.close(); out.close();
int status = connection.getResponseCode(); int status = connection.getResponseCode();
if (200 == status) { //200 if (200 == status) {
is = connection.getInputStream(); is = connection.getInputStream();
} else { //400/401 } else { //400/401
is = connection.getErrorStream(); is = connection.getErrorStream();
@@ -194,7 +197,9 @@ public class HuaweiSmsPlugin implements SmsPlugin {
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
result.append(line); result.append(line);
} }
System.out.println(result.toString()); //打印响应消息实体
// 打印响应消息实体
System.out.println(result.toString());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@@ -275,8 +280,12 @@ public class HuaweiSmsPlugin implements SmsPlugin {
return null; return null;
} }
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String time = sdf.format(new Date()); //Created
String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce // Created
String time = sdf.format(new Date());
// Nonce
String nonce = UUID.randomUUID().toString().replace("-", "");
MessageDigest md; MessageDigest md;
byte[] passwordDigest = null; byte[] passwordDigest = null;
@@ -289,8 +298,8 @@ public class HuaweiSmsPlugin implements SmsPlugin {
e.printStackTrace(); e.printStackTrace();
} }
//如果JDK版本是1.8,请加载原生Base64类,并使用如下代码 // PasswordDigest
String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest); //PasswordDigest String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest);
//如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码 //如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
//String passwordDigestBase64Str = Base64.encodeBase64String(passwordDigest); //PasswordDigest //String passwordDigestBase64Str = Base64.encodeBase64String(passwordDigest); //PasswordDigest
//若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正 //若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正

View File

@@ -150,8 +150,9 @@ public class ManagerAuthenticationFilter extends BasicAuthenticationFilter {
try { try {
Claims claims Claims claims
= Jwts.parser() = Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(jwt).getBody(); .parseClaimsJws(jwt).getBody();
//获取存储在claims中的用户信息 //获取存储在claims中的用户信息
String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();

View File

@@ -98,13 +98,14 @@ public class StoreAuthenticationFilter extends BasicAuthenticationFilter {
try { try {
Claims claims Claims claims
= Jwts.parser() = Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(jwt).getBody(); .parseClaimsJws(jwt).getBody();
//获取存储在claims中的用户信息 //获取存储在claims中的用户信息
String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();
AuthUser authUser = new Gson().fromJson(json, AuthUser.class); AuthUser authUser = new Gson().fromJson(json, AuthUser.class);
//校验redis中是否有权限 //校验redis中是否有权限
if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.STORE, authUser.getId()) + jwt)) { if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.STORE, authUser.getId()) + jwt)) {
//用户角色 //用户角色