小程序頁面
<button class='pay_fixed_right' formType="submit1" bindtap='pay' style="background:{{color}}">去支付</button>
小程序js 中間**就是需要替換的域名苔巨,openid需要自己小程序的
pay: function (e) {
var openId = "o7Rrj5M-METpuTV8mNxv6_6gn1sw";
var tradeNo = "85511613375";
var amount = "0.01";
var body = "餐費(fèi)";
wx.request({
url: 'http://**/app/pay',
method: 'POST',
data: {
openId: openId,
tradeNo: tradeNo,
tradeType: 'JSAPI',
amount: amount,
body: body,
}, //參數(shù)為鍵值對(duì)字符串
header: {
//設(shè)置參數(shù)內(nèi)容類型為x-www-form-urlencoded
"Accept": "*/*", 'Content-Type': 'application/json'
},
success: function (e) {
var data = e.data.wxPayResponse;
wx.requestPayment({
'timeStamp': data.timeStamp.toString(),
'nonceStr': data.nonceStr,
'package': data.package_wx,
'signType': 'MD5',
'paySign': data.sign,
success: function (event) {
// success
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
});
//處理 業(yè)務(wù)邏輯
},
fail: function (error) {
// fail
console.log("支付失敗")
wx.showToast({
title: '支付失敗',
icon: 'none',
duration: 2000
});
}
})
}
})
}
代碼刪減了些右冻,不過問題不大
開始服務(wù)端了
AppWxPayController.java
@Autowired
private WxPayService wxPayService;
private Logger logger = LoggerFactory.getLogger(getClass());
@PostMapping("pay")
@ApiOperation("微信支付")
public R pay(@RequestBody PayParam payParam){
WxPayEntity wxPayEntity=wxPayService.pay(payParam);//請求訂單統(tǒng)一接口
return R.ok().put("wxPayResponse", wxPayEntity);
}
@PostMapping("payNotifyUrl")
@ApiOperation("微信支付回調(diào)")
public String payNotifyUrl(HttpServletRequest request){
String xmlString = WxPayUtils.getXmlString(request);
logger.info("----微信支付回調(diào)接收到的數(shù)據(jù)如下:---" + xmlString);
return wxPayService.payAsyncNotify(xmlString);
}
服務(wù)端支付接口和回調(diào)
/**
* 調(diào)用微信支付-統(tǒng)一下單接口
* @param payParam 用戶傳入的訂單信息
* @return
*/
WxPayEntity pay(PayParam payParam);
WxPayService.java
service下面是實(shí)現(xiàn)類
WxPayServiceImpl.java 統(tǒng)一下單+回調(diào)
private Logger logger = LoggerFactory.getLogger(getClass());
/* (non-Javadoc)
* <p>Title: pay</p>
* <p>Description: 統(tǒng)一下單接口</p>
* @param payParam
* @return
* @see com.alpha.modules.wxpay.service.WxPayService#pay(com.alpha.modules.wxpay.form.PayParam)
*/
public WxPayEntity pay(PayParam payParam) {
WxPayUnifiedorderResponse response = null;
try {
//組織統(tǒng)一下單接口請求參數(shù)
WxPayUnifiedorderRequest request = new WxPayUnifiedorderRequest();
request.setAppid(WxConfigure.getAppID());
request.setBody(payParam.getBody());
request.setMchId(WxConfigure.getMch_id());
request.setNonceStr(WxPayUtils.getRandomStr(32));
request.setNotifyUrl(WxConfigure.getPayNotifyUrl());
request.setOpenid(payParam.getOpenId());
request.setOutTradeNo(payParam.getTradeNo());
request.setSpbillCreateIp(WxPayUtils.getIpAddr());//獲取ip
request.setTotalFee(WxPayUtils.yuanToFen(payParam.getAmount()));
request.setTradeType(payParam.getTradeType());
request.setSign(WxPayUtils.signByMD5(request, WxConfigure.getKey()));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.mch.weixin.qq.com")
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
String xml = WxPayUtils.objToXML(request);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
Call<WxPayUnifiedorderResponse> call = retrofit.create(WxPayApi.class).UNIFIEDORDER_RESPONSE_CALL(requestBody);
Response<WxPayUnifiedorderResponse> retrofitResponse = call.execute();
response = retrofitResponse.body();
if(!response.getReturnCode().equals("SUCCESS")) {
throw new RuntimeException("【微信統(tǒng)一支付】發(fā)起支付, returnCode != SUCCESS, returnMsg = " + response.getReturnMsg());
}
if (!response.getResultCode().equals("SUCCESS")) {
throw new RuntimeException("【微信統(tǒng)一支付】發(fā)起支付, resultCode != SUCCESS, err_code = " + response.getErrCode() + " err_code_des=" + response.getErrCodeDes());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buildWxPayResponse(response);
}
private WxPayEntity buildWxPayResponse(WxPayUnifiedorderResponse wxPayUnifiedorderResponse) {
String timeStamps = String.valueOf(System.currentTimeMillis() / 1000L); //微信接口時(shí)間戳為10位字符串
String package_wx = "prepay_id=" + wxPayUnifiedorderResponse.getPrepayId(); //返回前臺(tái)package字段值為
WxPayEntity wxPayEntity = new WxPayEntity();
try {
wxPayEntity.setTimeStamp(timeStamps);
wxPayEntity.setNonceStr(WxPayUtils.getRandomStr(32));
wxPayEntity.setPackage_wx(package_wx);
wxPayEntity.setAppid(WxConfigure.getAppID());
wxPayEntity.setSignType("MD5");
Map<String, String> wxResMap = buildWxResMap(wxPayEntity);
wxPayEntity.setSign(WxPayUtils.signByMD5(wxResMap, WxConfigure.getKey()));
} catch (Exception e) {
e.printStackTrace();
}
return wxPayEntity;
}
/**
* 構(gòu)造返回小程序簽名參數(shù)(小程序支付二次簽名)
* @param wxPayEntity
* @return
*/
private Map<String,String> buildWxResMap(WxPayEntity wxPayEntity) {
Map<String, String> wxResMap = new HashMap<>();
wxResMap.put("appId", wxPayEntity.getAppid());
wxResMap.put("nonceStr", wxPayEntity.getNonceStr());
wxResMap.put("package", wxPayEntity.getPackage_wx());
wxResMap.put("signType", "MD5");
wxResMap.put("timeStamp", wxPayEntity.getTimeStamp());
return wxResMap;
}
/* (non-Javadoc)
* <p>Title: payAsyncNotify</p>
* <p>Description: 支付回調(diào)接口</p>
* @param notifyData
* @return
* @see com.alpha.modules.wxpay.service.WxPayService#payAsyncNotify(java.lang.String)
*/
public String payAsyncNotify(String notifyData) {
WxPayNotifyResponse wxPayNotifyResponse = (WxPayNotifyResponse) WxPayUtils.xmlToObj(notifyData, WxPayNotifyResponse.class);
try {
String sign= WxPayUtils.signByMD5(wxPayNotifyResponse, WxConfigure.getKey());
if (sign.equals(wxPayNotifyResponse.getSign())) {
throw new RuntimeException("【微信支付異步通知】簽名驗(yàn)證失敗");
}
if(!wxPayNotifyResponse.getReturnCode().equals("SUCCESS")) {
throw new RuntimeException("【微信支付異步通知】發(fā)起支付, returnCode != SUCCESS, returnMsg = " + wxPayNotifyResponse.getReturnMsg());
}
//該訂單已支付直接返回
if (!wxPayNotifyResponse.getResultCode().equals("SUCCESS")
&& wxPayNotifyResponse.getErrCode().equals("ORDERPAID")) {
logger.info("【微信付款】付款成功通知:"+wxPayNotifyResponse.getOutTradeNo()+"付款成功");
return WxPayUtils.returnXML(wxPayNotifyResponse.getReturnCode());
}
if (!wxPayNotifyResponse.getResultCode().equals("SUCCESS")) {
throw new RuntimeException("【微信支付異步通知】發(fā)起支付, resultCode != SUCCESS, err_code = " + wxPayNotifyResponse.getErrCode() + " err_code_des=" + wxPayNotifyResponse.getErrCodeDes());
}
logger.info("【微信付款】付款成功通知:"+wxPayNotifyResponse.getOutTradeNo()+"付款成功");
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return WxPayUtils.returnXML(wxPayNotifyResponse.getReturnCode());
}
在貼上調(diào)用微信接口的api
WxPayApi.java
/**
* 統(tǒng)一下單接口
* @param body
* @return
*/
@POST("pay/unifiedorder")
Call<WxPayUnifiedorderResponse> UNIFIEDORDER_RESPONSE_CALL(@Body RequestBody body);
這里微信支付的代碼就全部完結(jié)了肆饶。如若遇到問題可以加我q:850728581,有空會(huì)給解答或者留郵箱發(fā)源碼
下一篇:小程序之微信退款