提交微信支付基础信息,基本实体脱胎于微信官方demo
parent
4d0553d429
commit
776b9be0a7
|
|
@ -0,0 +1,128 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.weixin.pay</groupId>
|
||||
<artifactId>wxpay-sdk</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>wxpay-sdk</name>
|
||||
<description>wxpay sdk</description>
|
||||
<url>https://github.com/YClimb/wxpay-sdk</url>
|
||||
<!-- 官方版 -->
|
||||
<!--<url>https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=11_1</url>-->
|
||||
|
||||
<licenses>
|
||||
<license>
|
||||
<name>The BSD 3-Clause License</name>
|
||||
<url>https://opensource.org/licenses/BSD-3-Clause</url>
|
||||
<distribution>repo</distribution>
|
||||
</license>
|
||||
</licenses>
|
||||
|
||||
<developers>
|
||||
<developer>
|
||||
<name>wxpay</name>
|
||||
<email>yclimb@qq.com</email>
|
||||
<url>https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=11_1</url>
|
||||
</developer>
|
||||
</developers>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>utf-8</project.reporting.outputEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.5.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk16</artifactId>
|
||||
<version>1.46</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.15</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<target>8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>release</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- Source -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>3.0.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar-no-fork</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- Javadoc -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>2.10.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
</project>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,104 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* 微信支付配置接口,用户设置获取微信支付关键信息抽象方法
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public abstract class WxPayConfig {
|
||||
|
||||
/**
|
||||
* 获取 App ID
|
||||
*
|
||||
* @return App ID
|
||||
*/
|
||||
abstract String getAppID();
|
||||
|
||||
/**
|
||||
* 获取 Mch ID
|
||||
*
|
||||
* @return Mch ID
|
||||
*/
|
||||
abstract String getMchID();
|
||||
|
||||
/**
|
||||
* 获取 API 密钥
|
||||
*
|
||||
* @return API密钥
|
||||
*/
|
||||
abstract String getKey();
|
||||
|
||||
/**
|
||||
* 获取商户证书内容
|
||||
*
|
||||
* @return 商户证书内容
|
||||
*/
|
||||
abstract InputStream getCertStream();
|
||||
|
||||
/**
|
||||
* HTTP(S) 连接超时时间,单位毫秒
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public int getHttpConnectTimeoutMs() {
|
||||
return 6 * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP(S) 读数据超时时间,单位毫秒
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public int getHttpReadTimeoutMs() {
|
||||
return 8 * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取WXPayDomain, 用于多域名容灾自动切换
|
||||
*
|
||||
* @return IWXPayDomain
|
||||
*/
|
||||
abstract WxPayDomain getWXPayDomain();
|
||||
|
||||
/**
|
||||
* 是否自动上报。
|
||||
* 若要关闭自动上报,子类中实现该函数返回 false 即可。
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean shouldAutoReport() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 进行健康上报的线程的数量
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public int getReportWorkerNum() {
|
||||
return 6;
|
||||
}
|
||||
|
||||
/**
|
||||
* 健康上报缓存消息的最大数量。会有线程去独立上报
|
||||
* 粗略计算:加入一条消息200B,10000消息占用空间 2000 KB,约为2MB,可以接受
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public int getReportQueueMaxSize() {
|
||||
return 10000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上报,一次最多上报多个数据
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public int getReportBatchSize() {
|
||||
return 10;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* 微信支付配置接口实现类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxPayConfigImpl extends WxPayConfig {
|
||||
|
||||
private byte[] certData;
|
||||
private static WxPayConfigImpl INSTANCE;
|
||||
|
||||
private WxPayConfigImpl() throws Exception {
|
||||
String certPath = WxPayConstants.APICLIENT_CERT;
|
||||
File file = new File(certPath);
|
||||
InputStream certStream = new FileInputStream(file);
|
||||
this.certData = new byte[(int) file.length()];
|
||||
certStream.read(this.certData);
|
||||
certStream.close();
|
||||
}
|
||||
|
||||
public static WxPayConfigImpl getInstance() throws Exception {
|
||||
if (INSTANCE == null) {
|
||||
synchronized (WxPayConfigImpl.class) {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = new WxPayConfigImpl();
|
||||
}
|
||||
}
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAppID() {
|
||||
return WxPayConstants.APP_ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMchID() {
|
||||
return WxPayConstants.MCH_ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKey() {
|
||||
return WxPayConstants.API_KEY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getCertStream() {
|
||||
ByteArrayInputStream certBis;
|
||||
certBis = new ByteArrayInputStream(this.certData);
|
||||
return certBis;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHttpConnectTimeoutMs() {
|
||||
return 2000;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHttpReadTimeoutMs() {
|
||||
return 10000;
|
||||
}
|
||||
|
||||
@Override
|
||||
WxPayDomain getWXPayDomain() {
|
||||
return WxPayDomainSimpleImpl.instance();
|
||||
}
|
||||
|
||||
public String getPrimaryDomain() {
|
||||
return "api.mch.weixin.qq.com";
|
||||
}
|
||||
|
||||
public String getAlternateDomain() {
|
||||
return "api2.mch.weixin.qq.com";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReportWorkerNum() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReportBatchSize() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
/**
|
||||
* 域名管理,实现主备域名自动切换
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public abstract interface WxPayDomain {
|
||||
/**
|
||||
* 上报域名网络状况
|
||||
* @param domain 域名。 比如:api.mch.weixin.qq.com
|
||||
* @param elapsedTimeMillis 耗时
|
||||
* @param ex 网络请求中出现的异常。
|
||||
* null表示没有异常
|
||||
* ConnectTimeoutException,表示建立网络连接异常
|
||||
* UnknownHostException, 表示dns解析异常
|
||||
*/
|
||||
abstract void report(final String domain, long elapsedTimeMillis, final Exception ex);
|
||||
|
||||
/**
|
||||
* 获取域名
|
||||
* @param config 配置
|
||||
* @return 域名
|
||||
*/
|
||||
abstract DomainInfo getDomain(final WxPayConfig config);
|
||||
|
||||
static class DomainInfo{
|
||||
public String domain; //域名
|
||||
public boolean primaryDomain; //该域名是否为主域名。例如:api.mch.weixin.qq.com为主域名
|
||||
public DomainInfo(String domain, boolean primaryDomain) {
|
||||
this.domain = domain;
|
||||
this.primaryDomain = primaryDomain;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DomainInfo{" +
|
||||
"domain='" + domain + '\'' +
|
||||
", primaryDomain=" + primaryDomain +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 微信支付域名实现类(官方简单版)
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxPayDomainSimpleImpl implements WxPayDomain {
|
||||
private WxPayDomainSimpleImpl() {
|
||||
}
|
||||
|
||||
private static class WxpayDomainHolder {
|
||||
private static WxPayDomain holder = new WxPayDomainSimpleImpl();
|
||||
}
|
||||
|
||||
public static WxPayDomain instance() {
|
||||
return WxpayDomainHolder.holder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void report(final String domain, long elapsedTimeMillis, final Exception ex) {
|
||||
DomainStatics info = domainData.get(domain);
|
||||
if (info == null) {
|
||||
info = new DomainStatics(domain);
|
||||
domainData.put(domain, info);
|
||||
}
|
||||
|
||||
// success
|
||||
if (ex == null) {
|
||||
if (info.succCount >= 2) {
|
||||
// continue succ, clear error count
|
||||
info.connectTimeoutCount = info.dnsErrorCount = info.otherErrorCount = 0;
|
||||
} else {
|
||||
++info.succCount;
|
||||
}
|
||||
} else if (ex instanceof ConnectTimeoutException) {
|
||||
info.succCount = info.dnsErrorCount = 0;
|
||||
++info.connectTimeoutCount;
|
||||
} else if (ex instanceof UnknownHostException) {
|
||||
info.succCount = 0;
|
||||
++info.dnsErrorCount;
|
||||
} else {
|
||||
info.succCount = 0;
|
||||
++info.otherErrorCount;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized DomainInfo getDomain(final WxPayConfig config) {
|
||||
DomainStatics primaryDomain = domainData.get(WxPayConstants.DOMAIN_API);
|
||||
if (primaryDomain == null ||
|
||||
primaryDomain.isGood()) {
|
||||
return new DomainInfo(WxPayConstants.DOMAIN_API, true);
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
if (switchToAlternateDomainTime == 0) {
|
||||
// first switch
|
||||
switchToAlternateDomainTime = now;
|
||||
return new DomainInfo(WxPayConstants.DOMAIN_API2, false);
|
||||
} else if (now - switchToAlternateDomainTime < MIN_SWITCH_PRIMARY_MSEC) {
|
||||
DomainStatics alternateDomain = domainData.get(WxPayConstants.DOMAIN_API2);
|
||||
if (alternateDomain == null ||
|
||||
alternateDomain.isGood() ||
|
||||
alternateDomain.badCount() < primaryDomain.badCount()) {
|
||||
return new DomainInfo(WxPayConstants.DOMAIN_API2, false);
|
||||
} else {
|
||||
return new DomainInfo(WxPayConstants.DOMAIN_API, true);
|
||||
}
|
||||
} else { //force switch back
|
||||
switchToAlternateDomainTime = 0;
|
||||
primaryDomain.resetCount();
|
||||
DomainStatics alternateDomain = domainData.get(WxPayConstants.DOMAIN_API2);
|
||||
if (alternateDomain != null) {
|
||||
alternateDomain.resetCount();
|
||||
}
|
||||
return new DomainInfo(WxPayConstants.DOMAIN_API, true);
|
||||
}
|
||||
}
|
||||
|
||||
static class DomainStatics {
|
||||
final String domain;
|
||||
int succCount = 0;
|
||||
int connectTimeoutCount = 0;
|
||||
int dnsErrorCount = 0;
|
||||
int otherErrorCount = 0;
|
||||
|
||||
DomainStatics(String domain) {
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
void resetCount() {
|
||||
succCount = connectTimeoutCount = dnsErrorCount = otherErrorCount = 0;
|
||||
}
|
||||
|
||||
boolean isGood() {
|
||||
return connectTimeoutCount <= 2 && dnsErrorCount <= 2;
|
||||
}
|
||||
|
||||
int badCount() {
|
||||
return connectTimeoutCount + dnsErrorCount * 5 + otherErrorCount / 4;
|
||||
}
|
||||
}
|
||||
|
||||
// 3 minutes
|
||||
private final int MIN_SWITCH_PRIMARY_MSEC = 3 * 60 * 1000;
|
||||
private long switchToAlternateDomainTime = 0;
|
||||
private Map<String, DomainStatics> domainData = new HashMap<String, DomainStatics>();
|
||||
}
|
||||
|
|
@ -0,0 +1,267 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
import com.weixin.pay.util.WxPayUtil;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
/**
|
||||
* 交易保障(官方版)
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxPayReport {
|
||||
|
||||
public static class ReportInfo {
|
||||
|
||||
/**
|
||||
* 布尔变量使用int。0为false, 1为true。
|
||||
*/
|
||||
|
||||
// 基本信息
|
||||
private String version = "v1";
|
||||
private String sdk = WxPayConstants.WXPAYSDK_VERSION;
|
||||
private String uuid; // 交易的标识
|
||||
private long timestamp; // 上报时的时间戳,单位秒
|
||||
private long elapsedTimeMillis; // 耗时,单位 毫秒
|
||||
|
||||
// 针对主域名
|
||||
private String firstDomain; // 第1次请求的域名
|
||||
private boolean primaryDomain; //是否主域名
|
||||
private int firstConnectTimeoutMillis; // 第1次请求设置的连接超时时间,单位 毫秒
|
||||
private int firstReadTimeoutMillis; // 第1次请求设置的读写超时时间,单位 毫秒
|
||||
private int firstHasDnsError; // 第1次请求是否出现dns问题
|
||||
private int firstHasConnectTimeout; // 第1次请求是否出现连接超时
|
||||
private int firstHasReadTimeout; // 第1次请求是否出现连接超时
|
||||
|
||||
public ReportInfo(String uuid, long timestamp, long elapsedTimeMillis, String firstDomain, boolean primaryDomain, int firstConnectTimeoutMillis, int firstReadTimeoutMillis, boolean firstHasDnsError, boolean firstHasConnectTimeout, boolean firstHasReadTimeout) {
|
||||
this.uuid = uuid;
|
||||
this.timestamp = timestamp;
|
||||
this.elapsedTimeMillis = elapsedTimeMillis;
|
||||
this.firstDomain = firstDomain;
|
||||
this.primaryDomain = primaryDomain;
|
||||
this.firstConnectTimeoutMillis = firstConnectTimeoutMillis;
|
||||
this.firstReadTimeoutMillis = firstReadTimeoutMillis;
|
||||
this.firstHasDnsError = firstHasDnsError ? 1 : 0;
|
||||
this.firstHasConnectTimeout = firstHasConnectTimeout ? 1 : 0;
|
||||
this.firstHasReadTimeout = firstHasReadTimeout ? 1 : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ReportInfo{" +
|
||||
"version='" + version + '\'' +
|
||||
", sdk='" + sdk + '\'' +
|
||||
", uuid='" + uuid + '\'' +
|
||||
", timestamp=" + timestamp +
|
||||
", elapsedTimeMillis=" + elapsedTimeMillis +
|
||||
", firstDomain='" + firstDomain + '\'' +
|
||||
", primaryDomain=" + primaryDomain +
|
||||
", firstConnectTimeoutMillis=" + firstConnectTimeoutMillis +
|
||||
", firstReadTimeoutMillis=" + firstReadTimeoutMillis +
|
||||
", firstHasDnsError=" + firstHasDnsError +
|
||||
", firstHasConnectTimeout=" + firstHasConnectTimeout +
|
||||
", firstHasReadTimeout=" + firstHasReadTimeout +
|
||||
'}';
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成 csv 格式
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String toLineString(String key) {
|
||||
String separator = ",";
|
||||
Object[] objects = new Object[]{
|
||||
version, sdk, uuid, timestamp, elapsedTimeMillis,
|
||||
firstDomain, primaryDomain, firstConnectTimeoutMillis, firstReadTimeoutMillis,
|
||||
firstHasDnsError, firstHasConnectTimeout, firstHasReadTimeout
|
||||
};
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (Object obj : objects) {
|
||||
sb.append(obj).append(separator);
|
||||
}
|
||||
try {
|
||||
String sign = WxPayUtil.HMACSHA256(sb.toString(), key);
|
||||
sb.append(sign);
|
||||
return sb.toString();
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final String REPORT_URL = "http://report.mch.weixin.qq.com/wxpay/report/default";
|
||||
// private static final String REPORT_URL = "http://127.0.0.1:5000/test";
|
||||
|
||||
|
||||
private static final int DEFAULT_CONNECT_TIMEOUT_MS = 6 * 1000;
|
||||
private static final int DEFAULT_READ_TIMEOUT_MS = 8 * 1000;
|
||||
|
||||
private LinkedBlockingQueue<String> reportMsgQueue = null;
|
||||
private WxPayConfig config;
|
||||
private ExecutorService executorService;
|
||||
|
||||
private volatile static WxPayReport INSTANCE;
|
||||
|
||||
private WxPayReport(final WxPayConfig config) {
|
||||
this.config = config;
|
||||
reportMsgQueue = new LinkedBlockingQueue<String>(config.getReportQueueMaxSize());
|
||||
|
||||
// 添加处理线程
|
||||
executorService = Executors.newFixedThreadPool(config.getReportWorkerNum(), new ThreadFactory() {
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = Executors.defaultThreadFactory().newThread(r);
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}
|
||||
});
|
||||
|
||||
if (config.shouldAutoReport()) {
|
||||
WxPayUtil.getLogger().info("report worker num: {}", config.getReportWorkerNum());
|
||||
for (int i = 0; i < config.getReportWorkerNum(); ++i) {
|
||||
executorService.execute(new Runnable() {
|
||||
public void run() {
|
||||
while (true) {
|
||||
// 先用 take 获取数据
|
||||
try {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
String firstMsg = reportMsgQueue.take();
|
||||
WxPayUtil.getLogger().info("get first report msg: {}", firstMsg);
|
||||
String msg = null;
|
||||
sb.append(firstMsg); //会阻塞至有消息
|
||||
int remainNum = config.getReportBatchSize() - 1;
|
||||
for (int j = 0; j < remainNum; ++j) {
|
||||
WxPayUtil.getLogger().info("try get remain report msg");
|
||||
// msg = reportMsgQueue.poll(); // 不阻塞了
|
||||
msg = reportMsgQueue.take();
|
||||
WxPayUtil.getLogger().info("get remain report msg: {}", msg);
|
||||
if (msg == null) {
|
||||
break;
|
||||
} else {
|
||||
sb.append("\n");
|
||||
sb.append(msg);
|
||||
}
|
||||
}
|
||||
// 上报
|
||||
WxPayReport.httpRequest(sb.toString(), DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
|
||||
} catch (Exception ex) {
|
||||
WxPayUtil.getLogger().warn("report fail. reason: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 单例,双重校验,请在 JDK 1.5及更高版本中使用
|
||||
*
|
||||
* @param config
|
||||
* @return
|
||||
*/
|
||||
public static WxPayReport getInstance(WxPayConfig config) {
|
||||
if (INSTANCE == null) {
|
||||
synchronized (WxPayReport.class) {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = new WxPayReport(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public void report(String uuid, long elapsedTimeMillis,
|
||||
String firstDomain, boolean primaryDomain, int firstConnectTimeoutMillis, int firstReadTimeoutMillis,
|
||||
boolean firstHasDnsError, boolean firstHasConnectTimeout, boolean firstHasReadTimeout) {
|
||||
long currentTimestamp = WxPayUtil.getCurrentTimestamp();
|
||||
ReportInfo reportInfo = new ReportInfo(uuid, currentTimestamp, elapsedTimeMillis,
|
||||
firstDomain, primaryDomain, firstConnectTimeoutMillis, firstReadTimeoutMillis,
|
||||
firstHasDnsError, firstHasConnectTimeout, firstHasReadTimeout);
|
||||
String data = reportInfo.toLineString(config.getKey());
|
||||
WxPayUtil.getLogger().info("report {}", data);
|
||||
if (data != null) {
|
||||
reportMsgQueue.offer(data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Deprecated
|
||||
private void reportSync(final String data) throws Exception {
|
||||
httpRequest(data, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
private void reportAsync(final String data) throws Exception {
|
||||
new Thread(new Runnable() {
|
||||
public void run() {
|
||||
try {
|
||||
httpRequest(data, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
|
||||
} catch (Exception ex) {
|
||||
WxPayUtil.getLogger().warn("report fail. reason: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* http 请求
|
||||
*
|
||||
* @param data
|
||||
* @param connectTimeoutMs
|
||||
* @param readTimeoutMs
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private static String httpRequest(String data, int connectTimeoutMs, int readTimeoutMs) throws Exception {
|
||||
BasicHttpClientConnectionManager connManager;
|
||||
connManager = new BasicHttpClientConnectionManager(
|
||||
RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", SSLConnectionSocketFactory.getSocketFactory())
|
||||
.build(),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
HttpClient httpClient = HttpClientBuilder.create()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
|
||||
HttpPost httpPost = new HttpPost(REPORT_URL);
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
|
||||
httpPost.setConfig(requestConfig);
|
||||
|
||||
StringEntity postEntity = new StringEntity(data, "UTF-8");
|
||||
httpPost.addHeader("Content-Type", "text/xml");
|
||||
httpPost.addHeader("User-Agent", WxPayConstants.USER_AGENT);
|
||||
httpPost.setEntity(postEntity);
|
||||
|
||||
HttpResponse httpResponse = httpClient.execute(httpPost);
|
||||
HttpEntity httpEntity = httpResponse.getEntity();
|
||||
return EntityUtils.toString(httpEntity, "UTF-8");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
import com.weixin.pay.util.WxPayUtil;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.InputStream;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import static com.weixin.pay.constants.WxPayConstants.USER_AGENT;
|
||||
|
||||
/**
|
||||
* 微信支付请求类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxPayRequest {
|
||||
private WxPayConfig config;
|
||||
|
||||
public WxPayRequest(WxPayConfig config) throws Exception {
|
||||
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求,只请求一次,不做重试
|
||||
*
|
||||
* @param domain
|
||||
* @param urlSuffix
|
||||
* @param uuid
|
||||
* @param data
|
||||
* @param connectTimeoutMs
|
||||
* @param readTimeoutMs
|
||||
* @param useCert 是否使用证书,针对退款、撤销等操作
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private String requestOnce(final String domain, String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert) throws Exception {
|
||||
BasicHttpClientConnectionManager connManager;
|
||||
if (useCert) {
|
||||
// 证书
|
||||
char[] password = config.getMchID().toCharArray();
|
||||
InputStream certStream = config.getCertStream();
|
||||
KeyStore ks = KeyStore.getInstance("PKCS12");
|
||||
ks.load(certStream, password);
|
||||
|
||||
// 实例化密钥库 & 初始化密钥工厂
|
||||
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
kmf.init(ks, password);
|
||||
|
||||
// 创建 SSLContext
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
|
||||
|
||||
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
|
||||
sslContext,
|
||||
new String[]{"TLSv1"},
|
||||
null,
|
||||
new DefaultHostnameVerifier());
|
||||
|
||||
connManager = new BasicHttpClientConnectionManager(
|
||||
RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", sslConnectionSocketFactory)
|
||||
.build(),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
} else {
|
||||
connManager = new BasicHttpClientConnectionManager(
|
||||
RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", SSLConnectionSocketFactory.getSocketFactory())
|
||||
.build(),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
HttpClient httpClient = HttpClientBuilder.create()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
|
||||
String url = "https://" + domain + urlSuffix;
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
|
||||
httpPost.setConfig(requestConfig);
|
||||
|
||||
StringEntity postEntity = new StringEntity(data, "UTF-8");
|
||||
httpPost.addHeader("Content-Type", "text/xml");
|
||||
httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
|
||||
httpPost.setEntity(postEntity);
|
||||
|
||||
HttpResponse httpResponse = httpClient.execute(httpPost);
|
||||
HttpEntity httpEntity = httpResponse.getEntity();
|
||||
return EntityUtils.toString(httpEntity, "UTF-8");
|
||||
|
||||
}
|
||||
|
||||
|
||||
private String request(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert, boolean autoReport) throws Exception {
|
||||
Exception exception = null;
|
||||
long elapsedTimeMillis = 0;
|
||||
long startTimestampMs = WxPayUtil.getCurrentTimestampMs();
|
||||
boolean firstHasDnsErr = false;
|
||||
boolean firstHasConnectTimeout = false;
|
||||
boolean firstHasReadTimeout = false;
|
||||
WxPayDomain.DomainInfo domainInfo = config.getWXPayDomain().getDomain(config);
|
||||
if (domainInfo == null) {
|
||||
throw new Exception("WXPayConfig.getWXPayDomain().getDomain() is empty or null");
|
||||
}
|
||||
try {
|
||||
String result = requestOnce(domainInfo.domain, urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, useCert);
|
||||
elapsedTimeMillis = WxPayUtil.getCurrentTimestampMs() - startTimestampMs;
|
||||
config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, null);
|
||||
WxPayReport.getInstance(config).report(
|
||||
uuid,
|
||||
elapsedTimeMillis,
|
||||
domainInfo.domain,
|
||||
domainInfo.primaryDomain,
|
||||
connectTimeoutMs,
|
||||
readTimeoutMs,
|
||||
firstHasDnsErr,
|
||||
firstHasConnectTimeout,
|
||||
firstHasReadTimeout);
|
||||
return result;
|
||||
} catch (UnknownHostException ex) { // dns 解析错误,或域名不存在
|
||||
exception = ex;
|
||||
firstHasDnsErr = true;
|
||||
elapsedTimeMillis = WxPayUtil.getCurrentTimestampMs() - startTimestampMs;
|
||||
WxPayUtil.getLogger().warn("UnknownHostException for domainInfo {}", domainInfo);
|
||||
WxPayReport.getInstance(config).report(
|
||||
uuid,
|
||||
elapsedTimeMillis,
|
||||
domainInfo.domain,
|
||||
domainInfo.primaryDomain,
|
||||
connectTimeoutMs,
|
||||
readTimeoutMs,
|
||||
firstHasDnsErr,
|
||||
firstHasConnectTimeout,
|
||||
firstHasReadTimeout
|
||||
);
|
||||
} catch (ConnectTimeoutException ex) {
|
||||
exception = ex;
|
||||
firstHasConnectTimeout = true;
|
||||
elapsedTimeMillis = WxPayUtil.getCurrentTimestampMs() - startTimestampMs;
|
||||
WxPayUtil.getLogger().warn("connect timeout happened for domainInfo {}", domainInfo);
|
||||
WxPayReport.getInstance(config).report(
|
||||
uuid,
|
||||
elapsedTimeMillis,
|
||||
domainInfo.domain,
|
||||
domainInfo.primaryDomain,
|
||||
connectTimeoutMs,
|
||||
readTimeoutMs,
|
||||
firstHasDnsErr,
|
||||
firstHasConnectTimeout,
|
||||
firstHasReadTimeout
|
||||
);
|
||||
} catch (SocketTimeoutException ex) {
|
||||
exception = ex;
|
||||
firstHasReadTimeout = true;
|
||||
elapsedTimeMillis = WxPayUtil.getCurrentTimestampMs() - startTimestampMs;
|
||||
WxPayUtil.getLogger().warn("timeout happened for domainInfo {}", domainInfo);
|
||||
WxPayReport.getInstance(config).report(
|
||||
uuid,
|
||||
elapsedTimeMillis,
|
||||
domainInfo.domain,
|
||||
domainInfo.primaryDomain,
|
||||
connectTimeoutMs,
|
||||
readTimeoutMs,
|
||||
firstHasDnsErr,
|
||||
firstHasConnectTimeout,
|
||||
firstHasReadTimeout);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
elapsedTimeMillis = WxPayUtil.getCurrentTimestampMs() - startTimestampMs;
|
||||
WxPayReport.getInstance(config).report(
|
||||
uuid,
|
||||
elapsedTimeMillis,
|
||||
domainInfo.domain,
|
||||
domainInfo.primaryDomain,
|
||||
connectTimeoutMs,
|
||||
readTimeoutMs,
|
||||
firstHasDnsErr,
|
||||
firstHasConnectTimeout,
|
||||
firstHasReadTimeout);
|
||||
}
|
||||
config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, exception);
|
||||
throw exception;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 可重试的,非双向认证的请求
|
||||
*
|
||||
* @param urlSuffix
|
||||
* @param uuid
|
||||
* @param data
|
||||
* @return
|
||||
*/
|
||||
public String requestWithoutCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception {
|
||||
return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), false, autoReport);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可重试的,非双向认证的请求
|
||||
*
|
||||
* @param urlSuffix
|
||||
* @param uuid
|
||||
* @param data
|
||||
* @param connectTimeoutMs
|
||||
* @param readTimeoutMs
|
||||
* @return
|
||||
*/
|
||||
public String requestWithoutCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception {
|
||||
return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, false, autoReport);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可重试的,双向认证的请求
|
||||
*
|
||||
* @param urlSuffix
|
||||
* @param uuid
|
||||
* @param data
|
||||
* @return
|
||||
*/
|
||||
public String requestWithCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception {
|
||||
return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), true, autoReport);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可重试的,双向认证的请求
|
||||
*
|
||||
* @param urlSuffix
|
||||
* @param uuid
|
||||
* @param data
|
||||
* @param connectTimeoutMs
|
||||
* @param readTimeoutMs
|
||||
* @return
|
||||
*/
|
||||
public String requestWithCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception {
|
||||
return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, true, autoReport);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package com.weixin.pay;
|
||||
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* 测试/第二个微信支付实体的微信支付实现类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/7/31
|
||||
*/
|
||||
public class XxxWxPayConfigImpl extends WxPayConfig {
|
||||
|
||||
private byte[] certData;
|
||||
private static XxxWxPayConfigImpl INSTANCE;
|
||||
|
||||
private XxxWxPayConfigImpl() throws Exception{
|
||||
String certPath = WxPayConstants.APICLIENT_CERT_XXX;
|
||||
File file = new File(certPath);
|
||||
InputStream certStream = new FileInputStream(file);
|
||||
this.certData = new byte[(int) file.length()];
|
||||
certStream.read(this.certData);
|
||||
certStream.close();
|
||||
}
|
||||
|
||||
public static XxxWxPayConfigImpl getInstance() throws Exception{
|
||||
if (INSTANCE == null) {
|
||||
synchronized (XxxWxPayConfigImpl.class) {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = new XxxWxPayConfigImpl();
|
||||
}
|
||||
}
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAppID() {
|
||||
return WxPayConstants.APP_ID_XXX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMchID() {
|
||||
return WxPayConstants.MCH_ID_XXX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKey() {
|
||||
return WxPayConstants.API_KEY_XXX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getCertStream() {
|
||||
ByteArrayInputStream certBis;
|
||||
certBis = new ByteArrayInputStream(this.certData);
|
||||
return certBis;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHttpConnectTimeoutMs() {
|
||||
return 2000;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHttpReadTimeoutMs() {
|
||||
return 10000;
|
||||
}
|
||||
|
||||
@Override
|
||||
WxPayDomain getWXPayDomain() {
|
||||
return WxPayDomainSimpleImpl.instance();
|
||||
}
|
||||
|
||||
public String getPrimaryDomain() {
|
||||
return "api.mch.weixin.qq.com";
|
||||
}
|
||||
|
||||
public String getAlternateDomain() {
|
||||
return "api2.mch.weixin.qq.com";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReportWorkerNum() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReportBatchSize() {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package com.weixin.pay.constants;
|
||||
|
||||
/**
|
||||
* 微信支付code码常量类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/6
|
||||
*/
|
||||
public enum WxPayCodeEnum {
|
||||
|
||||
/**
|
||||
* 余额不足
|
||||
*/
|
||||
ERR_CODE_NOTENOUGH("NOTENOUGH", "余额不足");
|
||||
|
||||
private String code;
|
||||
private String des;
|
||||
|
||||
WxPayCodeEnum(String code, String des) {
|
||||
this.code = code;
|
||||
this.des = des;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getDes() {
|
||||
return des;
|
||||
}
|
||||
|
||||
public void setDes(String des) {
|
||||
this.des = des;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,223 @@
|
|||
package com.weixin.pay.constants;
|
||||
|
||||
import org.apache.http.client.HttpClient;
|
||||
|
||||
/**
|
||||
* 微信支付SDK常量
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxPayConstants {
|
||||
|
||||
/**
|
||||
* 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
|
||||
*/
|
||||
public static String NOTIFY_URL = "https://xxx.com/v1/weixin/pay/wxnotify";
|
||||
|
||||
/**
|
||||
* 异步接收微信支付退款结果通知的回调地址,通知URL必须为外网可访问的url,不允许带参数,如果参数中传了notify_url,则商户平台上配置的回调地址将不会生效。
|
||||
*/
|
||||
public static String NOTIFY_URL_REFUND = "https://xxx.com/v1/weixin/pay/refund";
|
||||
|
||||
/**
|
||||
* 微信签名枚举类型
|
||||
*/
|
||||
public enum SignType {
|
||||
MD5, HMACSHA256
|
||||
}
|
||||
|
||||
/**
|
||||
* 公众号、小程序appid
|
||||
*/
|
||||
public static String APP_ID = "xxx"; // 真实
|
||||
public static String APP_ID_XXX = "xxx"; // 测试/第二个账号
|
||||
|
||||
/**
|
||||
* AppSecret
|
||||
*/
|
||||
public static String SECRET = "xxx"; // 真实
|
||||
public static String SECRET_XXX = "xxx"; // 测试/第二个账号
|
||||
|
||||
/**
|
||||
* 商户号
|
||||
*/
|
||||
public static final String MCH_ID = "xxx"; // 真实
|
||||
public static final String MCH_ID_XXX = "xxx"; // 测试/第二个账号
|
||||
|
||||
|
||||
/**
|
||||
* API密钥,在商户平台设置
|
||||
*/
|
||||
public static final String API_KEY = "xxx"; // 真实
|
||||
public static final String API_KEY_XXX = "xxx"; // 测试/第二个账号
|
||||
public static final String API_KEY_SANDBOX = "xxx"; // sandbox_signkey
|
||||
|
||||
/**
|
||||
* 证书路径
|
||||
*/
|
||||
public static String APICLIENT_CERT = "/data/ops/cert/apiclient_cert.p12"; // 真实
|
||||
public static String APICLIENT_CERT_XXX = "/data/ops/cert_xxx/apiclient_cert.p12"; // 真实
|
||||
|
||||
/**
|
||||
* 交易类型
|
||||
* JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里
|
||||
* MICROPAY--刷卡支付,刷卡支付有单独的支付接口,不调用统一下单接口
|
||||
*/
|
||||
public static String TRADE_TYPE = "JSAPI";
|
||||
public static String TRADE_TYPE_APP = "APP";
|
||||
public static String TRADE_TYPE_NATIVE = "NATIVE";
|
||||
|
||||
/**
|
||||
* 微信 - API域名地址
|
||||
* 域名管理实现主备域名自动切换
|
||||
*/
|
||||
public static final String DOMAIN_API = "api.mch.weixin.qq.com";
|
||||
public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
|
||||
public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
|
||||
public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";
|
||||
|
||||
/**
|
||||
* 微信 - 默认接口返回状态码
|
||||
* SUCCESS/FAIL
|
||||
* 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
|
||||
*/
|
||||
public static final String RESULT_CODE = "result_code";
|
||||
public static final String FAIL = "FAIL";
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
/**
|
||||
* 返回状态码 return_code SUCCESS/FAIL 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
|
||||
* 返回信息 return_msg 当return_code为FAIL时返回信息为错误原因
|
||||
* 错误代码 err_code 当result_code为FAIL时返回错误代码,详细参见下文错误列表
|
||||
* 错误代码描述 err_code_des 当result_code为FAIL时返回错误描述,详细参见下文错误列表
|
||||
*/
|
||||
public static final String RETURN_CODE = "return_code";
|
||||
public static final String RETURN_MSG = "return_msg";
|
||||
public static final String ERR_CODE = "err_code";
|
||||
public static final String ERR_CODE_DES = "err_code_des";
|
||||
|
||||
/**
|
||||
* 签名类型,默认为MD5,支持HMAC-SHA256和MD5。
|
||||
*/
|
||||
public static final String HMACSHA256 = "HMAC-SHA256";
|
||||
public static final String MD5 = "MD5";
|
||||
|
||||
/**
|
||||
* 标价币种:fee_type
|
||||
* 符合ISO 4217标准的三位字母代码,默认人民币:CNY,详细列表请参见货币类型
|
||||
*/
|
||||
public static final String FEE_TYPE_CNY = "CNY";
|
||||
|
||||
/**
|
||||
* 微信签名:通过签名算法计算得出的签名值
|
||||
*/
|
||||
public static final String FIELD_SIGN = "sign";
|
||||
public static final String FIELD_SIGN_TYPE = "sign_type";
|
||||
|
||||
/**
|
||||
* 微信支付版本
|
||||
*/
|
||||
public static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.9";
|
||||
public static final String USER_AGENT = WXPAYSDK_VERSION +
|
||||
" (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
|
||||
") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();
|
||||
|
||||
/**
|
||||
* 作用:企业付款到零钱资金使用商户号余额资金<br>
|
||||
* 场景:用于企业向微信用户个人付款
|
||||
*/
|
||||
public static final String TRANSFERS_URL_SUFFIX = "/mmpaymkttransfers/promotion/transfers";
|
||||
/**
|
||||
* 作用:商户平台-现金红包-发放普通红包<br>
|
||||
* 场景:现金红包发放后会以公众号消息的形式触达用户
|
||||
* 其他:需要证书
|
||||
*/
|
||||
public static final String SENDREDPACK_URL_SUFFIX = "/mmpaymkttransfers/sendredpack";
|
||||
/**
|
||||
* 作用:提交刷卡支付<br>
|
||||
* 场景:刷卡支付
|
||||
*/
|
||||
public static final String MICROPAY_URL_SUFFIX = "/pay/micropay";
|
||||
/**
|
||||
* 作用:统一下单<br>
|
||||
* 场景:公共号支付、扫码支付、APP支付
|
||||
*/
|
||||
public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
|
||||
/**
|
||||
* 作用:查询订单<br>
|
||||
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
|
||||
*/
|
||||
public static final String ORDERQUERY_URL_SUFFIX = "/pay/orderquery";
|
||||
/**
|
||||
* 作用:撤销订单<br>
|
||||
* 场景:刷卡支付<br>
|
||||
* 其他:需要证书
|
||||
*/
|
||||
public static final String REVERSE_URL_SUFFIX = "/secapi/pay/reverse";
|
||||
/**
|
||||
* 作用:关闭订单<br>
|
||||
* 场景:公共号支付、扫码支付、APP支付
|
||||
*/
|
||||
public static final String CLOSEORDER_URL_SUFFIX = "/pay/closeorder";
|
||||
/**
|
||||
* 作用:申请退款<br>
|
||||
* 场景:刷卡支付、公共号支付、扫码支付、APP支付<br>
|
||||
* 其他:需要证书
|
||||
*/
|
||||
public static final String REFUND_URL_SUFFIX = "/secapi/pay/refund";
|
||||
/**
|
||||
* 作用:退款查询<br>
|
||||
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
|
||||
*/
|
||||
public static final String REFUNDQUERY_URL_SUFFIX = "/pay/refundquery";
|
||||
/**
|
||||
* 作用:对账单下载<br>
|
||||
* 场景:刷卡支付、公共号支付、扫码支付、APP支付<br>
|
||||
* 其他:无论是否成功都返回Map。若成功,返回的Map中含有return_code、return_msg、data,
|
||||
* 其中return_code为`SUCCESS`,data为对账单数据。
|
||||
*/
|
||||
public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
|
||||
/**
|
||||
* 作用:交易保障<br>
|
||||
* 场景:刷卡支付、公共号支付、扫码支付、APP支付
|
||||
*/
|
||||
public static final String REPORT_URL_SUFFIX = "/payitil/report";
|
||||
/**
|
||||
* 作用:转换短链接<br>
|
||||
* 场景:刷卡支付、扫码支付
|
||||
*/
|
||||
public static final String SHORTURL_URL_SUFFIX = "/tools/shorturl";
|
||||
/**
|
||||
* 作用:授权码查询OPENID接口<br>
|
||||
* 场景:刷卡支付
|
||||
*/
|
||||
public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";
|
||||
|
||||
/**
|
||||
* 沙箱说明:sandbox
|
||||
*
|
||||
* 微信支付沙箱环境,是提供给微信支付商户的开发者,用于模拟支付及回调通知。以验证商户是否理解回调通知、账单格式,以及是否对异常做了正确的处理。
|
||||
* ◆ 如何对接沙箱环境?
|
||||
* 1、修改商户自有程序或配置中,微信支付api的链接,如:被扫支付官网的url为:https://api.mch.weixin.qq.com/pay/micropay增加sandbox路径,变更为https://api.mch.weixin.qq.com/sandbox/pay/micropay, 即可接入沙箱验收环境,其它接口类似;
|
||||
* 2、在微信支付开发调试站点(站点链接:http://mch.weixin.qq.com/wiki/doc/api/index.php),按接口文档填入正确的支付参数,发起微信支付请求,完成支付;
|
||||
* 3、验收完成后,修改程序或配置中的api链接(重要!),去掉sandbox路径。对接现网环境。
|
||||
*
|
||||
* 说明地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=23_1
|
||||
* https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=21_2
|
||||
*/
|
||||
public static final String SANDBOX_MICROPAY_URL_SUFFIX = "/sandboxnew/pay/micropay";
|
||||
public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
|
||||
public static final String SANDBOX_ORDERQUERY_URL_SUFFIX = "/sandboxnew/pay/orderquery";
|
||||
public static final String SANDBOX_REVERSE_URL_SUFFIX = "/sandboxnew/secapi/pay/reverse";
|
||||
public static final String SANDBOX_CLOSEORDER_URL_SUFFIX = "/sandboxnew/pay/closeorder";
|
||||
public static final String SANDBOX_REFUND_URL_SUFFIX = "/sandboxnew/secapi/pay/refund";
|
||||
public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX = "/sandboxnew/pay/refundquery";
|
||||
public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
|
||||
public static final String SANDBOX_REPORT_URL_SUFFIX = "/sandboxnew/payitil/report";
|
||||
public static final String SANDBOX_SHORTURL_URL_SUFFIX = "/sandboxnew/tools/shorturl";
|
||||
public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";
|
||||
public static final String SANDBOX_SENDREDPACK_URL_SUFFIX = "/sandboxnew/mmpaymkttransfers/sendredpack";
|
||||
public static final String SANDBOX_TRANSFERS_URL_SUFFIX = "/sandboxnew/mmpaymkttransfers/promotion/transfers";
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
package com.weixin.pay.util;
|
||||
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.Security;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* 微信支付AES加解密工具类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/6/21
|
||||
*/
|
||||
public class AesUtil {
|
||||
|
||||
/**
|
||||
* 密钥算法
|
||||
*/
|
||||
private static final String ALGORITHM = "AES";
|
||||
|
||||
/**
|
||||
* 加解密算法/工作模式/填充方式
|
||||
*/
|
||||
private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";
|
||||
|
||||
/**
|
||||
* 生成key
|
||||
*/
|
||||
private static SecretKeySpec KEY;
|
||||
|
||||
static {
|
||||
try {
|
||||
KEY = new SecretKeySpec(WxPayUtil.MD5(WxPayConstants.API_KEY).toLowerCase().getBytes(), ALGORITHM);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AES加密
|
||||
*
|
||||
* @param data d
|
||||
* @return str
|
||||
* @throws Exception e
|
||||
*/
|
||||
public static String encryptData(String data) throws Exception {
|
||||
// 创建密码器
|
||||
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
|
||||
// 初始化
|
||||
cipher.init(Cipher.ENCRYPT_MODE, KEY);
|
||||
return base64Encode8859(new String(cipher.doFinal(data.getBytes()), "ISO-8859-1"));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* AES解密
|
||||
*
|
||||
* @param base64Data 64
|
||||
* @return str
|
||||
* @throws Exception e
|
||||
*/
|
||||
public static String decryptData(String base64Data) throws Exception {
|
||||
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
|
||||
cipher.init(Cipher.DECRYPT_MODE, KEY);
|
||||
return new String(cipher.doFinal(base64Decode8859(base64Data).getBytes("ISO-8859-1")), "utf-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64解码
|
||||
* @param source base64 str
|
||||
* @return str
|
||||
*/
|
||||
public static String base64Decode8859(final String source) {
|
||||
String result = "";
|
||||
final Base64.Decoder decoder = Base64.getDecoder();
|
||||
try {
|
||||
// 此处的字符集是ISO-8859-1
|
||||
result = new String(decoder.decode(source), "ISO-8859-1");
|
||||
} catch (final UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64加密
|
||||
* @param source str
|
||||
* @return base64 str
|
||||
*/
|
||||
public static String base64Encode8859(final String source) {
|
||||
String result = "";
|
||||
final Base64.Encoder encoder = Base64.getEncoder();
|
||||
byte[] textByte = null;
|
||||
try {
|
||||
//注意此处的编码是ISO-8859-1
|
||||
textByte = source.getBytes("ISO-8859-1");
|
||||
result = encoder.encodeToString(textByte);
|
||||
} catch (final UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String A = "qS/pmvAXYetUObwHm9bAod9G3SVBKQK5CiIgETwHJT4ExUpJnIg87m37KlokIsBZCnQBIO2Ear7Q/IazZ6jDNsnmsITqYt1hPYloGjdjRGlqdSSBVRjk9NIkRRQIlb+5AOHJttfVKMsbMK8FzoysE+rL8yKaOzXvsNCA2g60z3bEw3x891ZwPPiUSkVJGeIHpafWdR94Y/j3hfsrEw5KOTGiPneH5d9zhC73MW/kDWu9+wDkJCtCf5fNc9GIC5x2zKNZozpQ9wT/WLyjSz/En166xbgUt9tApaaQSayFQ0eSokMjYYLKO5KJQ355QtkvZlW96rX9IO6hVHXDgPD7kJOTh/L99ZQtG5umLBfOd9i3xVH4qH+gvi/i0gEpvQOhTvxcrZeKs8Rsliua46u/aBdUy6GlICRxQPmvKBfL9cE2L5MZGqHkCMTmSr1i4L8Ubxoi3Yv6TCTTOo4MVc64igb9HttMVfOiLFrZKAyH64Y5C6+GATUMSzWhXDn089QyrZk+W6GFkQlA6dBlO7v0aucF8t3L6SFtnxm6XkH6eD4/FFxKz+wsqKDX1s+GnPGQdwjxsS3RLGjJuNoSB7N+v4AUbMgLT2sBzew89ow7/vEUMjJMQt3eISwprOaDZqZQBgdLVUwDyWnrWi50Rr2wEuJXv/m6x8f40wN93L8GvGbMsWGXlp9V9W3LR2LZD9CnrWAlhoYoDGMAwCKuPh+dfjXmVGttGxegM+PlUR8nq6Qr1zwHz4dV3PgzWlf3n5qR72tAJ/Y0045n3dT7Iw4UNzBHC6XkUIA884paHbZ3D0V95+WrdyVQ4icsgZIneaAMZfslVsnigUjnXl3m/qZGlW5A6d93VXNe8bQgA6s6lJeEsaZc3sLVPi5Tlr2nfbgdhB4XqYkR4DebEbUzalSOqM+OOeCsYj920+FboIxvShy2ECk6bjebMM3kYw0s1NUWXynKFTvbgZ35H9TNKaeom1qYVmbb/581N8+sO3yDDFzZaaqLqOtaUtgIe2SOS2A6GRnKSanqbsJVU4j2amWEpicl3WchYV9KPeuoqodu+4UCsaY2juUIcbbof/ygkG5NkDz27RA4fBxxAlqvtzEftw==";
|
||||
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
|
||||
System.out.println(AesUtil.decryptData(A));
|
||||
|
||||
/*String B = AESUtil.decryptData(A);
|
||||
System.out.println(B);*/
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,309 @@
|
|||
package com.weixin.pay.util;
|
||||
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
import com.weixin.pay.constants.WxPayConstants.SignType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 微信支付工具类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxPayUtil {
|
||||
|
||||
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
private static final Random RANDOM = new SecureRandom();
|
||||
|
||||
/**
|
||||
* XML格式字符串转换为Map
|
||||
*
|
||||
* @param strXML XML字符串
|
||||
* @return XML数据转换后的Map
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Map<String, String> xmlToMap(String strXML) throws Exception {
|
||||
try {
|
||||
Map<String, String> data = new HashMap<String, String>();
|
||||
DocumentBuilder documentBuilder = WxPayXmlUtil.newDocumentBuilder();
|
||||
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
|
||||
org.w3c.dom.Document doc = documentBuilder.parse(stream);
|
||||
doc.getDocumentElement().normalize();
|
||||
NodeList nodeList = doc.getDocumentElement().getChildNodes();
|
||||
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
|
||||
Node node = nodeList.item(idx);
|
||||
if (node.getNodeType() == Node.ELEMENT_NODE) {
|
||||
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
|
||||
data.put(element.getNodeName(), element.getTextContent());
|
||||
}
|
||||
}
|
||||
try {
|
||||
stream.close();
|
||||
} catch (Exception ex) {
|
||||
// do nothing
|
||||
}
|
||||
return data;
|
||||
} catch (Exception ex) {
|
||||
WxPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
|
||||
throw ex;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将Map转换为XML格式的字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @return XML格式的字符串
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String mapToXml(Map<String, String> data) throws Exception {
|
||||
org.w3c.dom.Document document = WxPayXmlUtil.newDocument();
|
||||
org.w3c.dom.Element root = document.createElement("xml");
|
||||
document.appendChild(root);
|
||||
for (String key: data.keySet()) {
|
||||
String value = data.get(key);
|
||||
if (value == null) {
|
||||
value = "";
|
||||
}
|
||||
value = value.trim();
|
||||
org.w3c.dom.Element filed = document.createElement(key);
|
||||
filed.appendChild(document.createTextNode(value));
|
||||
root.appendChild(filed);
|
||||
}
|
||||
TransformerFactory tf = TransformerFactory.newInstance();
|
||||
Transformer transformer = tf.newTransformer();
|
||||
DOMSource source = new DOMSource(document);
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
StringWriter writer = new StringWriter();
|
||||
StreamResult result = new StreamResult(writer);
|
||||
transformer.transform(source, result);
|
||||
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
|
||||
try {
|
||||
writer.close();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成带有 sign 的 XML 格式字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @return 含有sign字段的XML
|
||||
*/
|
||||
public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
|
||||
return generateSignedXml(data, key, SignType.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带有 sign 的 XML 格式字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @param signType 签名类型
|
||||
* @return 含有sign字段的XML
|
||||
*/
|
||||
public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
|
||||
String sign = generateSignature(data, key, signType);
|
||||
data.put(WxPayConstants.FIELD_SIGN, sign);
|
||||
return mapToXml(data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断签名是否正确
|
||||
*
|
||||
* @param xmlStr XML格式数据
|
||||
* @param key API密钥
|
||||
* @return 签名是否正确
|
||||
* @throws Exception
|
||||
*/
|
||||
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
|
||||
Map<String, String> data = xmlToMap(xmlStr);
|
||||
if (!data.containsKey(WxPayConstants.FIELD_SIGN) ) {
|
||||
return false;
|
||||
}
|
||||
String sign = data.get(WxPayConstants.FIELD_SIGN);
|
||||
return generateSignature(data, key).equals(sign);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @return 签名是否正确
|
||||
* @throws Exception
|
||||
*/
|
||||
public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
|
||||
return isSignatureValid(data, key, SignType.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断签名是否正确,必须包含sign字段,否则返回false。
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @param signType 签名方式
|
||||
* @return 签名是否正确
|
||||
* @throws Exception
|
||||
*/
|
||||
public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception {
|
||||
if (!data.containsKey(WxPayConstants.FIELD_SIGN) ) {
|
||||
return false;
|
||||
}
|
||||
String sign = data.get(WxPayConstants.FIELD_SIGN);
|
||||
return generateSignature(data, key, signType).equals(sign);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名
|
||||
*
|
||||
* @param data 待签名数据
|
||||
* @param key API密钥
|
||||
* @return 签名
|
||||
*/
|
||||
public static String generateSignature(final Map<String, String> data, String key) throws Exception {
|
||||
return generateSignature(data, key, SignType.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
|
||||
*
|
||||
* @param data 待签名数据
|
||||
* @param key API密钥
|
||||
* @param signType 签名方式
|
||||
* @return 签名
|
||||
*/
|
||||
public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
|
||||
Set<String> keySet = data.keySet();
|
||||
String[] keyArray = keySet.toArray(new String[keySet.size()]);
|
||||
Arrays.sort(keyArray);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String k : keyArray) {
|
||||
if (k.equals(WxPayConstants.FIELD_SIGN)) {
|
||||
continue;
|
||||
}
|
||||
if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
|
||||
sb.append(k).append("=").append(data.get(k).trim()).append("&");
|
||||
}
|
||||
sb.append("key=").append(key);
|
||||
if (SignType.MD5.equals(signType)) {
|
||||
WxPayUtil.getLogger().info("signPay=" + sb.toString());
|
||||
return MD5(sb.toString()).toUpperCase();
|
||||
}
|
||||
else if (SignType.HMACSHA256.equals(signType)) {
|
||||
return HMACSHA256(sb.toString(), key);
|
||||
}
|
||||
else {
|
||||
throw new Exception(String.format("Invalid sign_type: %s", signType));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取随机字符串 Nonce Str
|
||||
*
|
||||
* @return String 随机字符串
|
||||
*/
|
||||
public static String generateNonceStr() {
|
||||
char[] nonceChars = new char[32];
|
||||
for (int index = 0; index < nonceChars.length; ++index) {
|
||||
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
|
||||
}
|
||||
return new String(nonceChars);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成 MD5
|
||||
*
|
||||
* @param data 待处理数据
|
||||
* @return MD5结果
|
||||
*/
|
||||
public static String MD5(String data) throws Exception {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] array = md.digest(data.getBytes("UTF-8"));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte item : array) {
|
||||
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
|
||||
}
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 HMACSHA256
|
||||
* @param data 待处理数据
|
||||
* @param key 密钥
|
||||
* @return 加密结果
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String HMACSHA256(String data, String key) throws Exception {
|
||||
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
|
||||
sha256_HMAC.init(secret_key);
|
||||
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte item : array) {
|
||||
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
|
||||
}
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 日志
|
||||
* @return
|
||||
*/
|
||||
public static Logger getLogger() {
|
||||
return LoggerFactory.getLogger("wxpay java sdk");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间戳,单位秒
|
||||
* @return
|
||||
*/
|
||||
public static long getCurrentTimestamp() {
|
||||
return System.currentTimeMillis()/1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间戳,单位毫秒
|
||||
* @return
|
||||
*/
|
||||
public static long getCurrentTimestampMs() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 uuid, 即用来标识一笔单,也用做 nonce_str
|
||||
* @return
|
||||
*/
|
||||
public static String generateUUID() {
|
||||
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package com.weixin.pay.util;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
/**
|
||||
* 微信支付xml转换工具类
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public final class WxPayXmlUtil {
|
||||
|
||||
/**
|
||||
* 生成一个微信的xml文档
|
||||
* @return DocumentBuilder
|
||||
* @throws ParserConfigurationException e
|
||||
*/
|
||||
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
|
||||
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
|
||||
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
documentBuilderFactory.setXIncludeAware(false);
|
||||
documentBuilderFactory.setExpandEntityReferences(false);
|
||||
return documentBuilderFactory.newDocumentBuilder();
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建doc文档
|
||||
* @return Document
|
||||
* @throws ParserConfigurationException e
|
||||
*/
|
||||
public static Document newDocument() throws ParserConfigurationException {
|
||||
return newDocumentBuilder().newDocument();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,226 @@
|
|||
package com.weixin.pay.util;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.weixin.pay.constants.WxPayConstants;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Formatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 微信签名工具
|
||||
*
|
||||
* @author yclimb
|
||||
* @date 2018/8/17
|
||||
*/
|
||||
public class WxSignatureUtil {
|
||||
|
||||
/**
|
||||
* 获取微信签名信息
|
||||
* @param request
|
||||
* @param requestUrl 请求页面地址
|
||||
* @return 返回map:noncestr:随机字符串;timestamp:签名时间戳;appid;微信公众号Id;signature:签名串
|
||||
* @throws ClientProtocolException
|
||||
* @throws IOException
|
||||
* @throws CloneNotSupportedException
|
||||
*/
|
||||
public static Map<String,Object> getSignature(HttpServletRequest request, String requestUrl) throws ClientProtocolException, IOException, CloneNotSupportedException{
|
||||
Map<String, Object> map = new HashMap<String,Object>();
|
||||
|
||||
HttpSession session = request.getSession();
|
||||
|
||||
// 直接查询签名信息
|
||||
Object objMap = session.getAttribute(requestUrl);
|
||||
if (objMap != null) {
|
||||
return (Map<String, Object>) objMap;
|
||||
}
|
||||
|
||||
String appid = WxPayConstants.APP_ID;
|
||||
String secret = WxPayConstants.SECRET;
|
||||
String token;
|
||||
String jsapi_ticket;
|
||||
|
||||
Object tokenObj = session.getAttribute("token");
|
||||
if (tokenObj != null) {
|
||||
token = String.valueOf(tokenObj);
|
||||
} else {
|
||||
token = getToken(appid, secret);
|
||||
session.setAttribute("token", token);
|
||||
}
|
||||
|
||||
Object jsapiTicketObj = session.getAttribute("jsapi_ticket");
|
||||
if (jsapiTicketObj != null) {
|
||||
jsapi_ticket = String.valueOf(jsapiTicketObj);
|
||||
} else {
|
||||
jsapi_ticket = getTicket(token);
|
||||
session.setAttribute("jsapi_ticket", jsapi_ticket);
|
||||
}
|
||||
|
||||
String nonce_str = createNonceStr();
|
||||
String timestamp = createTimestamp();
|
||||
|
||||
String signature = "";
|
||||
|
||||
//注意这里参数名必须全部小写,且必须有序
|
||||
String string1 = "jsapi_ticket=" + jsapi_ticket +
|
||||
"&noncestr=" + nonce_str +
|
||||
"×tamp=" + timestamp +
|
||||
"&url=" + requestUrl;
|
||||
WxPayUtil.getLogger().info(string1);
|
||||
|
||||
try {
|
||||
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
|
||||
crypt.reset();
|
||||
crypt.update(string1.getBytes("UTF-8"));
|
||||
signature = byteToHex(crypt.digest());
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
map.put("noncestr", nonce_str);
|
||||
map.put("timestamp", timestamp);
|
||||
map.put("appid", appid);
|
||||
map.put("signature", signature);
|
||||
|
||||
session.setAttribute(requestUrl, map);
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
private static String byteToHex(final byte[] hash) {
|
||||
Formatter formatter = new Formatter();
|
||||
for (byte b : hash)
|
||||
{
|
||||
formatter.format("%02x", b);
|
||||
}
|
||||
String result = formatter.toString();
|
||||
formatter.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String createNonceStr() {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
public static String createTimestamp() {
|
||||
return Long.toString(System.currentTimeMillis() / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param appid 公众号应用id
|
||||
* @param secret 公众号应用密钥
|
||||
* @return 返回token
|
||||
* @throws IOException
|
||||
* @throws CloneNotSupportedException
|
||||
*/
|
||||
public static String getToken(String appid,String secret) throws IOException, CloneNotSupportedException{
|
||||
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
|
||||
WxPayUtil.getLogger().info("url:" + url);
|
||||
// 生成一个请求对象
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
// 生成一个Http客户端对象
|
||||
HttpClient httpClient = new DefaultHttpClient();
|
||||
// 下面使用Http客户端发送请求,并获取响应内容
|
||||
InputStream inputStream = null;
|
||||
// 发送请求并获得响应对象
|
||||
HttpResponse mHttpResponse = null;
|
||||
|
||||
BufferedReader bufferedReader = null;
|
||||
String result = "";
|
||||
String line;
|
||||
try {
|
||||
mHttpResponse = httpClient.execute(httpGet);
|
||||
// 获得响应的消息实体
|
||||
HttpEntity mHttpEntity = mHttpResponse.getEntity();
|
||||
|
||||
// 获取一个输入流
|
||||
inputStream = mHttpEntity.getContent();
|
||||
bufferedReader = new BufferedReader(
|
||||
new InputStreamReader(inputStream));
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
result += line;
|
||||
}
|
||||
JSONObject json = JSONObject.parseObject(result);
|
||||
return json.get("access_token").toString();
|
||||
} catch (IOException e) {
|
||||
throw new IOException("获取access_token异常!");
|
||||
}finally {
|
||||
bufferedReader.close();
|
||||
inputStream.close();
|
||||
httpGet.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param access_token 生成的token
|
||||
* @return 返回jsapi_ticket
|
||||
* @throws ClientProtocolException
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String getTicket(String access_token) throws ClientProtocolException, IOException{
|
||||
HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi");
|
||||
// 生成一个Http客户端对象
|
||||
HttpClient httpClient = new DefaultHttpClient();
|
||||
// 下面使用Http客户端发送请求,并获取响应内容
|
||||
InputStream inputStream = null;
|
||||
// 发送请求并获得响应对象
|
||||
HttpResponse mHttpResponse = null;
|
||||
|
||||
BufferedReader bufferedReader = null;
|
||||
String result = "";
|
||||
String line;
|
||||
try {
|
||||
mHttpResponse = httpClient.execute(httpGet);
|
||||
HttpEntity mHttpEntity = mHttpResponse.getEntity();
|
||||
inputStream = mHttpEntity.getContent();
|
||||
bufferedReader = new BufferedReader(
|
||||
new InputStreamReader(inputStream));
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
result += line;
|
||||
}
|
||||
JSONObject json2 = JSONObject.parseObject(result);
|
||||
|
||||
return json2.get("ticket").toString();
|
||||
} catch (IOException e) {
|
||||
throw new IOException("获取jsapi_ticket异常!");
|
||||
}finally {
|
||||
bufferedReader.close();
|
||||
inputStream.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title getPhotoWeixinUrl
|
||||
* @Description 获取微信图片上传路径
|
||||
* @param media_id
|
||||
* @return
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @throws CloneNotSupportedException
|
||||
* @throws IOException
|
||||
* @throws
|
||||
*/
|
||||
public static String getPhotoWeixinUrl(String media_id) throws NoSuchAlgorithmException, IOException, CloneNotSupportedException{
|
||||
String appid = WxPayConstants.APP_ID;
|
||||
String secret = WxPayConstants.SECRET;
|
||||
String token = getToken(appid,secret);
|
||||
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + media_id;
|
||||
return url;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue