修复:商品描述过长导致支付失败的bug
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import com.gxwebsoft.common.core.utils.WechatPayUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@@ -14,45 +15,6 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
@SpringBootTest
|
||||
public class WechatPayDescriptionTest {
|
||||
|
||||
/**
|
||||
* 截断字符串以确保字节数不超过指定限制
|
||||
* 微信支付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(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, StandardCharsets.UTF_8);
|
||||
// 检查是否有无效字符(被截断的UTF-8字符)
|
||||
if (!result.contains("\uFFFD")) {
|
||||
return result;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 继续尝试更短的长度
|
||||
}
|
||||
truncateLength--;
|
||||
}
|
||||
|
||||
return ""; // 如果无法安全截断,返回空字符串
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTruncateToByteLimit() {
|
||||
// 测试正常情况 - 字符串长度在限制内
|
||||
@@ -91,7 +53,7 @@ public class WechatPayDescriptionTest {
|
||||
public void testSpecificErrorCase() {
|
||||
// 测试错误信息中的具体案例
|
||||
String errorText = "【湾区认证】【百千万工程帮扶产品 通过远方320项检测 湾区认证 丰江桥佛手瓜面】独特风味低脂轻食便捷速食非油炸 720g/袋";
|
||||
|
||||
|
||||
// 验证原始文本确实超过127字节
|
||||
int originalBytes = errorText.getBytes(StandardCharsets.UTF_8).length;
|
||||
System.out.println("原始文本: " + errorText);
|
||||
@@ -101,10 +63,10 @@ public class WechatPayDescriptionTest {
|
||||
// 测试截断
|
||||
String truncated = truncateToByteLimit(errorText, 127);
|
||||
int truncatedBytes = truncated.getBytes(StandardCharsets.UTF_8).length;
|
||||
|
||||
|
||||
System.out.println("截断后文本: " + truncated);
|
||||
System.out.println("截断后字节数: " + truncatedBytes);
|
||||
|
||||
|
||||
// 验证截断后的文本符合要求
|
||||
assertNotNull(truncated);
|
||||
assertTrue(truncatedBytes <= 127, "截断后字节数应该不超过127");
|
||||
|
||||
Reference in New Issue
Block a user