微信支付核心代码

PayUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package com.yaofang.utils;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
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.util.PemUtil;
import com.yaofang.config.PayConfig;
import com.yaofang.pojo.Order;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;


import javax.sound.midi.Soundbank;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;

/**
* @author xzy
* @create 2022/8/3 16:21
*/

@Component
public class PayUtil {

@Autowired
private PayConfig payConfig;

private CloseableHttpClient httpClient;

//证书加载相关
public void setup(){
System.out.println("payConfig: "+payConfig);
// 加载商户私钥(privateKey:私钥字符串)
PrivateKey merchantPrivateKey = null;
try {
merchantPrivateKey = PemUtil
.loadPrivateKey(new ByteArrayInputStream(payConfig.getPrivateKey().getBytes("utf-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

// 加载平台证书(mchId:商户号,mchSerialNo:商户证书序列号,apiV3Key:V3密钥)
AutoUpdateCertificatesVerifier verifier = null;
try {
verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(payConfig.getMchid(), new PrivateKeySigner(payConfig.getMchSerialNo(), merchantPrivateKey)),payConfig.getApiV3Key().getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

// 初始化httpClient
httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(payConfig.getMchid(), payConfig.getMchSerialNo(), merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier)).build();
}


public void after() throws IOException {
httpClient.close();
}

public void CreateOrder(Order order) throws Exception{
setup();
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
// 请求body参数
String reqdata = "{"
+ "\"amount\": {"
+ "\"total\":"+order.getTotal()+","
+ "\"currency\":\""+order.getCurrency()+"\""
+ "},"
+ "\"mchid\":\""+order.getMchid()+"\","
+ "\"description\":\""+order.getDescription()+"\","
+ "\"notify_url\":\""+order.getNotify_url()+"\","
+ "\"out_trade_no\":\""+order.getOut_trade_no()+"\","
+ "\"appid\":\""+order.getAppid()+"\","
+ "}";
StringEntity entity = new StringEntity(reqdata,"utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");

//完成签名并执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);

try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) { //处理成功
System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
} else if (statusCode == 204) { //处理成功,无返回Body
System.out.println("success");
} else {
System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
throw new IOException("request failed");
}
} finally {
response.close();
}

after();
}

public String QueryOrder(Order order) throws Exception {
setup();
//请求URL
URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/"+order.getOut_trade_no()+"?mchid="+order.getMchid());
uriBuilder.setParameter("mchid", order.getMchid());

//完成签名并执行请求
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.addHeader("Accept", "application/json");
CloseableHttpResponse response = httpClient.execute(httpGet);

String res = "";
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
res = EntityUtils.toString(response.getEntity());
} else if (statusCode == 204) {
System.out.println("success");
} else {
System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
throw new IOException("request failed");
}
} finally {
response.close();
}

after();
return res;
}

public void CloseOrder(Order order) throws Exception {
setup();
//请求URL
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/sdkphp12345678920201028112429/close");
//请求body参数
String reqdata ="{\"mchid\": \""+order.getMchid()+"\"}";

StringEntity entity = new StringEntity(reqdata,"utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");

//完成签名并执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
} else if (statusCode == 204) {
System.out.println("success");
} else {
System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
throw new IOException("request failed");
}
} finally {
response.close();
}

after();
}

}

pom.xml

1
2
3
4
5
6
<!-- 微信支付API -->
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.4.8</version>
</dependency>