//生成随机号,防重发
private String getNonceStr() {
Random random = new Random();
return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
}
//生成订单号
private String getOutTradNo() {
Random random = new Random();
return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
} 5.参考下单API开始拼单
//构造商品参数集合,因为需要排序,所以用到了SortedMap
SortedMap
/** * 微信支付签名算法sign
* @param characterEncoding 签名编码(UTF-8)
* @param parameters 要签名的参数的集合
* @param key 商户自己设置的key
*/
public static String createSign(String characterEncoding, SortedMap parameters, String key){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + key);
System.out.println(sb.toString());
String sign = WxMd5.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
System.out.println(sign);
return sign;
}
public class WxMd5 {
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("utf-8")));
} 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"};
}
6.将订单信息拼成xml格式 由于微信服务器只接收xml格式的数据,需要将订单信息拼成xml格式
//3.因为统一下单接口需要以xml格式post发送给微信,所以我们先拼接xml格式的参数:
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("");
Set es = parameters.entrySet();
//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v1 = entry.getValue();
xmlBuilder.append("<").append(k).append(">");
xmlBuilder.append(v1);
xmlBuilder.append("").append(k).append(">");
}
xmlBuilder.append("");
System.out.println(xmlBuilder.toString());
Log.d("tag", "拼装的xml信息" + xmlBuilder.toString());
try {
//异步线程获取微信服务器返回的信息
new GetPrepayId(new String(xmlBuilder.toString().getBytes(), "ISO8859-1")).execute();
//这一步非常重要,不这样转换编码的话,传递中文就会报“签名错误”,这是很多人都会遇到的错误。}
catch (Exception e) {
e.printStackTrace();
}