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 {
Claims claims
= Jwts.parser()
= Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(jwt).getBody();
//获取存储在claims中的用户信息
// 获取存储在claims中的用户信息
String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();
AuthUser authUser = new Gson().fromJson(json, AuthUser.class);
//校验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<>();
auths.add(new SimpleGrantedAuthority("ROLE_" + authUser.getRole().name()));

View File

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

View File

@@ -92,8 +92,9 @@ public class UserContext {
try {
//获取token的信息
Claims claims
= Jwts.parser()
= Jwts.parserBuilder()
.setSigningKey(SecretKeyUtil.generalKeyByDecoders())
.build()
.parseClaimsJws(accessToken).getBody();
//获取存储在claims中的用户信息
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 {
BufferedReader bufferedReader = null;
InputStreamReader reader = null;
//获取输入流
@@ -163,9 +162,16 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
//继续读取下一行流直到line为空
line = bufferedReader.readLine();
}
if (CharSequenceUtil.isNotEmpty(body) && Boolean.TRUE.equals(JSONUtil.isJsonObj(body.toString()))) {
//将body转换为map
Map<String, Object> map = JSONUtil.parseObj(body.toString());
// 兼容替换:不再使用过时的 JSONUtil.isJsonObj(String),改为尝试解析并捕获异常
if (CharSequenceUtil.isNotEmpty(body)) {
Map<String, Object> map = null;
try {
map = JSONUtil.parseObj(body.toString());
} catch (Exception ignore) {
map = null;
}
if (map != null) {
//创建空的map用于存储结果
Map<String, Object> resultMap = new HashMap<>(map.size());
//遍历数组
@@ -205,6 +211,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
}
};
}
}
//将json字符串转换为字节
final ByteArrayInputStream bis = new ByteArrayInputStream(body.toString().getBytes());

View File

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

View File

@@ -90,7 +90,8 @@ public abstract class BaseElasticsearchService {
request.settings(Settings.builder()
.put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards())
.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));
//创建索引

View File

@@ -535,7 +535,8 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
try (InputStream inputStream = file.getInputStream()) {
// 使用 WorkbookFactory.create 方法读取 Excel 文件
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0); // 我们只读取第一个sheet
// 我们只读取第一个sheet
Sheet sheet = workbook.getSheetAt(0);
// 检查第一个sheet的行数是否超过10002行
if (sheet.getPhysicalNumberOfRows() > 10002) {
@@ -1039,7 +1040,8 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
// 设置下拉列表数据验证
DataValidationHelper validationHelper = templateSheet.getDataValidationHelper();
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);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);

View File

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

View File

