修复:商品描述过长导致支付失败的bug

This commit is contained in:
2025-08-10 13:30:37 +08:00
parent 7c3188fbf6
commit 4a1fa6911e
2 changed files with 159 additions and 1 deletions

View File

@@ -141,7 +141,13 @@ import com.gxwebsoft.common.core.service.PaymentCacheService;
request.setAmount(amount);
request.setAppid(payment.getAppId());
request.setMchid(payment.getMchId());
request.setDescription(order.getComments());
// 微信支付description字段限制127字节需要截断处理
String description = order.getComments();
if (description != null) {
// 确保字节数不超过127字节
description = truncateToByteLimit(description, 127);
}
request.setDescription(description);
request.setOutTradeNo(order.getOrderNo());
request.setAttach(order.getTenantId().toString());
final Payer payer = new Payer();
@@ -667,4 +673,43 @@ import com.gxwebsoft.common.core.service.PaymentCacheService;
}
}
/**
* 截断字符串以确保字节数不超过指定限制
* 微信支付description字段限制127字节
*
* @param text 原始文本
* @param maxBytes 最大字节数
* @return 截断后的文本
*/
private String truncateToByteLimit(String text, int maxBytes) {
if (text == null || text.isEmpty()) {
return text;
}
byte[] bytes = text.getBytes(java.nio.charset.StandardCharsets.UTF_8);
if (bytes.length <= maxBytes) {
return text;
}
// 截断字节数组但要确保不会截断UTF-8字符的中间
int truncateLength = maxBytes;
while (truncateLength > 0) {
byte[] truncated = new byte[truncateLength];
System.arraycopy(bytes, 0, truncated, 0, truncateLength);
try {
String result = new String(truncated, java.nio.charset.StandardCharsets.UTF_8);
// 检查是否有无效字符被截断的UTF-8字符
if (!result.contains("\uFFFD")) {
return result;
}
} catch (Exception e) {
// 继续尝试更短的长度
}
truncateLength--;
}
return ""; // 如果无法安全截断,返回空字符串
}
}