前言
之前对接微信支付使用的是v2版本, 微信也将v2版本升级到了v3版本, 之后可能会舍弃v2, 所以需要重新对接一下.
不得不说微信支付的对接, 对于新手不太友好, 不如支付宝那么方便, 上次的对接微信就挺繁琐.
这里省略springboot项目的创建, 有问题的老铁们自己搜搜, 网上教程多的是.
本章内容是以native下单为例, 其他的类型直接套公式.
微信支付开发文档链接 :链接: https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_4_1.shtml
这边是下单po参数说明,以及回调vo参数说明.
好了,废话不多说, 直接上代码.
一.引入依赖
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.11</version>
</dependency>
二.配置文件
微信支付没有沙箱环境(偷偷吐槽下), 申请又需要审核费300又300. 所以这里配置就不隐藏了, 方便各位铁子们开发的时候使用, 正式环境调试的时候只需要换成你们自己公司的.
wxpay:
#appid
appId: wx1cd564c7469238d3
# 商户号
mchId: 1639864766
# 商户证书序列号
wechatPaySerial: 4FFB54B40DEAEF54819ED5CFC0A6C6E12B4A1767
# 商户证书私钥-apiclient_key.pem路径
apiclientKey: apiclient_key.pem
# APIv3密钥
apiV3Key: BuLiangYuWangLuoGongZuoShi123456
# 支付回调地址(我们本地调试需要内网穿透出去,否则回调不会成功的, 如果有权限,也要把接口权限放开,大家注意)
notifyUrl: http://*******/wx/notify
三.controller代码
import com.alibaba.fastjson.JSONObject;
import com.eshop.user.util.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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 javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxPayController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
WeChatPayUtil weChatPayUtil;
@GetMapping("/createOrder")
public String createOrder(String orderNumber) throws Exception {
String s = weChatPayUtil.transactionsNative("订单支付", orderNumber, new BigDecimal(0.01));
return s;
}
@PostMapping("/notify")
public void notify(HttpServletRequest request, HttpServletResponse response) {
try{
//获取微信回调结果
JSONObject dataJSON = weChatPayUtil.getCallback(request);
logger.info("v3回调参数:{}",dataJSON);
//TODO 文章最后边有回调参数示例, 需要什么自取
//创建订单时的我们业务的订单号
String out_trade_no = dataJSON.getString("out_trade_no");
//微信平台的支付交易号
String transaction_id = dataJSON.getString("transaction_id");
//自由发挥, 我们自己的业务处理, 最好放到service中.
/*
*
*
*/
//返回给微信,通知他我们已经处理好了, 不要在给我们发了
response.setStatus(200);
}catch (Exception e){
e.printStackTrace();
logger.error("v3回调异常:{}",e.getMessage());
}
}
}
四.工具类代码
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.HttpHeaders.CONTENT_TYPE;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
@Configuration
@Data
public class WeChatPayUtil {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${wxpay.notifyUrl}")
private String notifyUrl;
@Value("${wxpay.mchId}")
private String mchId;
@Value("${wxpay.apiV3Key}")
private String apiV3Key;
@Value("${wxpay.apiclientKey}")
private String apiclientKey;
@Value("${wxpay.wechatPaySerial}")
private String wechatPaySerial;
@Value("${wxpay.appId}")
private String appId;
/**
* 微信v3 post请求
* @param url
* @param body
* @return
* @throws Exception
*/
public String v3Post(String url,String body) throws Exception {
logger.info("post请求参数:{}",body);
CloseableHttpClient httpClient = getClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(ACCEPT, APPLICATION_JSON.toString());
httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON.toString());
httpPost.addHeader("Wechatpay-Serial", wechatPaySerial);
httpPost.setEntity(new StringEntity(body, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
String bodyAsString = EntityUtils.toString(response.getEntity());
logger.info("post请求返回信息:{}",bodyAsString);
return bodyAsString;
} finally {
httpClient.close();
response.close();
}
}
/**
* client
* @return CloseableHttpClient
*/
public CloseableHttpClient getClient() throws Exception {
/**商户证书私钥文件*/
InputStream apiclientKeyInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(apiclientKey);
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(apiclientKeyInputStream);
WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
.withMerchant(mchId, wechatPaySerial, merchantPrivateKey)
.withValidator(getValidator());
CloseableHttpClient httpClient = builder.build();
return httpClient;
}
/**
* 获取商户证书私钥
* @return 私钥对象
*/
public PrivateKey getPrivateKey() {
ClassPathResource apiclientKeyFile = new ClassPathResource(apiclientKey);
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(apiclientKeyFile.getStream());
return merchantPrivateKey;
}
/**
* 获得验签器
* @return
* @throws Exception
*/
public Verifier verifier() throws Exception {
//获取证书管理器实例
CertificatesManager certificatesManager = CertificatesManager.getInstance();
certificatesManager.putMerchant(mchId, new WechatPay2Credentials(mchId,new PrivateKeySigner(wechatPaySerial, getPrivateKey())), apiV3Key.getBytes(StandardCharsets.UTF_8));
// 从证书管理器中获取verifier
Verifier verifier = certificatesManager.getVerifier(mchId);
return verifier;
}
public WechatPay2Validator getValidator() throws Exception {
WechatPay2Validator validator = new WechatPay2Validator(verifier());
return validator;
}
/**
* 转换为分
* @param money
* @return
*/
public int conversionFraction(BigDecimal money){
int fractionMoney = 0;
if(money!=null){
fractionMoney = money.multiply(new BigDecimal(100)).intValue();
}
return fractionMoney;
}
/**
* 获取回调结果
* @param request
* @return
* @throws Exception
*/
public JSONObject getCallback(HttpServletRequest request) throws Exception {
String body = getRequestBody(request);
String nonce = request.getHeader("Wechatpay-Nonce");
String signature = request.getHeader("Wechatpay-Signature");
String wechatPaySerial = request.getHeader("Wechatpay-Serial");
String timestamp = request.getHeader("Wechatpay-Timestamp");
// 验签构建
NotificationRequest notificationRequest = new NotificationRequest.Builder()
.withSerialNumber(wechatPaySerial)
.withNonce(nonce)
.withTimestamp(timestamp)
.withSignature(signature)
.withBody(body)
.build();
NotificationHandler handler = new NotificationHandler(verifier(), apiV3Key.getBytes(StandardCharsets.UTF_8));
// 验签和解析请求体
/**
* TODO 与其他的旧版本验签不同, 这里handler.parse(),在解析的时,会先进行的验签操作, 我们不用再去验签了. 我是这么理解的
* TODO 我们看下.parse()内容
* /**
* * 解析微信支付通知请求结果
* *
* * @param request 微信支付通知请求
* * @return 微信支付通知报文解密结果
* * @throws ValidationException 1.输入参数不合法 2.参数被篡改导致验签失败 3.请求和验证的平台证书不一致导致验签失败
* * @throws ParseException 1.解析请求体为Json失败 2.请求体无对应参数 3.AES解密失败
*
* public Notification parse (Request request) throws ValidationException, ParseException {
* // 验签
* validate(request);
* // 解析请求体
* return parseBody(request.getBody());
* }
*/
Notification notification = handler.parse(notificationRequest);
return JSON.parseObject(notification.getDecryptData());
}
/**
* 获取报文
* @param request
* @return
* @throws Exception
*/
private String getRequestBody(HttpServletRequest request) throws Exception {
StringBuffer stringBuffer = new StringBuffer();
ServletInputStream inputStream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
/**
* native下单
* @param description 商品描述
* @param orderNum 商户订单号
* @param total 总金额
* @throws Exception
*/
public String transactionsNative(String description, String orderNum, BigDecimal total) throws Exception {
JSONObject transactionsJsapiJSON = new JSONObject();
transactionsJsapiJSON.put("appid", appId);
transactionsJsapiJSON.put("mchid", mchId);
transactionsJsapiJSON.put("description", description);
transactionsJsapiJSON.put("out_trade_no", orderNum);
transactionsJsapiJSON.put("notify_url",notifyUrl);
JSONObject amount = new JSONObject();
amount.put("total",conversionFraction(total));
amount.put("currency","CNY");
transactionsJsapiJSON.put("amount",amount);
String body = transactionsJsapiJSON.toJSONString();
return v3Post("https://api.mch.weixin.qq.com/v3/pay/transactions/native",body);
}
}
五.回调业务参数示例
{
"transaction_id":"1217752501201407033233368018",
"amount":{
"payer_total":100,
"total":100,
"currency":"CNY",
"payer_currency":"CNY"
},
"mchid":"1230000109",
"trade_state":"SUCCESS",
"bank_type":"CMC",
"promotion_detail":[
{
"amount":100,
"wechatpay_contribute":0,
"coupon_id":"109519",
"scope":"GLOBAL",
"merchant_contribute":0,
"name":"单品惠-6",
"other_contribute":0,
"currency":"CNY",
"stock_id":"931386",
"goods_detail":[
{
"goods_remark":"商品备注信息",
"quantity":1,
"discount_amount":1,
"goods_id":"M1006",
"unit_price":100
},
{
"goods_remark":"商品备注信息",
"quantity":1,
"discount_amount":1,
"goods_id":"M1006",
"unit_price":100
}
]
},
{
"amount":100,
"wechatpay_contribute":0,
"coupon_id":"109519",
"scope":"GLOBAL",
"merchant_contribute":0,
"name":"单品惠-6",
"other_contribute":0,
"currency":"CNY",
"stock_id":"931386",
"goods_detail":[
{
"goods_remark":"商品备注信息",
"quantity":1,
"discount_amount":1,
"goods_id":"M1006",
"unit_price":100
},
{
"goods_remark":"商品备注信息",
"quantity":1,
"discount_amount":1,
"goods_id":"M1006",
"unit_price":100
}
]
}
],
"success_time":"2018-06-08T10:34:56+08:00",
"payer":{
"openid":"oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
},
"out_trade_no":"1217752501201407033233368018",
"appid":"wxd678efh567hg6787",
"trade_state_desc":"支付成功",
"trade_type":"MICROPAY",
"attach":"自定义数据",
"scene_info":{
"device_id":"013467007045764"
}
}
结语
到此v3版本微信支付就已经结束了, 希望各位铁子们调试成功.