首先去微信申请app应用,然后申请app支付.
#依赖
com.github.wxpay
wxpay-sdk
0.0.3
这里我是实现的官方的sdk
package com.hanfu.payment.center.config;
import com.github.wxpay.sdk.WXPayConfig;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@Component
public class MiniProgramConfig implements WXPayConfig {
private byte[] certData;
private String PATH_APP = "退款证书位置";
// @Bean
@Override
public String getAppID() {
return "appid";
}
@Override
public String getMchID() {
// TODO Auto-generated method stub
return "商户号";
}
@Override
public String getKey() {
// TODO Auto-generated method stub
return "自己的商户密匙";
}
@Override
public InputStream getCertStream() {
// TODO Auto-generated method stub
InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PATH_APP);
try {
this.certData = IOUtils.toByteArray(certStream);
certStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(this.certData);
}
@Override
public int getHttpConnectTimeoutMs() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getHttpReadTimeoutMs() {
// TODO Auto-generated method stub
return 0;
}
}
生成预支付订单,和两次签名,返给前端的是第二次签名,
要是有报错没有调起微信,如errMsg”: “requestPayment:fail errors”,支付签名验证失败
1、看自己是否下载了微信,没有下载微信是不能调起的,支付宝不会(ps:找了一上午错)
2、像uniapp之内的有没有配置支付权限模块
3、微信开放平台是否配置了包和签名,获取签名下载
4、参数是否正确,注意大小写
var orderInfo = {
"appid":res.map.appid,
"noncestr":res.map.nonceStr,
"package":res.map.package,
"partnerid":res.map.partnerid,
"prepayid":res.map.prepayid,
"timestamp":res.map.timestamp,
"sign":res.map.sign
}
5、返回给前端的二次签名是30位,很多返回是32位(巨坑)
/**
*orderId: 订单号
*/
private Map wxAppPay(Integer orderId) throws Exception {
MiniProgramConfig miniProgramConfig = new MiniProgramConfig();
Map data = getWxPayData(miniProgramConfig, String.valueOf(orderId),1);//为了方便这里我默认传1,这里是1分
// logger.info(JSONObject.toJSONString(data));
WXPay wxpay = new WXPay(miniProgramConfig);
Map resp = wxpay.unifiedOrder(data);
System.out.println(resp);
// logger.info(JSONObject.toJSONString(resp));
if ("SUCCESS".equals(resp.get("return_code"))) {
System.out.println(1);
resp.put("appid", resp.get("appid"));
resp.put("noncestr", resp.get("nonce_str"));
if ("SUCCESS".equals(resp.get("result_code"))) {//resultCode 为SUCCESS,才会返回prepay_id和trade_type
System.out.println(2);
Map reData = new HashMap<>();
reData.put("appId", miniProgramConfig.getAppID());
reData.put("nonceStr", resp.get("nonce_str"));
reData.put("package", "Sign=WXPay");
// reData.put("signType", "MD5");
reData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
reData.put("partnerid", resp.get("mch_id"));
reData.put("prepayid", resp.get("prepay_id"));
String sign = WXPayUtil.generateSignature(reData, miniProgramConfig.getKey());// 二次签名
System.out.println(sign);
resp.put("sign",sign.substring(0, 30)); //签名第二次签名是30位否则校验失败
resp.put("trade_type", resp.get("trade_type"));//获取预支付交易回话标志
resp.put("package","Sign=WXPay");
resp.put("partnerid", resp.get("mch_id"));
resp.put("prepayid", resp.get("prepay_id"));
resp.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
return resp;
} else {
//此时返回没有预付订单的数据
return resp;
}
} else {
throw new Exception(resp.get("return_msg"));
}
}
private Map getWxPayData(MiniProgramConfig config, String orderCode,Integer Amount)
throws Exception {
Map data = new HashMap<>();
data.put("appid", config.getAppID());
data.put("mch_id", config.getMchID());
data.put("body", "订单支付");
data.put("out_trade_no", orderCode);
data.put("device_info", req.getRemoteHost());
data.put("fee_type", "CNY");
data.put("total_fee", String.valueOf(Amount));
data.put("spbill_create_ip", req.getRemoteAddr());
data.put("notify_url", "https://www.tjsichuang.cn:1443/api/payment/hf-payment/handleWxpay");
data.put("trade_type", "APP");
// data.put("signType", "MD5");
// data.put("openid", openId);
String sign = WXPayUtil.generateSignature(data, config.getKey());//获取第一次签名
System.out.println(sign);
data.put("sign", sign);
// logger.info(JSONObject.toJSONString(data));
return data;
}
uniapp简单代码,支付宝app支付类似
如果不成功可以去微信支付校验工具 校验一下后端传入参数是否正确
wxPayment(){
var num = Math.floor(Math.random() * 100000 + 100);
console.log("随机"+num)//这里我随机生成的订单号方便测试
uni.request({ url:"http://localhost:9099/WxAPPpay/order?userId="+num,
method: 'GET',
success: res => {
console.log(res)
var obj ={
"appid": res.data.data.appid,
"noncestr": res.data.data.noncestr,
"package": "Sign%3DWXPay",
"partnerid": res.data.data.partnerid,
"prepayid": res.data.data.prepayid,
"timestamp": res.data.data.timestamp,
"sign": res.data.data.sign
}
console.log(obj)
uni.requestPayment({
provider: 'wxpay',
orderInfo: JSON.stringify(obj), //微信、支付宝订单数据
success: function (res) {
console.log('success:' + JSON.stringify(res));
},
fail: function (err) {
console.log('fail:' + JSON.stringify(err));
},
complete: function(){
console.log("")
},
});
},
fail: () => {},
complete: () => {}
});
}
退款,前端只需要调用一下就可以,就不展示前端代码了,swagger测试下也行
@ApiOperation(value = "退款订单", notes = "")
@RequestMapping(value = "/refund", method = RequestMethod.GET)
public ResponseEntity refund(Integer id) throws Exception {
ResponseEntity.BodyBuilder builder = ResponseUtils.getBodyBuilder(HttpStatus.OK);
MiniProgramConfig miniProgramConfig = new MiniProgramConfig();
WXPay wxpay = new WXPay(miniProgramConfig);
Map data = new HashMap<>();
data.put("appid", miniProgramConfig.getAppID());
data.put("mch_id", miniProgramConfig.getMchID());
data.put("device_info", req.getRemoteHost());
data.put("fee_type", "CNY");
data.put("total_fee", String.valueOf(1));
data.put("spbill_create_ip", req.getRemoteAddr());
data.put("notify_url", "回调地址");
data.put("out_trade_no", String.valueOf(id));
data.put("op_user_id", miniProgramConfig.getMchID());
data.put("refund_fee_type", "CNY");
data.put("refund_fee", String.valueOf(1));
// if (hfOrder!=null){
// System.out.println(hfOrder.getAmount());
// data.put("refund_fee", String.valueOf(hfOrder.getAmount()));
// }else {
// System.out.println(payOrder.getAmount());
// data.put("refund_fee", String.valueOf(payOrder.getAmount()));
// }
data.put("out_refund_no", UUID.randomUUID().toString().replaceAll("-", ""));
String sign = WXPayUtil.generateSignature(data, miniProgramConfig.getKey());
data.put("sign", sign);
Map resp = wxpay.refund(data);
if ("SUCCESS".equals(resp.get("return_code"))) {
LocalDateTime current = LocalDateTime.now();
System.out.println("成功");
}
return builder.body(ResponseUtils.getResponseBody(1));
}
这里把回调也展示下把
@SuppressWarnings({ "unchecked", "rawtypes" })
@ApiOperation(value = "訂單支付后處理", notes = "訂單支付后處理")
@RequestMapping(value = "/handleWxpay", method = RequestMethod.GET)
public void refund(HttpServletRequest request, HttpServletResponse response) throws Exception {
// MiniProgramConfig config = new MiniProgramConfig();
miniProgramConfig.setBossId((Integer) req.getServletContext().getAttribute("bossId"));
BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
// sb为微信返回的xml
String notityXml = sb.toString();
String resXml = "";
logger.info("接收到的报文:" + notityXml);
Map map = PayUtil.doXMLParse(notityXml);
String returnCode = (String) map.get("return_code");
if ("SUCCESS".equals(returnCode)) {
// hfOrderDao.updateHfOrderStatus(out_trade_no,
// OrderStatus.PROCESS.getOrderStatus(), LocalDateTime.now());
Map validParams = PayUtil.paraFilter(map); // 回调验签时需要去除sign和空值参数
String validStr = PayUtil.createLinkString(validParams);// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
String sign = PayUtil.sign(validStr, miniProgramConfig.getKey(), "utf-8").toUpperCase();// 拼装生成服务器端验证的签名
// 因为微信回调会有八次之多,所以当第一次回调成功了,那么我们就不再执行逻辑了
// 根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
if (sign.equals(map.get("sign"))) {
/** 此处添加自己的业务逻辑代码start **/
// bla bla bla....
/** 此处添加自己的业务逻辑代码end **/
// 通知微信服务器已经支付成功
resXml = "" + " "
+ " " + " ";
} else {
System.out.println("微信支付回调失败!签名不一致");
}
} else {
resXml = "" + " "
+ " " + " ";
}
System.out.println(resXml);
logger.info("微信支付回调数据结束");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
}