一定要看最后面的温馨提示
一定要看最后面的温馨提示
一定要看最后面的温馨提示
开发环境:
springboot+maven
引入微信sdk
com.github.wxpay
wxpay-sdk
0.0.3
微信支付基本配置类:
需要修改的地方:
public static final String APP_ID = "你的appid";
public static final String KEY = "你的api秘钥,不是appSecret";
public static final String MCH_ID = "你的商户id";
String certPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/weixin/apiclient_cert.p12";//从微信商户平台下载的安全证书存放的路径
package com.calcnext.purchase.config;
import com.github.wxpay.sdk.WXPayConfig;
import org.springframework.util.ClassUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @author saodiseng
* @date 2019/2/18
*/
public class WXConfigUtil implements WXPayConfig {
private byte[] certData;
public static final String APP_ID = "你的appid";
public static final String KEY = "你的api key不是appSecret";
public static final String MCH_ID = "你的商户id";
public WXConfigUtil() throws Exception {
String certPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/weixin/apiclient_cert.p12";//从微信商户平台下载的安全证书存放的路径
File file = new File(certPath);
InputStream certStream = new FileInputStream(file);
this.certData = new byte[(int) file.length()];
certStream.read(this.certData);
certStream.close();
}
@Override
public String getAppID() {
return APP_ID;
}
//parnerid,商户号
@Override
public String getMchID() {
return MCH_ID;
}
@Override
public String getKey() {
return KEY;
}
@Override
public InputStream getCertStream() {
ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
return certBis;
}
@Override
public int getHttpConnectTimeoutMs() {
return 8000;
}
@Override
public int getHttpReadTimeoutMs() {
return 10000;
}
}
controller:
需要根据个人需求修改参数的传值,例如支付金额等
package com.calcnext.purchase.controller;
import com.calcnext.purchase.service.WxService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
/**
* @author saodiseng
* @date 2018/11/5
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private WxService wxService;
@PostMapping("/wx")
public Map wxAdd() throws Exception {
return wxService.doUnifiedOrder();
}
@PostMapping("/notify")
@ApiOperation("微信回调")
public String wxPayNotify(HttpServletRequest request) {
String resXml = "";
try {
InputStream inputStream = request.getInputStream();
//将InputStream转换成xmlString
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
resXml = sb.toString();
String result = wxService.payBack(resXml);
return result;
} catch (Exception e) {
System.out.println("微信手机支付失败:" + e.getMessage());
String result = "" + " " + " " + " ";
return result;
}
}
}
service接口:
package com.calcnext.purchase.service;
import java.math.BigDecimal;
import java.util.Map;
/**
* @author saodiseng
* @date 2019/2/18
*/
public interface WxService {
String payBack(String resXml);
Map doUnifiedOrder() throws Exception;
}
service实现类:
此类返回值用户移动端使用
需要添加支付成功后的业务处理(例如订单状态的修改): //业务数据持久化
统一下单接口根据controller修改,例如金额等
import com.calcnext.purchase.config.WXConfigUtil;
import com.calcnext.purchase.service.WxService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* @author saodiseng
* @date 2019/2/18
*/
@Service
@Slf4j
public class WxServiceImpl implements WxService {
public static final String SPBILL_CREATE_IP = "服务器ip地址";
public static final String NOTIFY_URL = "回调接口地址";
public static final String TRADE_TYPE_APP = "APP";
@Override
public String payBack(String resXml) {
WXConfigUtil config = null;
try {
config = new WXConfigUtil();
} catch (Exception e) {
e.printStackTrace();
}
WXPay wxpay = new WXPay(config);
String xmlBack = "";
Map notifyMap = null;
try {
notifyMap = WXPayUtil.xmlToMap(resXml); // 调用官方SDK转换成map类型数据
if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效,有效则进一步处理
String return_code = notifyMap.get("return_code");//状态
String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
if (return_code.equals("SUCCESS")) {
if (out_trade_no != null) {
// 注意特殊情况:订单已经退款,但收到了支付结果成功的通知,不应把商户的订单状态从退款改成支付成功
// 注意特殊情况:微信服务端同样的通知可能会多次发送给商户系统,所以数据持久化之前需要检查是否已经处理过了,处理了直接返回成功标志
//业务数据持久化
log.info("微信手机支付回调成功订单号:{}", out_trade_no);
xmlBack = "" + " " + " " + " ";
} else {
log.info("微信手机支付回调失败订单号:{}", out_trade_no);
xmlBack = "" + " " + " " + " ";
}
}
return xmlBack;
} else {
// 签名错误,如果数据里没有sign字段,也认为是签名错误
//失败的数据要不要存储?
log.error("手机支付回调通知签名错误");
xmlBack = "" + " " + " " + " ";
return xmlBack;
}
} catch (Exception e) {
log.error("手机支付回调通知失败", e);
xmlBack = "" + " " + " " + " ";
}
return xmlBack;
}
@Override
public Map doUnifiedOrder() throws Exception {
try {
WXConfigUtil config = new WXConfigUtil();
WXPay wxpay = new WXPay(config);
Map data = new HashMap<>();
//生成商户订单号,不可重复
data.put("appid", config.getAppID());
data.put("mch_id", config.getMchID());
data.put("nonce_str", WXPayUtil.generateNonceStr());
String body = "订单支付";
data.put("body", body);
data.put("out_trade_no", "订单号");
data.put("total_fee", "1");
//自己的服务器IP地址
data.put("spbill_create_ip", SPBILL_CREATE_IP);
//异步通知地址(请注意必须是外网)
data.put("notify_url", NOTIFY_URL);
//交易类型
data.put("trade_type", TRADE_TYPE_APP);
//附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
data.put("attach", "");
data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
WXPayConstants.SignType.MD5));
//使用官方API请求预付订单
Map response = wxpay.unifiedOrder(data);
if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
Map param = new HashMap<>();
param.put("appid",config.getAppID());
param.put("partnerid",response.get("mch_id"));
param.put("prepayid",response.get("prepay_id"));
param.put("package","Sign=WXPay");
param.put("noncestr",WXPayUtil.generateNonceStr());
param.put("timestamp",System.currentTimeMillis()/1000+"");
param.put("sign",WXPayUtil.generateSignature(param, config.getKey(),
WXPayConstants.SignType.MD5));
return param;
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("下单失败");
}
throw new Exception("下单失败");
}