因为本人比较懒 不想写太过于理论的东西 所以直接开始上操作
微信APIV3支付 开始上操作了
支付前准备
APP_ID:应用id
MchId : 商户号
privateKey :私钥字符串
mchSerialNo :证书序列号
apiV3Key : APIV3秘钥
domain:“”native支付的链接 https://api.mch.weixin.qq.com/v3/pay/transactions/native“”
h5Domain:“”h5支付的请求链接 https://api.mch.weixin.qq.com/v3/pay/transactions/h5“”
notify_url :“”支付成功后的回调地址“”
开始上代码了
导入jar
```java
<!--微信支付依赖包-->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
<!--微信支付SDK-->
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.3.0</version>
</dependency>
<!--发送http请求-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
``
支付请求类
package com.tm.forum.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.tm.forum.common.utils.ip.IpUtils;
import com.tm.forum.system.domain.order.Order;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.*;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
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 javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.*;
public class WXPayPubUtil {
public static final String APP_ID = "w*****************b";
/**
* 贸友圈 APPId
*/
public static final String M_APP_ID = "wx**********e85";
public static final String PARTNER = "1***********01";
public static final String PARTNER_KEY = "fsB2b***************888";
public static final String PAY_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static final String QRY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
/**
* 微信支付的AppId
*/
public static final String AppId = "w*********0b";
/**
* 微信支付的商户号(mchid)
*/
public static final String MchId = "1********01";
/**微信支付的secret参数*/
private static final String Secret = "d81****************27f9e";
/**
* 私钥字符串
*/
public static final String privateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDwnTWYsG6RwTyu\n" +
"L09j6a*************4++YnzMFiXkRkiONjdyS8Iefz5/DEvTuiGgFd\n" +
"jqerQVx3x3U7a7RKyUQensjDDbctXLfpiGrwDQs+OOZRQpFHcWqPWrsBfgwfOvqW\n" +
"LxRBg1YLvdGjCHcXR2asXO6/IgrcOs8mz1OXkLoWjW/MnIyRS0dX3pxPfdneAeMW\n" +
"kbcKgttjDPUJZc7oRvcw0Kdj4NRNjnAIW3A5qwlXHkE+hBzUcPkgZkckROPoXgdY\n" +
"0uLgw4Wk*************Y2cCIb\n" +
"x/AWWb69AgMBAAECggEBAMTTNQakPK6KbgLmvIC0mel8/xpJI1v9NMeUrqIs6UwO\n" +
"cyVXf1HiXvwGZkv1KF2lNsL0*************L7Fc6feVO6++tjCtbW\n" +
"o7MrXp7jbLEHhpAubf0NL+f4hkUgQPZDHr0/4cf9kaOlMRm2UQT/6WNR2hML2+pt\n" +
"stUlVd1l8gwe2HpKgrr1zatamGKfhnlU8lF8Ny0NOjGh6MQ0MCEU8cgs1LmEHdWr\n" +
"jRzF7RfysXavDONCilAePvBJlvkZTEwaCI6utMytLEZFONQMcbcrl2xSTpaSbilk\n" +
"MEx7MOyd3pbkKIDCW5*************/05dmHBWGTUUePpV\n" +
"ycezES6sg278AhZM+WtXdhO50wIlRPkkVvgdLr3tWMWIBw9WEy+HRhAFIC8oqVga\n" +
"meODmExVtBC6quw5D4/SV9658ljDNSXLQLAFdKzSvENhJ2EcGXSiGKw382M0pZNW\n" +
"KOJLUY6e8iOntC/dP5JTzZQTjzkCgYEA8USfGbfmdoFLjvRqIYLtnki1//HIzp37\n" +
"x2Fyng5Jev1NhbnM6cOTmRK7IjKdHBVFTzKlVuXLCUSIKB65cPk7xdwwjY/7KN3b\n" +
"u1sjHj2h5B2U3rKSdaVFsePimjmcUC8uEf8x1iass0kLkEMO7hA1oPK5QKnX4+c6\n" +
"POXrW9mS56*************ujTBtXTE9DgY8Z1SpcDqxPgmJM2kUQg\n" +
"uN3o+i889qCnbUUHaZKsBLu7ugeB2jVnA+Z+e2SXL+Jdr21+IG38Ufe5und1Pf3g\n" +
"xyzMDly0abTd4z47mhzV1nX9LobZAvXU2pejTUVa/36Ri8mUa1aARmXM+uECgYAs\n" +
"peZLfBzKEWNKMTDywqf2gr4rfzMKCXJukzoCxeITQIz4Eko5eFf4G99FlNg+OjF5\n" +
"VoYCbsQE*************COsGX2Lt880y\n" +
"x2cRmlabVwksyTwaEiXagxCFRukM492DJ4lGlhz5gQKBgQCsIdwrUSLivDsf7xqc\n" +
"ur6+mM7PruV*************8SrEdwJeLWeK\n" +
"1hIsW1naH3*************Q\n" +
"zFhKvrPBJ1LgswRZeC90wWq3NA==";
/**
* 证书序列号
*/
public static final String mchSerialNo = "63C*************E";
/**
* APIv3密钥
*/
public static final String apiV3Key = "fsB2b*************88";
private static final String domain = "https://api.mch.weixin.qq.com/v3/pay/transactions/native";
/**
* h5
*/
private static final String h5Domain = "https://api.mch.weixin.qq.com/v3/pay/transactions/h5";
/**
* JSAPI
*/
private static final String jsDomain = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi";
/**
* 子应用id
*/
private static final String sub_appid = "wx6*************e85";
/**
* 子商户id
*/
private static final String sub_mchid = "127*************1";
/**
* native 支付
* @return
*/
public static String createNative(Order order) throws IOException {
PrivateKey mePrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)));
AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(new WechatPay2Credentials(MchId, new PrivateKeySigner(mchSerialNo, mePrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(MchId, mchSerialNo, mePrivateKey)
.withValidator(new WechatPay2Validator(verifier)).build();
HttpPost httpPost = new HttpPost(domain);
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
if (order.getUserId() == 223695) {
jsonObject1.put("total" , 1);
} else {
jsonObject1.put("total" , order.getRmbPrice().longValue() * 100);
}
jsonObject1.put("currency" , "CNY");
jsonObject.put("amount" , jsonObject1);
jsonObject.put("mchid" , MchId);
jsonObject.put("description" , order.getName());
jsonObject.put("notify_url" , "https://api.tr********************/allback"); // 回调地址
jsonObject.put("out_trade_no" , order.getOutTradeNo());
jsonObject.put("appid" , AppId);
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), "utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept" , "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
Integer statusCode = response.getStatusLine().getStatusCode();
String codeUrl = EntityUtils.toString(response.getEntity());
String qrCode = codeUrl.substring(codeUrl.indexOf("w"), codeUrl.indexOf("}") - 1);
// 生成二维码
String code = QRCodeUtil.getBase64QRCode(qrCode);
return code;
}
/**
* h5支付
* @return
*/
public static String mCreateNative(Order order, HttpServletRequest request) throws IOException {
PrivateKey mePrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)));
AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(new WechatPay2Credentials(MchId, new PrivateKeySigner(mchSerialNo, mePrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(MchId, mchSerialNo, mePrivateKey)
.withValidator(new WechatPay2Validator(verifier)).build();
HttpPost httpPost = new HttpPost(h5Domain);
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
if (order.getUserId() == 223695) {
jsonObject1.put("total" , 1);
} else {
jsonObject1.put("total" , order.getRmbPrice().longValue() * 100);
}
jsonObject1.put("currency" , "CNY");
jsonObject.put("amount" , jsonObject1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("payer_client_ip" , IpUtils.getIpAddr(request));
JSONObject jsonObject3 = new JSONObject();
String[] str = {"iOS" , "Android" , "Wap"};
jsonObject3.put("type" , "Wap");
jsonObject2.put("h5_info" , jsonObject3);
jsonObject.put("scene_info" , jsonObject2);
jsonObject.put("mchid" , MchId);
jsonObject.put("description" , order.getName());
//https://api.trademanager.com/api/wechat/callbac
jsonObject.put("notify_url" , "https://api******************wechat/callback");
jsonObject.put("out_trade_no" , order.getOutTradeNo());
jsonObject.put("appid" , APP_ID);
System.out.println(jsonObject.toJSONString());
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), "utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept" , "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
Integer statusCode = response.getStatusLine().getStatusCode();
String codeUrl = EntityUtils.toString(response.getEntity());
JSONObject jsonObject4 = JSONObject.parseObject(codeUrl);
// String qrCode = codeUrl.substring(codeUrl.indexOf(“w”), codeUrl.indexOf(“}”) - 1);
// 生成二维码
// String code = QRCodeUtil.getBase64QRCode(qrCode);
return jsonObject4.getString(“h5_url”);
}
/**
* @param out_trade_no 订单id
* @return
*/
public static Map queryPayStatus(String out_trade_no) {
Map param = new HashMap();
param.put("appid" , APP_ID);
param.put("mch_id" , PARTNER);
param.put("out_trade_no" , out_trade_no);
param.put("nonce_str" , WXPayUtil.generateNonceStr());
try {
String xmlParam = WXPayUtil.generateSignedXml(param, PARTNER_KEY);
HttpUtil client = new HttpUtil(QRY_URL);
client.setHttps(true);
client.setXmlParam(xmlParam);
client.post();
String result = client.getContent();
Map<String, String> map = WXPayUtil.xmlToMap(result);
if (map.get("err_code") != null && map.get("err_code").equals("ORDERNOTEXIST")) {
System.out.println("订单不存在!");
}
if (map.get("trade_state").equals("SUCCESS")) {
//支付成功,未支付为:NOTPAY
}
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取微信请求头
*
* @param request
* @return
* @throws IOException
*/
public static String getRequestBody(HttpServletRequest request) throws IOException {
ServletInputStream stream = null;
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
stream = request.getInputStream();
// 获取响应
reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
throw new IOException("读取返回支付接口数据流出现异常!");
} finally {
reader.close();
}
return sb.toString();
}
/**
* @param order jsApi支付
* @return
*/
public static String jsApiCreateNative(Order order, HttpServletRequest request) throws IOException {
PrivateKey mePrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)));
AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(new WechatPay2Credentials(MchId, new PrivateKeySigner(mchSerialNo, mePrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(MchId, mchSerialNo, mePrivateKey)
.withValidator(new WechatPay2Validator(verifier)).build();
HttpPost httpPost = new HttpPost(jsDomain);
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
if (order.getUserId() == 223695) {
jsonObject1.put("total" , 1);
} else {
jsonObject1.put("total" , order.getRmbPrice().longValue() * 100);
}
jsonObject1.put("currency" , "CNY");
jsonObject.put("amount" , jsonObject1);
jsonObject.put("sp_mchid" , ""); // 服务商户号
jsonObject.put("sub_mchid" , ""); // 子商户号
jsonObject.put("sp_appid" , ""); // 服务商应用ID
jsonObject.put("sub_appid" , ""); // 子商户应用ID
jsonObject.put("sub_appid" , ""); // 子商户应用ID
jsonObject.put("description" , order.getName());
jsonObject.put("notify_url" , "https://api.trademanager.com/api/wechat/callback");
jsonObject.put("out_trade_no" , order.getOutTradeNo());
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("sp_openid" , "");
jsonObject.put("payer" , jsonObject2); // 支付者信息
System.out.println(jsonObject.toJSONString());
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), "utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept" , "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
Integer statusCode = response.getStatusLine().getStatusCode();
String codeUrl = EntityUtils.toString(response.getEntity());
JSONObject jsonObject4 = JSONObject.parseObject(codeUrl);
return jsonObject4.getString("prepay_id");
}
}
注: 复制粘贴就能用 改改配置参数 不知道参数这么获取的 官方文档有告诉你参数在哪