解决微信支付 errCode返回-1

最近 新接入一个项目的微信支付功能,遇到回调老是返回-1

android端要做的事很简单

wxApi = WXAPIFactory.createWXAPI(getView(), null);
wxApi.registerApp(WXConstant.APP_ID);// 将该app注册到微信
PayReq request = new PayReq();
request.appId = wxPayBean.getAppid();
request.partnerId = wxPayBean.getPartnerid();
request.prepayId = wxPayBean.getPrepayid();
request.packageValue = wxPayBean.getPackageX();
request.nonceStr = wxPayBean.getNoncestr();
request.timeStamp = wxPayBean.getTimestamp();
request.sign = wxPayBean.getSign();
wxApi.sendReq(request);
除了sign外其他字段都很好检测,关键是sign.我们就是sign计算错误,耽误了挺长时间.

首先微信有验证sign的工具

https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=20_1

请先验证sign是否正确

再贴生成sign的函数

SortedMap packageParams = new TreeMap();
packageParams.put("appid", appId);
packageParams.put("mch_id", mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("out_trade_no", out_trade_no);


// 这里写的金额为1 分到时修改
packageParams.put("total_fee", totalFee);


packageParams.put("out_refund_no", out_refund_no);


packageParams.put("refund_fee", refund_fee);


packageParams.put("op_user_id", op_user_id);

/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
public String createSign(SortedMap packageParams) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
String sign = MD5Util.MD5Encode(sb.toString(), this.charset)
.toUpperCase();
return sign;


}

你可能感兴趣的:(android)