1、微信接口文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
2、具体代码
package com.lyn.v5.polish.infrastructure.utils;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
public class WeixinPayUtils {
/**
* https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
*
* @param parameters
* @param key
* @return
*/
public static String createSign(SortedMap<String, String> parameters, String key) {
StringBuffer sb = new StringBuffer();
StringBuffer sbkey = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (StringUtils.isNotBlank(v.toString())) {
sb.append(k + "=" + v + "&");
sbkey.append(k + "=" + v + "&");
}
}
sbkey = sbkey.append("key=" + key);
return MD5Util.textToMD5U32(sbkey.toString()).toUpperCase();
}
public static void main(String[] args) throws Exception {
String key = "192006250b4c09247ec02edce69f6a2d";
String s = WXPayUtil.generateSignedXml(initRequestMapTest(key), key);
System.out.println(s);
}
/**
* 此测试方法所用举例数据,与官方文档中的数据同
* @param key
* @return
*/
private static SortedMap<String, String> initRequestMapTest(String key) {
SortedMap<String, String> requestMap = new TreeMap();
requestMap.put("appid", "wxd930ea5d5a258f4f");
requestMap.put("mch_id", "10000100");
requestMap.put("device_info", "1000");
requestMap.put("body", "test");
requestMap.put("nonce_str", "ibuaiVcKdpRxkhJA");//随机串生成 WXPayUtil.generateNonceStr()
requestMap.put("sign", createSign(requestMap, key));
return requestMap;
}
}
3、执行结果
以下粘贴了微信接口文档中的示例,可见,二者生成的最终请求串是相同的。