微信小程序调用支付接口官方文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
在上一节中其实已经准备好了调起支付接口的各项参数,只需使用wx.requestPayment()即可
目录:
微信小程序接入微信支付(一):大概流程与准备需知
微信小程序接入微信支付(二):后台调用统一下单接口
微信小程序接入微信支付(三):小程序端调用支付接口
微信小程序接入微信支付(四):接收支付结果通知与沙箱测试
代码如下:
wx.requestPayment(
{
'timeStamp': '',
'nonceStr': '',
'package': '',
'signType': 'MD5',
'paySign': '',
'success':function(res){},
'fail':function(res){}, //fail包含取消支付和支付失败等多种情况,记得区分
'complete':function(res){}
})
为了严谨考虑,通常会在接收到接口返回的结果后再次去后台调用微信支付查询订单接口,二次确认订单状态,从而保证订单是否支付成功,以便做出相应的处理。
微信支付查询订单接口官方文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_2
代码:
/**
* 请求微信查询订单接口,获取订单状态, 把订单状态返回给小程序端
*
* @param order_code 商户订单号
* @return
* @throws Exception
*/
@GetMapping("/queryorder")
@ResponseBody
public String queryOrder(@Param("order_code") String order_code) throws Exception {
//
Map<String, String> map = new HashMap<>();
map.put("appid", appId);
map.put("mch_id", mchId);
map.put("out_trade_no", order_code);
map.put("nonce_str", getRandomString());
map.put("sign_type", "MD5");
//生成符合规格的签名串
String stringSignTemp = getParamStr(map,realKey); //realKey -- key
//进行MD5运算,并转为大写,获得sign参数的值
String signValue = MD5(stringSignTemp.toString()).toUpperCase();
//把sign放入map中
map.put("sign",signValue);
//当sign参数有值时
if (map.get("sign").trim().length()>0) {
//map转义为xml格式
String requestParam = new String(mapToXml(map).getBytes(),"utf-8");
LOG.info("----queryorder requestParam: " + requestParam);
//发送请求
String result = sendPostParam(queryOrderUrl, requestParam); //queryOrderUrl -- https://api.mch.weixin.qq.com/pay/orderquery
LOG.info("----queryorder result: " + result);
//将返回的结果从xml字符串转义为map
Map<String, String> resultMap = xmlToMap(result);
String return_code;
if (resultMap.containsKey("return_code")) {
return_code = resultMap.get("return_code");
}
else {
throw new Exception(String.format("No `return_code` in XML: %s", result));
}
if (return_code.equals("FAIL")) {
throw new Exception("return_code : fail, the result xml string is :" + result);
}
else if (return_code.equals("SUCCESS")) {
//只传trade_state
if (resultMap.get("trade_state") != null) {
return resultMap.get("trade_state");
}else {
throw new Exception("query order warning: " + resultMap.get("err_code") + "--" + resultMap.get("err_code_des") );
}
}
else {
throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, result));
}
}
return null;
}
相关外部方法写在上一节:微信小程序接入微信支付(二):后台调用统一下单接口