@@ -1,13 +1,10 @@
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.lili.common.context.ThreadContextHolder;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.ApiProperties;
import cn.lili.common.properties.DomainProperties;
import cn.lili.common.utils.BeanUtil;
import cn.lili.common.utils.SnowFlake;
@@ -40,7 +37,6 @@ import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
@@ -90,13 +86,14 @@ public class AliPayPlugin implements Payment {
payModel.setBody(cashierParam.getTitle());
payModel.setSubject(cashierParam.getDetail());
payModel.setTotalAmount(cashierParam.getPrice() + "");
//回传数据
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8));
//3分钟超时
payModel.setTimeoutExpress("3m");
payModel.setOutTradeNo(outTradeNo);
payModel.setProductCode("QUICK_WAP_PAY");
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));
AliPayRequest.wapPay(response, payModel, callbackUrl(alipayPaymentSetting.getCallbackUrl(), PaymentMethodEnum.ALIPAY),
notifyUrl(alipayPaymentSetting.getCallbackUrl(), PaymentMethodEnum.ALIPAY));
@@ -130,8 +127,8 @@ public class AliPayPlugin implements Payment {
//3分钟超时
payModel.setTimeoutExpress("3m");
//回传数据
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8));
//回传数据(替换 Hutool 的 URLEncoder 为 JDK 的 java.net.URLEncoder
payModel.setPassbackParams(java.net.URLEncoder.encode(BeanUtil.formatKeyValuePair(payParam), "UTF-8"));
payModel.setOutTradeNo(outTradeNo);
payModel.setProductCode("QUICK_MSECURITY_PAY");
@@ -164,8 +161,8 @@ public class AliPayPlugin implements Payment {
payModel.setSubject(cashierParam.getDetail());
payModel.setTotalAmount(cashierParam.getPrice() + "");
//回传数据
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8));
//回传数据(替换 Hutool 的 URLEncoder 为 JDK 的 java.net.URLEncoder
payModel.setPassbackParams(java.net.URLEncoder.encode(BeanUtil.formatKeyValuePair(payParam), "UTF-8"));
payModel.setTimeoutExpress("3m");
payModel.setOutTradeNo(outTradeNo);
log.info("支付宝扫码:{}", payModel);
@@ -314,7 +311,8 @@ public class AliPayPlugin implements Payment {
return;
}
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());
@@ -331,6 +329,8 @@ public class AliPayPlugin implements Payment {
}
} catch (AlipayApiException 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;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.ResultCode;
@@ -67,7 +66,7 @@ public class UnionPayPlugin implements Payment {
String ip = IpKit.getRealIp(request);
//第三方付款订单
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()
.service(ServiceEnum.NATIVE.toString())
.mch_id(unionPaymentSetting.getUnionPayMachId())
@@ -94,12 +93,10 @@ public class UnionPayPlugin implements Payment {
@Override
public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) {
try {
CashierParam cashierParam = cashierSupport.cashierParam(payParam);
UnionPaymentSetting unionPaymentSetting = this.unionPaymentSetting();
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
String ip = IpKit.getRealIp(request);
Map<String, String> params = UnifiedOrderModel.builder()
@@ -135,9 +132,7 @@ public class UnionPayPlugin implements Payment {
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
return null;
}
}
@@ -147,10 +142,12 @@ public class UnionPayPlugin implements Payment {
String buyerId="";
CashierParam cashierParam = cashierSupport.cashierParam(payParam);
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
String ip = IpKit.getRealIp(request);
try {
String attach = java.net.URLEncoder.encode(JSONUtil.toJsonStr(payParam), StandardCharsets.UTF_8.name());
if (StrUtil.isEmpty(buyerLogonId) && StrUtil.isEmpty(buyerId)) {
log.error("buyer_logon_id buyer_id 不能同时为空");
return null;

View File

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

View File

@@ -411,9 +411,12 @@ public class CouponActivityServiceImpl extends AbstractPromotionsServiceImpl<Cou
//判断优惠券的发送范围,获取会员列表
List<String> ids = new ArrayList<>();
if (JSONUtil.isJsonArray(couponActivity.getActivityScopeInfo())) {
JSONArray array = JSONUtil.parseArray(couponActivity.getActivityScopeInfo());
String scopeInfo = couponActivity.getActivityScopeInfo();
try {
JSONArray array = JSONUtil.parseArray(scopeInfo);
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);
}

View File

@@ -863,7 +863,8 @@ public class EsGoodsIndexServiceImpl extends BaseElasticsearchService implements
// log.info("ES修改商品活动索引-原商品索引信息:{}", goodsIndex);
// 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);
} 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 {
//必填,请参考"开发准备"获取如下数据,替换为实际值
String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1"; //APP接入地址(在控制台"应用管理"页面获取)+接口访问URI
String appKey = smsSetting.getHuaweiAppKey(); //APP_Key
String appSecret = smsSetting.getHuaweiAppSecret(); //APP_Secret
String sender = smsSetting.getHuaweiSender(); //国内短信签名通道号或国际/港澳台短信通道号
String templateId = templateCode; //模板ID
//APP接入地址(在控制台"应用管理"页面获取)+接口访问URI
String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1";
String appKey = smsSetting.getHuaweiAppKey();
String appSecret = smsSetting.getHuaweiAppSecret();
String sender = smsSetting.getHuaweiSender();
//条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
//国际/港澳台短信不用关注该参数
String signature = smsSetting.getHuaweiSignature(); //签名名称
// 模板ID
String templateId = templateCode;
//必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
String receiver = mobile; //短信接收人号码
// 签名名称
String signature = smsSetting.getHuaweiSignature();
//选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
String receiver = mobile;
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
String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);
@@ -179,12 +180,14 @@ public class HuaweiSmsPlugin implements SmsPlugin {
connection.connect();
out = new OutputStreamWriter(connection.getOutputStream());
out.write(body); //发送请求Body参数
// 发送请求Body参数
out.write(body);
out.flush();
out.close();
int status = connection.getResponseCode();
if (200 == status) { //200
if (200 == status) {
is = connection.getInputStream();
} else { //400/401
is = connection.getErrorStream();
@@ -194,7 +197,9 @@ public class HuaweiSmsPlugin implements SmsPlugin {
while ((line = in.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString()); //打印响应消息实体
// 打印响应消息实体
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
@@ -275,8 +280,12 @@ public class HuaweiSmsPlugin implements SmsPlugin {
return null;
}
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;
byte[] passwordDigest = null;
@@ -289,8 +298,8 @@ public class HuaweiSmsPlugin implements SmsPlugin {
e.printStackTrace();
}
//如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest); //PasswordDigest
// PasswordDigest
String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest);
//如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
//String passwordDigestBase64Str = Base64.encodeBase64String(passwordDigest); //PasswordDigest
//若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正

View File

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

View File

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