微信支付body中文时,签名失败,乱码问题解决方案

主要是body中文问题,解决起来真是醉了,百度了好多文章都没有彻底解决的,各种问题,害的我哭了好几天!废话不多说了,开始进入正题:

因为公司的项目要用微信支付,部署时候发现总是报签名错,经过排查,是编码问题。(如果大家没时间,请直接查看第三种解决方案


 

第一种解决方案:

   tomcat在window环境默认编码是gbk,所以要设置tomcat编码为utf-8。

    第一步:在catalina.bat里面的头部第二行添加

set JAVA_OPTS=-Xms128m -Xmx512m -XX:MaxPermSize=256m -Dfile.encoding=utf-8 -Dsun.jnu.encoding=utf-8
让java环境使用utf-8编码

第二步:在server.xml添加

URIEncoding="UTF-8" useBodyEncodingForURI="true",使tomcat发送的请求使用utf-8,如下面代码

  1. <Connector port="8081" protocol="HTTP/1.1"

  2. connectionTimeout="20000"

  3. redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true" />

   控制台可能会有乱码,但是改成gbk就没事,但是微信签名失败


第二种解决方案:进行body转码

String body  = new String("body中文字段值".toString().getBytes("ISO8859-1"),"UTF-8");

但是:微信返回的商品名会出现乱码


第三种解决方案:修改签名MD5编码(这个解决方案才是王道

tomcat在window环境默认编码是gbk,所以在进行md5签名的时候设置编码,为utf-8就可以了。

这个是我用的MD5签名工具类:

public class MD5Util {

	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname))
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes()));
			else
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes(charsetname)));
		} catch (Exception exception) {
		}
		return resultString;
	}

	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

}

猜你喜欢

转载自blog.csdn.net/ling1234ling1234/article/details/81353909