记一次微信支付的坑-1
一直返回-1
1 包名一定要和平台上的一致
2签名改成小写
3 怀疑返回的sign不对,自己本地签名,果然是返回的sign不对
WXPayRegister(mContext);
req = new PayReq();
req.appId = json.optString("appid");
req.partnerId = json.optString("partnerid");
req.prepayId = json.optString("prepayid");
req.nonceStr = json.optString("noncestr");
req.timeStamp = json.optString("timestamp");
req.packageValue = json.optString("package");
req.sign = json.optString("sign");
req.extData = "app data"; // optional
//自己签名
// StringBuffer weiXinVo=new StringBuffer();
// SortedMap<String, String> signParam = new TreeMap<String, String>();
// signParam.put("appid", req.appId);//app_id
// signParam.put("partnerid", req.partnerId);//微信商户账号
// signParam.put("prepayid", req.prepayId);//预付订单id
// signParam.put("package", req.packageValue);//默认sign=WXPay
// signParam.put("noncestr", req.nonceStr);//自定义不重复的长度不长于32位
// signParam.put("timestamp",req.timeStamp);//北京时间时间戳
// String signAgain = createSign("UTF-8", signParam);//再次生成签名
// signParam.put("sign", signAgain);
// Log.e("roach", "run: "+signAgain );
// req.sign = signAgain;
//定义签名,微信根据参数字段的ASCII码值进行排序 加密签名,故使用SortMap进行参数排序
public static String createSign(String characterEncoding,SortedMap<String,String> parameters) {
StringBuffer sb = 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 (null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + "42903cbd6b1ca3ed0e9811cb07822ac3");//最后加密时添加商户密钥,由于key值放在最后,所以不用添加到SortMap里面去,单独处理,编码方式采用UTF-8
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
import java.security.MessageDigest;
/**
* 作者:Administrator on 2017/12/20 09:45
* 邮箱:android_gaoxuge@163.com
*/
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" };
}