mirror of
https://gitee.com/egzosn/pay-java-parent.git
synced 2026-05-31 04:49:54 +08:00
初始版本
This commit is contained in:
409
README.md
409
README.md
@@ -1 +1,410 @@
|
||||
|
||||
#pay-java-parent
|
||||
|
||||
##整合支付模块(微信支付,支付宝)
|
||||
|
||||
|
||||
###特性
|
||||
|
||||
1.支付请求调用支持HTTP和异步
|
||||
2.控制层统一异常处理
|
||||
3.LogBack日志记录
|
||||
4.简单快速完成支付模块的开发
|
||||
5.支持多种支付类型多支付账户扩展(目前已支持微信支付,支付宝支付,友店支付)
|
||||
6.支持http代理
|
||||
|
||||
###使用
|
||||
这里不多说直接上代码 集群的话,友店可能会有bug。
|
||||
|
||||
测试链接 : http://pay.egan.in/index.html
|
||||
|
||||
### 快速入门
|
||||
#####1.支付整合配置
|
||||
```java
|
||||
|
||||
|
||||
/**
|
||||
* 支付类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/20 0:30
|
||||
*/
|
||||
public enum PayType implements BasePayType{
|
||||
aliPay{
|
||||
@Override
|
||||
public PayService getPayService(ApyAccount apyAccount) {
|
||||
AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
|
||||
aliPayConfigStorage.setPartner(apyAccount.getPartner());
|
||||
aliPayConfigStorage.setAliPublicKey(apyAccount.getPublicKey());
|
||||
aliPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey());
|
||||
aliPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl());
|
||||
aliPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl());
|
||||
aliPayConfigStorage.setSignType(apyAccount.getSignType());
|
||||
aliPayConfigStorage.setSeller(apyAccount.getSeller());
|
||||
aliPayConfigStorage.setPayType(apyAccount.getPayType().toString());
|
||||
aliPayConfigStorage.setMsgType(apyAccount.getMsgType());
|
||||
aliPayConfigStorage.setInputCharset(apyAccount.getInputCharset());
|
||||
return new AliPayService(aliPayConfigStorage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransactionType getTransactionType(String transactionType) {
|
||||
return AliTransactionType.valueOf(transactionType);
|
||||
}
|
||||
|
||||
|
||||
},wxPay {
|
||||
@Override
|
||||
public PayService getPayService(ApyAccount apyAccount) {
|
||||
WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
|
||||
wxPayConfigStorage.setMchId(apyAccount.getPartner());
|
||||
wxPayConfigStorage.setAppSecret(apyAccount.getPublicKey());
|
||||
wxPayConfigStorage.setKeyPublic(apyAccount.getPublicKey());
|
||||
wxPayConfigStorage.setAppid(apyAccount.getAppid());
|
||||
wxPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey());
|
||||
wxPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl());
|
||||
wxPayConfigStorage.setSignType(apyAccount.getSignType());
|
||||
wxPayConfigStorage.setPayType(apyAccount.getPayType().toString());
|
||||
wxPayConfigStorage.setMsgType(apyAccount.getMsgType());
|
||||
wxPayConfigStorage.setInputCharset(apyAccount.getInputCharset());
|
||||
return new WxPayService(wxPayConfigStorage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据支付类型获取交易类型
|
||||
* @param transactionType 类型值
|
||||
* @see WxTransactionType
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public TransactionType getTransactionType(String transactionType) {
|
||||
|
||||
return WxTransactionType.valueOf(transactionType);
|
||||
}
|
||||
},youdianPay {
|
||||
@Override
|
||||
public PayService getPayService(ApyAccount apyAccount) {
|
||||
// TODO 2017/1/23 14:12 author: egan 集群的话,友店可能会有bug。暂未测试集群环境
|
||||
WxYouDianPayConfigStorage wxPayConfigStorage = new WxYouDianPayConfigStorage();
|
||||
wxPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey());
|
||||
wxPayConfigStorage.setKeyPublic(apyAccount.getPublicKey());
|
||||
// wxPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl());
|
||||
// wxPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl());
|
||||
wxPayConfigStorage.setSignType(apyAccount.getSignType());
|
||||
wxPayConfigStorage.setPayType(apyAccount.getPayType().toString());
|
||||
wxPayConfigStorage.setMsgType(apyAccount.getMsgType());
|
||||
wxPayConfigStorage.setSeller(apyAccount.getSeller());
|
||||
wxPayConfigStorage.setInputCharset(apyAccount.getInputCharset());
|
||||
return new WxYouDianPayService(wxPayConfigStorage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据支付类型获取交易类型
|
||||
* @param transactionType 类型值
|
||||
* @see YoudianTransactionType
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public TransactionType getTransactionType(String transactionType) {
|
||||
|
||||
return YoudianTransactionType.valueOf(transactionType);
|
||||
}
|
||||
};
|
||||
|
||||
public abstract PayService getPayService(ApyAccount apyAccount);
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付响应对象
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 0:34
|
||||
*/
|
||||
public class PayResponse {
|
||||
@Resource
|
||||
private AutowireCapableBeanFactory spring;
|
||||
|
||||
private PayConfigStorage storage;
|
||||
|
||||
private PayService service;
|
||||
|
||||
private PayMessageRouter router;
|
||||
|
||||
public PayResponse() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化支付配置
|
||||
* @param apyAccount 账户信息
|
||||
* @see ApyAccount 对应表结构详情--》 pay-java-demo/resources/apy_account.sql
|
||||
*/
|
||||
public void init(ApyAccount apyAccount) {
|
||||
|
||||
//根据不同的账户类型 初始化支付配置
|
||||
this.service = apyAccount.getPayType().getPayService(apyAccount);
|
||||
this.storage = service.getPayConfigStorage();
|
||||
|
||||
buildRouter(apyAccount.getPayId());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 配置路由
|
||||
* @param payId 指定账户id,用户多微信支付多支付宝支付
|
||||
*/
|
||||
private void buildRouter(Integer payId) {
|
||||
router = new PayMessageRouter(this.service);
|
||||
router
|
||||
.rule()
|
||||
.async(false)
|
||||
.msgType(MsgType.text.name()) //消息类型
|
||||
.event(PayType.aliPay.name()) //支付账户事件类型
|
||||
.interceptor(new AliPayMessageInterceptor()) //拦截器
|
||||
.handler(autowire(new AliPayMessageHandler(payId))) //处理器
|
||||
.end()
|
||||
.rule()
|
||||
.async(false)
|
||||
.msgType(MsgType.xml.name())
|
||||
.event(PayType.wxPay.name())
|
||||
.handler(autowire(new WxPayMessageHandler(payId)))
|
||||
.end()
|
||||
;
|
||||
}
|
||||
|
||||
|
||||
private PayMessageHandler autowire(PayMessageHandler handler) {
|
||||
spring.autowireBean(handler);
|
||||
return handler;
|
||||
}
|
||||
|
||||
public PayConfigStorage getStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public PayService getService() {
|
||||
return service;
|
||||
}
|
||||
|
||||
public PayMessageRouter getRouter() {
|
||||
return router;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#####2.支付处理器与拦截器简单实现
|
||||
|
||||
```java
|
||||
/**
|
||||
* 微信支付回调处理器
|
||||
* Created by ZaoSheng on 2016/6/1.
|
||||
*/
|
||||
public class WxPayMessageHandler extends BasePayMessageHandler {
|
||||
public WxPayMessageHandler(Integer payId) {
|
||||
super(payId);
|
||||
}
|
||||
@Override
|
||||
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
//交易状态
|
||||
if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))){
|
||||
/////这里进行成功的处理
|
||||
|
||||
return payService.getPayOutMessage("SUCCESS", "OK");
|
||||
}
|
||||
|
||||
return payService.getPayOutMessage("FAIL", "失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付宝回调信息拦截器
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/1/18 19:28
|
||||
*/
|
||||
public class AliPayMessageInterceptor implements PayMessageInterceptor {
|
||||
/**
|
||||
* 拦截支付消息
|
||||
*
|
||||
* @param payMessage 支付回调消息
|
||||
* @param context 上下文,如果handler或interceptor之间有信息要传递,可以用这个
|
||||
* @param payService
|
||||
* @return true代表OK,false代表不OK并直接中断对应的支付处理器
|
||||
* @see PayMessageHandler 支付处理器
|
||||
*/
|
||||
@Override
|
||||
public boolean intercept(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
|
||||
//这里进行拦截器处理,自行实现
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
#####3.支付响应PayResponse的获取
|
||||
|
||||
|
||||
```java
|
||||
|
||||
|
||||
public class ApyAccountService {
|
||||
|
||||
|
||||
@Inject
|
||||
private ApyAccountDao dao;
|
||||
|
||||
@Inject
|
||||
private AutowireCapableBeanFactory spring;
|
||||
|
||||
private final static Map<Integer, PayResponse> payResponses = new HashMap<Integer, PayResponse>();
|
||||
|
||||
|
||||
/**
|
||||
* 获取支付响应
|
||||
* @param id 账户id
|
||||
* @return
|
||||
*/
|
||||
public PayResponse getPayResponse(Integer id) {
|
||||
|
||||
PayResponse payResponse = payResponses.get(id);
|
||||
if (payResponse == null) {
|
||||
ApyAccount apyAccount = dao.get(id);
|
||||
if (apyAccount == null) {
|
||||
throw new IllegalArgumentException ("无法查询");
|
||||
}
|
||||
payResponse = new PayResponse();
|
||||
spring.autowireBean(payResponse);
|
||||
payResponse.init(apyAccount);
|
||||
payResponses.put(id, payResponse);
|
||||
// 查询
|
||||
}
|
||||
return payResponse;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
#####4.根据账户id与业务id,组拼订单信息(支付宝、微信支付订单)获取支付信息所需的数据
|
||||
|
||||
```java
|
||||
|
||||
/**
|
||||
* 跳到支付页面
|
||||
* 针对实时支付,即时付款
|
||||
*
|
||||
* @param payId 账户id
|
||||
* @param transactionType 交易类型, 这个针对于每一个 支付类型的对应的几种交易方式
|
||||
* @param bankType 针对刷卡支付,卡的类型,类型值
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "toPay.html", produces = "text/html;charset=UTF-8")
|
||||
public String toPay( Integer payId, String transactionType, String bankType, BigDecimal price) {
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
|
||||
PayOrder order = new PayOrder("订单title", "摘要", null == price ? new BigDecimal(0.01) : price, UUID.randomUUID().toString().replace("-", ""), PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType));
|
||||
|
||||
//此处只有刷卡支付(银行卡支付)时需要
|
||||
if (StringUtils.isNotEmpty(bankType)){
|
||||
order.setBankType(bankType);
|
||||
}
|
||||
Map orderInfo = payResponse.getService().orderInfo(order);
|
||||
return payResponse.getService().buildRequest(orderInfo, MethodType.POST);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取二维码图像
|
||||
* 二维码支付
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "toQrPay.jpg", produces = "image/jpeg;charset=UTF-8")
|
||||
public byte[] toWxQrPay(Integer payId, String transactionType, BigDecimal price) throws IOException {
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
//获取订单信息
|
||||
Map<String, Object> orderInfo = payResponse.getService().orderInfo(new PayOrder("订单title", "摘要", null == price ? new BigDecimal(0.01) : price, UUID.randomUUID().toString().replace("-", ""), PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType)));
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(payResponse.getService().genQrPay(orderInfo), "JPEG", baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 获取支付预订单信息
|
||||
* @param payId 支付账户id
|
||||
* @param transactionType 交易类型
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("getOrderInfo")
|
||||
public Map<String, Object> getOrderInfo(Integer payId, String transactionType, BigDecimal price){
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("code", 0);
|
||||
PayOrder order = new PayOrder("订单title", "摘要", null == price ? new BigDecimal(0.01) : price, UUID.randomUUID().toString().replace("-", ""), PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType));
|
||||
data.put("orderInfo", payResponse.getService().orderInfo(order));
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
#####5.支付回调
|
||||
```java
|
||||
|
||||
|
||||
/**
|
||||
* 支付回调地址
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "payBack{payId}.json")
|
||||
public String payBack(HttpServletRequest request, @PathVariable Integer payId) throws IOException {
|
||||
//根据账户id,获取对应的支付账户操作工具
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
PayConfigStorage storage = payResponse.getStorage();
|
||||
//获取支付方返回的对应参数
|
||||
Map<String, String> params = payResponse.getService().getParameter2Map(request.getParameterMap(), request.getInputStream());
|
||||
if (null == params){
|
||||
return payResponse.getService().getPayOutMessage("fail","失败").toMessage();
|
||||
}
|
||||
|
||||
//校验
|
||||
if (payResponse.getService().verify(params)){
|
||||
PayMessage message = new PayMessage(params, storage.getPayType(), storage.getMsgType().name());
|
||||
PayOutMessage outMessage = payResponse.getRouter().route(message);
|
||||
return outMessage.toMessage();
|
||||
}
|
||||
|
||||
return payResponse.getService().getPayOutMessage("fail","失败").toMessage();
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
##交流
|
||||
很希望更多志同道合友友一起扩展新的的支付接口。
|
||||
|
||||
非常欢迎和感谢对本项目发起Pull Request的同学,不过本项目基于git flow开发流程,因此在发起Pull Request的时候请选择develop分支。
|
||||
|
||||
E-Mail:egzosn@gmail.com
|
||||
|
||||
QQ群:542193977
|
||||
|
||||
|
||||
26
pay-java-ali/pom.xml
Normal file
26
pay-java-ali/pom.xml
Normal file
@@ -0,0 +1,26 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<artifactId>pay-java-parent</artifactId>
|
||||
<groupId>in.egan</groupId>
|
||||
<version>2.0.SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>pay-java-ali</artifactId>
|
||||
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- pay-java -->
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-common</artifactId>
|
||||
</dependency>
|
||||
<!-- /pay-java -->
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,63 @@
|
||||
package in.egan.pay.ali.api;
|
||||
|
||||
import in.egan.pay.common.api.BasePayConfigStorage;
|
||||
|
||||
/**
|
||||
* 支付客户端配置存储
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class AliPayConfigStorage extends BasePayConfigStorage {
|
||||
|
||||
// 商户PID
|
||||
public volatile String partner ;
|
||||
// 商户收款账号
|
||||
public volatile String seller;
|
||||
//公钥
|
||||
private volatile String aliPublicKey;
|
||||
|
||||
|
||||
public String getAliPublicKey() {
|
||||
return aliPublicKey;
|
||||
}
|
||||
|
||||
public void setAliPublicKey(String aliPublicKey) {
|
||||
setKeyPublic(aliPublicKey);
|
||||
this.aliPublicKey = aliPublicKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSecretKey() {
|
||||
return aliPublicKey;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String getAppid() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPartner() {
|
||||
return partner;
|
||||
}
|
||||
|
||||
|
||||
public void setPartner(String partner) {
|
||||
this.partner = partner;
|
||||
}
|
||||
|
||||
public String getSeller() {
|
||||
return seller;
|
||||
}
|
||||
|
||||
public void setSeller(String seller) {
|
||||
this.seller = seller;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
package in.egan.pay.ali.api;
|
||||
|
||||
import in.egan.pay.ali.bean.AliTransactionType;
|
||||
import in.egan.pay.ali.util.SimpleGetRequestExecutor;
|
||||
import in.egan.pay.common.api.PayConfigStorage;
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.MethodType;
|
||||
import in.egan.pay.common.bean.PayOrder;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.sign.SignUtils;
|
||||
import in.egan.pay.common.util.str.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 支付宝支付通知
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class AliPayService implements PayService {
|
||||
protected final Log log = LogFactory.getLog(AliPayService.class);
|
||||
|
||||
protected PayConfigStorage payConfigStorage;
|
||||
|
||||
protected CloseableHttpClient httpClient;
|
||||
|
||||
protected HttpHost httpProxy;
|
||||
|
||||
private int retrySleepMillis = 1000;
|
||||
|
||||
private int maxRetryTimes = 5;
|
||||
|
||||
private String httpsReqUrl = "https://mapi.alipay.com/gateway.do";
|
||||
|
||||
|
||||
public String getHttpsVerifyUrl() {
|
||||
return httpsReqUrl + "?service=notify_verify";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(Map<String, String> params) {
|
||||
|
||||
|
||||
if (params.get("sign") == null || params.get("notify_id") == null) {
|
||||
log.debug("支付宝支付异常:params:" + params);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return getSignVerify(params, params.get("sign")) && "true".equals(verifyUrl(params.get("notify_id")));
|
||||
} catch (PayErrorException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据反馈回来的信息,生成签名结果
|
||||
* @param params 通知返回来的参数数组
|
||||
* @param sign 比对的签名结果
|
||||
* @return 生成的签名结果
|
||||
*/
|
||||
public boolean getSignVerify(Map<String, String> params, String sign) {
|
||||
|
||||
return SignUtils.valueOf(payConfigStorage.getSignType()).verify(params, sign, payConfigStorage.getKeyPublic(), payConfigStorage.getInputCharset());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String verifyUrl(String notify_id) throws PayErrorException {
|
||||
return execute(new SimpleGetRequestExecutor(), getHttpsVerifyUrl(), "partner=" + payConfigStorage.getPartner() + "¬ify_id=" + notify_id);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 向支付宝端发送请求,在这里执行的策略是当发生access_token过期时才去刷新,然后重新执行请求,而不是全局定时请求
|
||||
*
|
||||
* @param executor
|
||||
* @param uri
|
||||
* @param data
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
@Override
|
||||
public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException {
|
||||
int retryTimes = 0;
|
||||
do {
|
||||
try {
|
||||
return executeInternal(executor, uri, data);
|
||||
} catch (PayErrorException e) {
|
||||
PayError error = e.getError();
|
||||
if (error.getErrorCode() == 404) {
|
||||
int sleepMillis = retrySleepMillis * (1 << retryTimes);
|
||||
try {
|
||||
log.debug(String.format("支付宝系统繁忙,(%s)ms 后重试(第%s次)", sleepMillis, retryTimes + 1));
|
||||
Thread.sleep(sleepMillis);
|
||||
} catch (InterruptedException e1) {
|
||||
throw new RuntimeException(e1);
|
||||
}
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
} while (++retryTimes < maxRetryTimes);
|
||||
|
||||
throw new RuntimeException("支付宝服务端异常,超出重试次数");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 返回创建的订单信息
|
||||
*
|
||||
* @param order 支付订单
|
||||
* @return
|
||||
* @see in.egan.pay.common.bean.PayOrder
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> orderInfo(PayOrder order) {
|
||||
|
||||
Map<String, Object> orderInfo = getOrder(order);
|
||||
|
||||
String sign = createSign( SignUtils.parameterText(orderInfo, "&"), "UTF-8");
|
||||
|
||||
try {
|
||||
sign = URLEncoder.encode(sign, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
orderInfo.put("sign", sign);
|
||||
orderInfo.put("sign_type", payConfigStorage.getSignType());
|
||||
return orderInfo;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 支付宝创建订单信息
|
||||
* create the order info
|
||||
*
|
||||
* @param order 支付订单
|
||||
* @return
|
||||
* @see in.egan.pay.common.bean.PayOrder
|
||||
*/
|
||||
@Deprecated
|
||||
private String getOrderInfo(PayOrder order) {
|
||||
StringBuilder orderInfo = new StringBuilder();
|
||||
// 签约合作者身份ID
|
||||
orderInfo.append( "partner=").append( "\"").append( payConfigStorage.getPartner() ).append("\"");
|
||||
|
||||
// 签约卖家支付宝账号
|
||||
orderInfo.append("&seller_id=" ) .append("\"" ) .append(payConfigStorage.getSeller() ) .append("\"");
|
||||
|
||||
// 商户网站唯一订单号
|
||||
orderInfo.append("&out_trade_no=" ) .append("\"" ).append(order.getTradeNo() ) .append("\"");
|
||||
|
||||
// 商品名称
|
||||
orderInfo.append("&subject=" ) .append("\"" ) .append(order.getSubject() ) .append("\"");
|
||||
|
||||
// 商品详情
|
||||
orderInfo.append("&body=" ) .append("\"" ) .append(order.getBody() ) .append("\"");
|
||||
|
||||
// 商品金额
|
||||
orderInfo.append("&total_fee=" ) .append("\"" ) .append(order.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP) ) .append("\"");
|
||||
|
||||
// 服务器异步通知页面路径
|
||||
orderInfo.append("¬ify_url=" ) .append("\"" ).append( payConfigStorage.getNotifyUrl() ) .append("\"");
|
||||
|
||||
// 服务接口名称, 固定值
|
||||
orderInfo.append("&service=\"" ).append( order.getTransactionType().getType() ).append("\"");
|
||||
|
||||
// 支付类型, 固定值
|
||||
orderInfo.append("&payment_type=\"1\"");
|
||||
|
||||
// 参数编码, 固定值
|
||||
orderInfo.append("&_input_charset=\"utf-8\"");
|
||||
|
||||
// 设置未付款交易的超时时间
|
||||
// 默认30分钟,一旦超时,该笔交易就会自动被关闭。
|
||||
// 取值范围:1m~15d。
|
||||
// m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。
|
||||
// 该参数数值不接受小数点,如1.5h,可转换为90m。
|
||||
orderInfo.append("&it_b_pay=\"30m\"");
|
||||
|
||||
// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
|
||||
// orderInfo.append("&extern_token=" ) .append("\"" ) extern_token ) .append("\"");
|
||||
|
||||
// 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空
|
||||
if (AliTransactionType.APP == order.getTransactionType()){
|
||||
orderInfo.append("&return_url=\"m.alipay.com\"");
|
||||
}
|
||||
|
||||
// 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)
|
||||
// if (order.getTransactionType().getType())
|
||||
// orderInfo.append("&paymethod=\"expressGateway\"");
|
||||
|
||||
return orderInfo.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付宝创建订单信息
|
||||
* create the order info
|
||||
*
|
||||
* @param order 支付订单
|
||||
* @return
|
||||
* @see in.egan.pay.common.bean.PayOrder
|
||||
*/
|
||||
private Map<String, Object> getOrder(PayOrder order) {
|
||||
Map<String, Object> orderInfo = new HashMap<>();
|
||||
// StringBuilder orderInfo = new StringBuilder();
|
||||
// 签约合作者身份ID
|
||||
orderInfo.put("partner", payConfigStorage.getPartner());
|
||||
// orderInfo.append( "partner=").append( "\"").append( payConfigStorage.getPartner() ).append("\"");
|
||||
|
||||
// 签约卖家支付宝账号
|
||||
orderInfo.put("seller_id", payConfigStorage.getSeller());
|
||||
// orderInfo.append("&seller_id=" ) .append("\"" ) .append(payConfigStorage.getSeller() ) .append("\"");
|
||||
|
||||
// 商户网站唯一订单号
|
||||
orderInfo.put("out_trade_no", order.getTradeNo());
|
||||
// orderInfo.append("&out_trade_no=" ) .append("\"" ).append(order.getTradeNo() ) .append("\"");
|
||||
|
||||
// 商品名称
|
||||
orderInfo.put("subject", order.getSubject());
|
||||
// orderInfo.append("&subject=" ) .append("\"" ) .append(order.getSubject() ) .append("\"");
|
||||
|
||||
// 商品详情
|
||||
orderInfo.put("body", order.getBody());
|
||||
// orderInfo.append("&body=" ) .append("\"" ) .append(order.getBody() ) .append("\"");
|
||||
|
||||
// 商品金额
|
||||
orderInfo.put("total_fee", order.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString() );
|
||||
// orderInfo.append("&total_fee=" ) .append("\"" ) .append(order.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP) ) .append("\"");
|
||||
|
||||
// 服务器异步通知页面路径
|
||||
orderInfo.put("notify_url", payConfigStorage.getNotifyUrl() );
|
||||
// orderInfo.append("¬ify_url=" ) .append("\"" ).append( payConfigStorage.getNotifyUrl() ) .append("\"");
|
||||
|
||||
// 服务接口名称, 固定值
|
||||
orderInfo.put("service", order.getTransactionType().getType() );
|
||||
// orderInfo.append("&service=\"" ).append( order.getTransactionType().getType() ).append("\"");
|
||||
|
||||
// 支付类型, 固定值
|
||||
orderInfo.put("payment_type", "1" );
|
||||
// orderInfo.append("&payment_type=\"1\"");
|
||||
|
||||
// 参数编码, 固定值
|
||||
orderInfo.put("_input_charset", payConfigStorage.getInputCharset());
|
||||
// orderInfo.append("&_input_charset=\"utf-8\"");
|
||||
|
||||
// 设置未付款交易的超时时间
|
||||
// 默认30分钟,一旦超时,该笔交易就会自动被关闭。
|
||||
// 取值范围:1m~15d。
|
||||
// m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。
|
||||
// 该参数数值不接受小数点,如1.5h,可转换为90m。
|
||||
// TODO 2017/2/6 11:05 author: egan 目前写死,这一块建议配置
|
||||
orderInfo.put("it_b_pay", "30m");
|
||||
// orderInfo.append("&it_b_pay=\"30m\"");
|
||||
|
||||
// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
|
||||
// orderInfo.append("&extern_token=" ) .append("\"" ) extern_token ) .append("\"");
|
||||
|
||||
// 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空
|
||||
orderInfo.put("return_url", payConfigStorage.getReturnUrl());
|
||||
// orderInfo.append("&return_url=\"m.alipay.com\"");
|
||||
|
||||
// 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)
|
||||
// if (order.getTransactionType().getType())
|
||||
// orderInfo.append("&paymethod=\"expressGateway\"");
|
||||
|
||||
return orderInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createSign(String content, String characterEncoding) {
|
||||
|
||||
return SignUtils.valueOf(payConfigStorage.getSignType()).createSign(content, payConfigStorage.getKeyPrivate(),characterEncoding);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Map<String, String> getParameter2Map(Map<String, String[]> parameterMap, InputStream is) {
|
||||
|
||||
Map<String,String> params = new TreeMap<String,String>();
|
||||
for (Iterator iter = parameterMap.keySet().iterator(); iter.hasNext();) {
|
||||
String name = (String) iter.next();
|
||||
String[] values = parameterMap.get(name);
|
||||
String valueStr = "";
|
||||
for (int i = 0,len = values.length; i < len; i++) {
|
||||
valueStr += (i == len - 1) ? values[i]
|
||||
: values[i] + ",";
|
||||
}
|
||||
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
|
||||
//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
|
||||
params.put(name, valueStr);
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayOutMessage getPayOutMessage(String code, String message) {
|
||||
return PayOutMessage.TEXT().content(code.toLowerCase()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String buildRequest(Map<String, Object> orderInfo, MethodType method) {
|
||||
|
||||
StringBuffer formHtml = new StringBuffer();
|
||||
|
||||
formHtml.append("<form id=\"_alipaysubmit_\" name=\"alipaysubmit\" action=\"" )
|
||||
.append( httpsReqUrl)
|
||||
.append( "?_input_charset=" )
|
||||
.append( payConfigStorage.getInputCharset())
|
||||
.append( "\" method=\"")
|
||||
.append( method.name().toLowerCase()) .append( "\">");
|
||||
|
||||
for (String key: orderInfo.keySet()) {
|
||||
Object o = orderInfo.get(key);
|
||||
if (null == o ||"null".equals(o) || "".equals(o) ){
|
||||
continue;
|
||||
}
|
||||
formHtml.append("<input type=\"hidden\" name=\"" + key + "\" value=\"" + orderInfo.get(key) + "\"/>");
|
||||
}
|
||||
|
||||
|
||||
//submit按钮控件请不要含有name属性
|
||||
// formHtml.append("<input type=\"submit\" value=\"\" style=\"display:none;\">");
|
||||
formHtml.append("</form>");
|
||||
formHtml.append("<script>document.forms['_alipaysubmit_'].submit();</script>");
|
||||
|
||||
return formHtml.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码支付
|
||||
* 暂未实现或无此功能
|
||||
* @param orderInfo 发起支付的订单信息
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public BufferedImage genQrPay(Map<String, Object> orderInfo) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
|
||||
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException {
|
||||
|
||||
try {
|
||||
return executor.execute(getHttpClient(), httpProxy, uri, data);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public HttpHost getHttpProxy() {
|
||||
return httpProxy;
|
||||
}
|
||||
|
||||
public CloseableHttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public void setPayConfigStorage(PayConfigStorage payConfigStorage) {
|
||||
this.payConfigStorage = payConfigStorage;
|
||||
|
||||
String http_proxy_host = payConfigStorage.getHttpProxyHost();
|
||||
int http_proxy_port = payConfigStorage.getHttpProxyPort();
|
||||
String http_proxy_username = payConfigStorage.getHttpProxyUsername();
|
||||
String http_proxy_password = payConfigStorage.getHttpProxyPassword();
|
||||
|
||||
if (StringUtils.isNotBlank(http_proxy_host)) {
|
||||
// 使用代理服务器
|
||||
if (StringUtils.isNotBlank(http_proxy_username)) {
|
||||
// 需要用户认证的代理服务器
|
||||
CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
credsProvider.setCredentials(
|
||||
new AuthScope(http_proxy_host, http_proxy_port),
|
||||
new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
|
||||
httpClient = HttpClients
|
||||
.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider)
|
||||
.build();
|
||||
} else {
|
||||
// 无需用户认证的代理服务器
|
||||
httpClient = HttpClients.createDefault();
|
||||
}
|
||||
httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
|
||||
} else {
|
||||
httpClient = HttpClients.createDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayConfigStorage getPayConfigStorage() {
|
||||
return payConfigStorage;
|
||||
}
|
||||
|
||||
public AliPayService() {
|
||||
}
|
||||
|
||||
public AliPayService(PayConfigStorage payConfigStorage) {
|
||||
setPayConfigStorage(payConfigStorage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package in.egan.pay.ali.bean;
|
||||
|
||||
import in.egan.pay.common.bean.PayCallMessage;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 阿里支付回调消息
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class AliPayCallMessage extends PayCallMessage {
|
||||
|
||||
private Date notify_time;
|
||||
private String notify_type;
|
||||
private String notify_id ;
|
||||
private String subject;
|
||||
private String payment_type;
|
||||
private String trade_no;
|
||||
private String trade_status;
|
||||
private String seller_id;
|
||||
private String seller_email;
|
||||
private String buyer_id;
|
||||
private String buyer_email;
|
||||
private Integer quantity;
|
||||
private BigDecimal price;
|
||||
private String body;
|
||||
private Date gmt_create;
|
||||
private Date gmt_payment;
|
||||
private String is_total_fee_adjust;
|
||||
private String use_coupon;
|
||||
private String discount;
|
||||
private String refund_status;
|
||||
private String gmt_refund;
|
||||
|
||||
public Date getNotify_time() {
|
||||
return notify_time;
|
||||
}
|
||||
|
||||
public void setNotify_time(Date notify_time) {
|
||||
this.notify_time = notify_time;
|
||||
}
|
||||
|
||||
public String getNotify_type() {
|
||||
return notify_type;
|
||||
}
|
||||
|
||||
public void setNotify_type(String notify_type) {
|
||||
this.notify_type = notify_type;
|
||||
}
|
||||
|
||||
public String getNotify_id() {
|
||||
return notify_id;
|
||||
}
|
||||
|
||||
public void setNotify_id(String notify_id) {
|
||||
this.notify_id = notify_id;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getPayment_type() {
|
||||
return payment_type;
|
||||
}
|
||||
|
||||
public void setPayment_type(String payment_type) {
|
||||
this.payment_type = payment_type;
|
||||
}
|
||||
|
||||
public String getTrade_no() {
|
||||
return trade_no;
|
||||
}
|
||||
|
||||
public void setTrade_no(String trade_no) {
|
||||
this.trade_no = trade_no;
|
||||
}
|
||||
|
||||
public String getTrade_status() {
|
||||
return trade_status;
|
||||
}
|
||||
|
||||
public void setTrade_status(String trade_status) {
|
||||
this.trade_status = trade_status;
|
||||
}
|
||||
|
||||
public String getSeller_id() {
|
||||
return seller_id;
|
||||
}
|
||||
|
||||
public void setSeller_id(String seller_id) {
|
||||
this.seller_id = seller_id;
|
||||
}
|
||||
|
||||
public String getSeller_email() {
|
||||
return seller_email;
|
||||
}
|
||||
|
||||
public void setSeller_email(String seller_email) {
|
||||
this.seller_email = seller_email;
|
||||
}
|
||||
|
||||
public String getBuyer_id() {
|
||||
return buyer_id;
|
||||
}
|
||||
|
||||
public void setBuyer_id(String buyer_id) {
|
||||
this.buyer_id = buyer_id;
|
||||
}
|
||||
|
||||
public String getBuyer_email() {
|
||||
return buyer_email;
|
||||
}
|
||||
|
||||
public void setBuyer_email(String buyer_email) {
|
||||
this.buyer_email = buyer_email;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Date getGmt_create() {
|
||||
return gmt_create;
|
||||
}
|
||||
|
||||
public void setGmt_create(Date gmt_create) {
|
||||
this.gmt_create = gmt_create;
|
||||
}
|
||||
|
||||
public Date getGmt_payment() {
|
||||
return gmt_payment;
|
||||
}
|
||||
|
||||
public void setGmt_payment(Date gmt_payment) {
|
||||
this.gmt_payment = gmt_payment;
|
||||
}
|
||||
|
||||
public String getIs_total_fee_adjust() {
|
||||
return is_total_fee_adjust;
|
||||
}
|
||||
|
||||
public void setIs_total_fee_adjust(String is_total_fee_adjust) {
|
||||
this.is_total_fee_adjust = is_total_fee_adjust;
|
||||
}
|
||||
|
||||
public String getUse_coupon() {
|
||||
return use_coupon;
|
||||
}
|
||||
|
||||
public void setUse_coupon(String use_coupon) {
|
||||
this.use_coupon = use_coupon;
|
||||
}
|
||||
|
||||
public String getDiscount() {
|
||||
return discount;
|
||||
}
|
||||
|
||||
public void setDiscount(String discount) {
|
||||
this.discount = discount;
|
||||
}
|
||||
|
||||
public String getRefund_status() {
|
||||
return refund_status;
|
||||
}
|
||||
|
||||
public void setRefund_status(String refund_status) {
|
||||
this.refund_status = refund_status;
|
||||
}
|
||||
|
||||
public String getGmt_refund() {
|
||||
return gmt_refund;
|
||||
}
|
||||
|
||||
public void setGmt_refund(String gmt_refund) {
|
||||
this.gmt_refund = gmt_refund;
|
||||
}
|
||||
|
||||
|
||||
public AliPayCallMessage() {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package in.egan.pay.ali.bean;
|
||||
|
||||
import in.egan.pay.common.bean.TransactionType;
|
||||
|
||||
/**
|
||||
* 阿里交易类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/10/19 22:58
|
||||
*/
|
||||
public enum AliTransactionType implements TransactionType {
|
||||
//即时到帐 //移动支付 //手机网站支付
|
||||
DIRECT("create_direct_pay_by_user"),APP("mobile.securitypay.pay"),WAP("alipay.wap.create.direct.pay.by.user");
|
||||
|
||||
private String type;
|
||||
|
||||
private AliTransactionType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package in.egan.pay.ali.util;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-24
|
||||
*/
|
||||
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.http.Utf8ResponseHandler;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 简单的GET请求执行器,请求的参数是String, 返回的结果也是String
|
||||
* @author Daniel Qian
|
||||
*
|
||||
*/
|
||||
public class SimpleGetRequestExecutor implements RequestExecutor<String, String> {
|
||||
|
||||
@Override
|
||||
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws IOException, PayErrorException {
|
||||
if (queryParam != null) {
|
||||
if (uri.indexOf('?') == -1) {
|
||||
uri += '?';
|
||||
}
|
||||
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
|
||||
}
|
||||
HttpGet httpGet = new HttpGet(uri);
|
||||
if (httpProxy != null) {
|
||||
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
|
||||
httpGet.setConfig(config);
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
|
||||
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
if ("true".equals(responseContent)){ return responseContent; }
|
||||
|
||||
throw new PayErrorException(new PayError(100101, responseContent));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
47
pay-java-common/pom.xml
Normal file
47
pay-java-common/pom.xml
Normal file
@@ -0,0 +1,47 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<artifactId>pay-java-parent</artifactId>
|
||||
<groupId>in.egan</groupId>
|
||||
<version>2.0.SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-common</artifactId>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<!--httpcomponents-->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
</dependency>
|
||||
<!--/httpcomponents-->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jdom</groupId>
|
||||
<artifactId>jdom</artifactId>
|
||||
</dependency>
|
||||
<!-- log4j -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
</dependency>
|
||||
<!-- / log4j -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.zxing</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>3.3.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,223 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
import in.egan.pay.common.bean.MsgType;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
* 支付基础配置存储
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public abstract class BasePayConfigStorage implements PayConfigStorage{
|
||||
|
||||
|
||||
// ali rsa_private 商户私钥,pkcs8格式
|
||||
//wx api_key 商户密钥
|
||||
protected volatile String keyPrivate ;
|
||||
// 支付公钥
|
||||
protected volatile String keyPublic;
|
||||
//异步回调地址
|
||||
protected volatile String notifyUrl;
|
||||
//同步回调地址
|
||||
protected volatile String returnUrl;;
|
||||
//签名加密类型
|
||||
protected volatile String signType;
|
||||
//字符类型
|
||||
protected volatile String inputCharset;
|
||||
|
||||
|
||||
//支付类型 aliPay 支付宝, wxPay微信..等等,开发者自定义,唯一
|
||||
protected volatile String payType;
|
||||
/**
|
||||
* 消息来源类型
|
||||
* @see PayConsts#MSG_XML
|
||||
* @see PayConsts#MSG_TEXT
|
||||
* @see PayConsts#MSG_JSON
|
||||
*/
|
||||
protected volatile MsgType msgType;
|
||||
|
||||
|
||||
// 访问令牌 每次请求其他方法都要传入的值
|
||||
protected volatile String accessToken;
|
||||
// access token 到期时间时间戳
|
||||
protected volatile long expiresTime;
|
||||
//授权码锁
|
||||
protected Lock accessTokenLock = new ReentrantLock();
|
||||
|
||||
|
||||
protected volatile String httpProxyHost;
|
||||
protected volatile int httpProxyPort;
|
||||
protected volatile String httpProxyUsername;
|
||||
protected volatile String httpProxyPassword;
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String getInputCharset() {
|
||||
return inputCharset;
|
||||
}
|
||||
|
||||
public void setInputCharset(String inputCharset) {
|
||||
this.inputCharset = inputCharset;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String getNotifyUrl() {
|
||||
return notifyUrl;
|
||||
}
|
||||
|
||||
public void setNotifyUrl(String notifyUrl) {
|
||||
this.notifyUrl = notifyUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReturnUrl() {
|
||||
return returnUrl;
|
||||
}
|
||||
|
||||
public void setReturnUrl(String returnUrl) {
|
||||
this.returnUrl = returnUrl;
|
||||
}
|
||||
|
||||
public void setSignType(String signType) {
|
||||
this.signType = signType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSignType() {
|
||||
return signType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String getHttpProxyHost() {
|
||||
return httpProxyHost;
|
||||
}
|
||||
|
||||
public void setHttpProxyHost(String httpProxyHost) {
|
||||
this.httpProxyHost = httpProxyHost;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHttpProxyPort() {
|
||||
return httpProxyPort;
|
||||
}
|
||||
|
||||
public void setHttpProxyPort(int httpProxyPort) {
|
||||
this.httpProxyPort = httpProxyPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHttpProxyUsername() {
|
||||
return httpProxyUsername;
|
||||
}
|
||||
|
||||
public void setHttpProxyUsername(String httpProxyUsername) {
|
||||
this.httpProxyUsername = httpProxyUsername;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHttpProxyPassword() {
|
||||
return httpProxyPassword;
|
||||
}
|
||||
|
||||
|
||||
public void setHttpProxyPassword(String httpProxyPassword) {
|
||||
this.httpProxyPassword = httpProxyPassword;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKeyPrivate() {
|
||||
return keyPrivate;
|
||||
}
|
||||
|
||||
public void setKeyPrivate(String keyPrivate) {
|
||||
this.keyPrivate = keyPrivate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKeyPublic() {
|
||||
return keyPublic;
|
||||
}
|
||||
|
||||
public void setKeyPublic(String keyPublic) {
|
||||
this.keyPublic = keyPublic;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 支付类型 自定义
|
||||
* 这里暂定 aliPay 支付宝, wxPay微信支付
|
||||
* @return
|
||||
*/
|
||||
public String getPayType() {
|
||||
return payType;
|
||||
}
|
||||
|
||||
public void setPayType(String payType) {
|
||||
this.payType = payType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MsgType getMsgType() {
|
||||
return msgType;
|
||||
}
|
||||
|
||||
public void setMsgType(MsgType msgType) {
|
||||
this.msgType = msgType;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getAccessToken() {
|
||||
return this.accessToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Lock getAccessTokenLock() {
|
||||
return this.accessTokenLock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getExpiresTime() {
|
||||
return expiresTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccessTokenExpired() {
|
||||
return System.currentTimeMillis() > this.expiresTime;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
|
||||
this.accessToken = accessToken;
|
||||
this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 600) * 1000L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void updateAccessToken(String accessToken, long expiresTime) {
|
||||
this.accessToken = accessToken;
|
||||
this.expiresTime = expiresTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void expireAccessToken() {
|
||||
this.expiresTime = 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original huodull or egan.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.str.StringUtils;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/1/12 20:09
|
||||
*/
|
||||
public abstract class BasePayService implements PayService {
|
||||
|
||||
protected PayConfigStorage payConfigStorage;
|
||||
|
||||
protected CloseableHttpClient httpClient;
|
||||
|
||||
protected HttpHost httpProxy;
|
||||
|
||||
protected int retrySleepMillis = 1000;
|
||||
|
||||
protected int maxRetryTimes = 5;
|
||||
|
||||
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException {
|
||||
|
||||
try {
|
||||
return executor.execute(getHttpClient(), httpProxy, uri, data);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public HttpHost getHttpProxy() {
|
||||
return httpProxy;
|
||||
}
|
||||
|
||||
public CloseableHttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置支付配置
|
||||
* @param payConfigStorage 支付配置
|
||||
*/
|
||||
public void setPayConfigStorage(PayConfigStorage payConfigStorage) {
|
||||
this.payConfigStorage = payConfigStorage;
|
||||
|
||||
String http_proxy_host = payConfigStorage.getHttpProxyHost();
|
||||
int http_proxy_port = payConfigStorage.getHttpProxyPort();
|
||||
String http_proxy_username = payConfigStorage.getHttpProxyUsername();
|
||||
String http_proxy_password = payConfigStorage.getHttpProxyPassword();
|
||||
|
||||
if (StringUtils.isNotBlank(http_proxy_host)) {
|
||||
// 使用代理服务器
|
||||
if (StringUtils.isNotBlank(http_proxy_username)) {
|
||||
// 需要用户认证的代理服务器
|
||||
CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
credsProvider.setCredentials(
|
||||
new AuthScope(http_proxy_host, http_proxy_port),
|
||||
new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
|
||||
httpClient = HttpClients
|
||||
.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider)
|
||||
.build();
|
||||
} else {
|
||||
// 无需用户认证的代理服务器
|
||||
httpClient = HttpClients.createDefault();
|
||||
}
|
||||
httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
|
||||
} else {
|
||||
httpClient = HttpClients.createDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayConfigStorage getPayConfigStorage() {
|
||||
return payConfigStorage;
|
||||
}
|
||||
|
||||
public BasePayService() {
|
||||
}
|
||||
|
||||
|
||||
public BasePayService(PayConfigStorage payConfigStorage) {
|
||||
setPayConfigStorage(payConfigStorage);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
import in.egan.pay.common.bean.MsgType;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
/**
|
||||
* 支付客户端配置存储
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public interface PayConfigStorage {
|
||||
|
||||
/*
|
||||
* 应用id
|
||||
*/
|
||||
String getAppid();
|
||||
/**
|
||||
* 合作商唯一标识
|
||||
*/
|
||||
String getPartner();
|
||||
/**
|
||||
* 获取收款账号
|
||||
*/
|
||||
String getSeller();
|
||||
|
||||
/**
|
||||
* 授权令牌
|
||||
*/
|
||||
String getToken();
|
||||
|
||||
|
||||
/**
|
||||
* 服务端异步回调Url
|
||||
*/
|
||||
String getNotifyUrl();
|
||||
/**
|
||||
* 服务端同步回调Url
|
||||
*/
|
||||
String getReturnUrl();
|
||||
/**
|
||||
* 签名方式
|
||||
*/
|
||||
String getSignType();
|
||||
// 字符编码格式 目前支持 gbk 或 utf-8
|
||||
String getInputCharset();
|
||||
/**
|
||||
* 获取密钥 与 #getKeyPrivate 类似
|
||||
*/
|
||||
String getSecretKey();
|
||||
|
||||
/**
|
||||
* 公钥
|
||||
* @return
|
||||
*/
|
||||
String getKeyPublic();
|
||||
|
||||
/**
|
||||
* 私钥
|
||||
* @return
|
||||
*/
|
||||
String getKeyPrivate();
|
||||
|
||||
/**
|
||||
* 支付类型 自定义
|
||||
* 这里暂定 aliPay 支付宝, wxPay微信支付
|
||||
* @return
|
||||
*/
|
||||
String getPayType();
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
* @see #getMsgType
|
||||
* @see MsgType
|
||||
* @return "text" 或者 "xml"
|
||||
* @see MsgType#text
|
||||
* @see MsgType#xml
|
||||
* @see MsgType#json
|
||||
*/
|
||||
MsgType getMsgType();
|
||||
|
||||
|
||||
/**
|
||||
* 获取访问令牌
|
||||
* @return
|
||||
*/
|
||||
String getAccessToken();
|
||||
|
||||
/**
|
||||
* 访问令牌是否过期
|
||||
* @return
|
||||
*/
|
||||
boolean isAccessTokenExpired();
|
||||
/**
|
||||
* 获取access token锁
|
||||
* @return
|
||||
*/
|
||||
Lock getAccessTokenLock();
|
||||
|
||||
/**
|
||||
* 强制将access token过期掉
|
||||
*/
|
||||
void expireAccessToken();
|
||||
/**
|
||||
* 强制将access token过期掉
|
||||
*/
|
||||
long getExpiresTime();
|
||||
|
||||
/**
|
||||
* 应该是线程安全的
|
||||
* @param accessToken 新的accessToken值
|
||||
* @param expiresInSeconds 过期时间,以秒为单位 多少秒
|
||||
*/
|
||||
void updateAccessToken(String accessToken, int expiresInSeconds);
|
||||
|
||||
/**
|
||||
* 应该是线程安全的
|
||||
* @param accessToken 新的accessToken值
|
||||
* @param expiresTime 过期时间,时间戳
|
||||
*/
|
||||
void updateAccessToken(String accessToken, long expiresTime);
|
||||
|
||||
|
||||
/**
|
||||
* http代理地址
|
||||
* @return
|
||||
*/
|
||||
String getHttpProxyHost();
|
||||
|
||||
/**
|
||||
* 代理端口
|
||||
* @return
|
||||
*/
|
||||
int getHttpProxyPort();
|
||||
|
||||
/**
|
||||
* 代理用户名
|
||||
* @return
|
||||
*/
|
||||
String getHttpProxyUsername();
|
||||
|
||||
/**
|
||||
* 代理密码
|
||||
* @return
|
||||
*/
|
||||
String getHttpProxyPassword();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
/**
|
||||
* 支付宝支付通知
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:45:31
|
||||
*/
|
||||
public class PayConsts {
|
||||
///////////////
|
||||
//支付回复消息类型
|
||||
/////////////
|
||||
public static final String OUT_MSG_TEXT = "text";
|
||||
public static final String OUT_MSG_XML = "xml";
|
||||
public static final String OUT_MSG_JSON = "json";
|
||||
///////////////
|
||||
//支付回调消息类型
|
||||
/////////////
|
||||
public static final String MSG_TEXT = "text";
|
||||
public static final String MSG_XML = "xml";
|
||||
public static final String MSG_JSON = "json";
|
||||
|
||||
///////////////
|
||||
//支付消息事件
|
||||
/////////////
|
||||
// TODO 2017/1/6 17:25 author: egan 移除此处
|
||||
// public static String MSG_ALIPAY = "aliPay";
|
||||
// public static String MSG_WXPAY = "wxPay";
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* PayErrorExceptionHandler处理器
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:33:01
|
||||
*/
|
||||
public interface PayErrorExceptionHandler {
|
||||
|
||||
public void handle(PayErrorException e);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* 处理支付回调消息的处理器接口
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public interface PayMessageHandler {
|
||||
|
||||
/**
|
||||
* @param payMessage
|
||||
* @param context 上下文,如果handler或interceptor之间有信息要传递,可以用这个
|
||||
* @param payService
|
||||
* @return xml,text格式的消息,如果在异步规则里处理的话,可以返回null
|
||||
*/
|
||||
public PayOutMessage handle(PayMessage payMessage,
|
||||
Map<String, Object> context,
|
||||
PayService payService
|
||||
) throws PayErrorException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 支付消息拦截器,可以用来做验证
|
||||
*
|
||||
*/
|
||||
public interface PayMessageInterceptor {
|
||||
|
||||
/**
|
||||
* 拦截微信消息
|
||||
*
|
||||
* @param wxMessage
|
||||
* @param context 上下文,如果handler或interceptor之间有信息要传递,可以用这个
|
||||
* @param payService
|
||||
* @return true代表OK,false代表不OK
|
||||
*/
|
||||
public boolean intercept(PayMessage wxMessage,
|
||||
Map<String, Object> context,
|
||||
PayService payService
|
||||
) throws PayErrorException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.util.LogExceptionHandler;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* 支付消息路由器,通过代码化的配置,把来自支付的消息交给handler处理
|
||||
*
|
||||
* 说明:
|
||||
* 1. 配置路由规则时要按照从细到粗的原则,否则可能消息可能会被提前处理
|
||||
* 2. 默认情况下消息只会被处理一次,除非使用 {@link PayMessageRouterRule#next()}
|
||||
* 3. 规则的结束必须用{@link PayMessageRouterRule#end()}或者{@link PayMessageRouterRule#next()},否则不会生效
|
||||
*
|
||||
* 使用方法:
|
||||
* PayMessageRouter router = new PayMessageRouter();
|
||||
* router
|
||||
* .rule()
|
||||
* .msgType("MSG_TYPE").event("EVENT").eventKey("EVENT_KEY").content("CONTENT")
|
||||
* .interceptor(interceptor, ...).handler(handler, ...)
|
||||
* .end()
|
||||
* .rule()
|
||||
* // 另外一个匹配规则
|
||||
* .end()
|
||||
* ;
|
||||
*
|
||||
* // 将PayMessage交给消息路由器
|
||||
* router.route(message);
|
||||
*
|
||||
* </pre>
|
||||
* @source Daniel Qian
|
||||
* @author egan
|
||||
*
|
||||
*/
|
||||
public class PayMessageRouter {
|
||||
|
||||
protected final Log log = LogFactory.getLog(PayMessageRouter.class);
|
||||
|
||||
private static final int DEFAULT_THREAD_POOL_SIZE = 100;
|
||||
|
||||
private final List<PayMessageRouterRule> rules = new ArrayList<PayMessageRouterRule>();
|
||||
|
||||
private final PayService payService;
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
private PayErrorExceptionHandler exceptionHandler;
|
||||
|
||||
public PayMessageRouter(PayService payService) {
|
||||
this.payService = payService;
|
||||
this.executorService = Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE);
|
||||
this.exceptionHandler = new LogExceptionHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* 设置自定义的 {@link ExecutorService}
|
||||
* 如果不调用该方法,默认使用 Executors.newFixedThreadPool(100)
|
||||
* </pre>
|
||||
* @param executorService
|
||||
*/
|
||||
public void setExecutorService(ExecutorService executorService) {
|
||||
this.executorService = executorService;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* 设置自定义的{@link PayErrorExceptionHandler}
|
||||
* 如果不调用该方法,默认使用 {@link LogExceptionHandler}
|
||||
* </pre>
|
||||
* @param exceptionHandler
|
||||
*/
|
||||
public void setExceptionHandler(PayErrorExceptionHandler exceptionHandler) {
|
||||
this.exceptionHandler = exceptionHandler;
|
||||
}
|
||||
|
||||
List<PayMessageRouterRule> getRules() {
|
||||
return this.rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始一个新的Route规则
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule rule() {
|
||||
return new PayMessageRouterRule(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理支付消息
|
||||
* @param payMessage
|
||||
*/
|
||||
public PayOutMessage route(final PayMessage payMessage) {
|
||||
|
||||
final List<PayMessageRouterRule> matchRules = new ArrayList<PayMessageRouterRule>();
|
||||
// 收集匹配的规则
|
||||
for (final PayMessageRouterRule rule : rules) {
|
||||
if (rule.test(payMessage)) {
|
||||
matchRules.add(rule);
|
||||
if(!rule.isReEnter()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (matchRules.size() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PayOutMessage res = null;
|
||||
final List<Future> futures = new ArrayList<Future>();
|
||||
for (final PayMessageRouterRule rule : matchRules) {
|
||||
// 返回最后一个非异步的rule的执行结果
|
||||
if(rule.isAsync()) {
|
||||
futures.add(
|
||||
executorService.submit(new Runnable() {
|
||||
public void run() {
|
||||
rule.service(payMessage, payService, exceptionHandler);
|
||||
}
|
||||
})
|
||||
);
|
||||
} else {
|
||||
res = rule.service(payMessage, payService, exceptionHandler);
|
||||
// 在同步操作结束,session访问结束
|
||||
log.debug("End session access: async=false, fromPay=" + payMessage.getFromPay());
|
||||
}
|
||||
}
|
||||
|
||||
if (futures.size() > 0) {
|
||||
executorService.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
for (Future future : futures) {
|
||||
try {
|
||||
future.get();
|
||||
log.debug("End session access: async=true, fromPay=" + payMessage.getFromPay());
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
log.error("Error happened when wait task finish", e);
|
||||
} catch (ExecutionException e) {
|
||||
log.error("Error happened when wait task finish", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:28:01
|
||||
*/
|
||||
public class PayMessageRouterRule {
|
||||
|
||||
private final PayMessageRouter routerBuilder;
|
||||
|
||||
private boolean async = true;
|
||||
|
||||
private String fromPay;
|
||||
|
||||
private String msgType;
|
||||
|
||||
private String event;
|
||||
|
||||
private String eventKey;
|
||||
|
||||
private String discount;
|
||||
|
||||
private String rDiscount;
|
||||
|
||||
private String subject;
|
||||
|
||||
private String rSubject;
|
||||
|
||||
|
||||
private boolean reEnter = false;
|
||||
|
||||
private List<PayMessageHandler> handlers = new ArrayList<PayMessageHandler>();
|
||||
|
||||
private List<PayMessageInterceptor> interceptors = new ArrayList<PayMessageInterceptor>();
|
||||
|
||||
public PayMessageRouterRule(PayMessageRouter routerBuilder) {
|
||||
this.routerBuilder = routerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否异步执行,默认是true
|
||||
*
|
||||
* @param async
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule async(boolean async) {
|
||||
this.async = async;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果msgType等于某值
|
||||
*
|
||||
* @param msgType
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule msgType(String msgType) {
|
||||
this.msgType = msgType;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果event等于某值
|
||||
*
|
||||
* @param event
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule event(String event) {
|
||||
this.event = event;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果eventKey等于某值
|
||||
*
|
||||
* @param eventKey
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule eventKey(String eventKey) {
|
||||
this.eventKey = eventKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果discount等于某值
|
||||
*
|
||||
* @param discount
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule discount(String discount) {
|
||||
this.discount = discount;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果discount匹配该正则表达式
|
||||
*
|
||||
* @param regex
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule rDiscount(String regex) {
|
||||
this.rDiscount = regex;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果discount等于某值
|
||||
*
|
||||
* @param subject
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule subject(String subject) {
|
||||
this.subject = subject;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果discount匹配该正则表达式
|
||||
*
|
||||
* @param regex
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule rSubject(String regex) {
|
||||
this.rSubject = regex;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 如果消息匹配某个matcher,用在用户需要自定义更复杂的匹配规则的时候
|
||||
*
|
||||
* @param matcher
|
||||
* @return
|
||||
*/
|
||||
/* public PayMessageRouterRule matcher(WxMpMessageMatcher matcher) {
|
||||
this.matcher = matcher;
|
||||
return this;
|
||||
}*/
|
||||
|
||||
/**
|
||||
* 设置微信消息拦截器
|
||||
*
|
||||
* @param interceptor
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule interceptor(PayMessageInterceptor interceptor) {
|
||||
return interceptor(interceptor, (PayMessageInterceptor[]) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置微信消息拦截器
|
||||
*
|
||||
* @param interceptor
|
||||
* @param otherInterceptors
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule interceptor(PayMessageInterceptor interceptor, PayMessageInterceptor... otherInterceptors) {
|
||||
this.interceptors.add(interceptor);
|
||||
if (otherInterceptors != null && otherInterceptors.length > 0) {
|
||||
for (PayMessageInterceptor i : otherInterceptors) {
|
||||
this.interceptors.add(i);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置微信消息处理器
|
||||
*
|
||||
* @param handler
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule handler(PayMessageHandler handler) {
|
||||
return handler(handler, (PayMessageHandler[]) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置微信消息处理器
|
||||
*
|
||||
* @param handler
|
||||
* @param otherHandlers
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouterRule handler(PayMessageHandler handler, PayMessageHandler... otherHandlers) {
|
||||
this.handlers.add(handler);
|
||||
if (otherHandlers != null && otherHandlers.length > 0) {
|
||||
for (PayMessageHandler i : otherHandlers) {
|
||||
this.handlers.add(i);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则结束,代表如果一个消息匹配该规则,那么它将不再会进入其他规则
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouter end() {
|
||||
this.routerBuilder.getRules().add(this);
|
||||
return this.routerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则结束,但是消息还会进入其他规则
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public PayMessageRouter next() {
|
||||
this.reEnter = true;
|
||||
return end();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将支付事件修正为不区分大小写,
|
||||
* 比如框架定义的事件常量为
|
||||
* @param payMessage
|
||||
* @return
|
||||
*/
|
||||
protected boolean test(PayMessage payMessage) {
|
||||
return (
|
||||
(this.fromPay == null || this.fromPay.toLowerCase().equals((payMessage.getFromPay() ==null?null:payMessage.getFromPay().toLowerCase())))
|
||||
&&
|
||||
(this.msgType == null || this.msgType.toLowerCase().equals((payMessage.getMsgType() ==null?null:payMessage.getMsgType().toLowerCase())))
|
||||
&&
|
||||
(this.event == null || this.event.equals((payMessage.getEvent() == null ? null : payMessage.getEvent())))
|
||||
&&
|
||||
(this.eventKey == null || this.eventKey.toLowerCase().equals((payMessage.getEventKey()==null?null:payMessage.getEventKey().toLowerCase())))
|
||||
&&
|
||||
(this.discount == null || this.discount
|
||||
.equals(payMessage.getDiscount() == null ? null : payMessage.getDiscount().trim()))
|
||||
&&
|
||||
(this.rDiscount == null || Pattern
|
||||
.matches(this.rDiscount, payMessage.getDiscount() == null ? "" : payMessage.getDiscount().trim()))
|
||||
&&
|
||||
(this.subject == null || this.subject
|
||||
.equals(payMessage.getSubject() == null ? null : payMessage.getSubject().trim()))
|
||||
&&
|
||||
(this.rSubject == null || Pattern
|
||||
.matches(this.rSubject, payMessage.getSubject() == null ? "" : payMessage.getSubject().trim()))
|
||||
)
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理支付回调过来的消息
|
||||
*
|
||||
* @param payService
|
||||
* @return true 代表继续执行别的router,false 代表停止执行别的router
|
||||
*/
|
||||
protected PayOutMessage service(PayMessage payMessage,
|
||||
PayService payService,
|
||||
PayErrorExceptionHandler exceptionHandler) {
|
||||
|
||||
try {
|
||||
|
||||
Map<String, Object> context = new HashMap<String, Object>();
|
||||
// 如果拦截器不通过
|
||||
for (PayMessageInterceptor interceptor : this.interceptors) {
|
||||
if (!interceptor.intercept(payMessage, context, payService)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 交给handler处理
|
||||
PayOutMessage res = null;
|
||||
for (PayMessageHandler handler : this.handlers) {
|
||||
// 返回最后handler的结果
|
||||
res = handler.handle(payMessage, context, payService);
|
||||
}
|
||||
return res;
|
||||
} catch (PayErrorException e) {
|
||||
exceptionHandler.handle(e);
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public PayMessageRouter getRouterBuilder() {
|
||||
return routerBuilder;
|
||||
}
|
||||
|
||||
public boolean isAsync() {
|
||||
return async;
|
||||
}
|
||||
|
||||
public void setAsync(boolean async) {
|
||||
this.async = async;
|
||||
}
|
||||
|
||||
public String getFromPay() {
|
||||
return fromPay;
|
||||
}
|
||||
|
||||
public void setFromPay(String fromPay) {
|
||||
this.fromPay = fromPay;
|
||||
}
|
||||
|
||||
public String getMsgType() {
|
||||
return msgType;
|
||||
}
|
||||
|
||||
public void setMsgType(String msgType) {
|
||||
this.msgType = msgType;
|
||||
}
|
||||
|
||||
public String getEvent() {
|
||||
return event;
|
||||
}
|
||||
|
||||
public void setEvent(String event) {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
public String getEventKey() {
|
||||
return eventKey;
|
||||
}
|
||||
|
||||
public void setEventKey(String eventKey) {
|
||||
this.eventKey = eventKey;
|
||||
}
|
||||
|
||||
public String getDiscount() {
|
||||
return discount;
|
||||
}
|
||||
|
||||
public void setDiscount(String discount) {
|
||||
this.discount = discount;
|
||||
}
|
||||
|
||||
public String getrDiscount() {
|
||||
return rDiscount;
|
||||
}
|
||||
|
||||
public void setrDiscount(String rDiscount) {
|
||||
this.rDiscount = rDiscount;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getrSubject() {
|
||||
return rSubject;
|
||||
}
|
||||
|
||||
public void setrSubject(String rSubject) {
|
||||
this.rSubject = rSubject;
|
||||
}
|
||||
|
||||
public boolean isReEnter() {
|
||||
return reEnter;
|
||||
}
|
||||
|
||||
public void setReEnter(boolean reEnter) {
|
||||
this.reEnter = reEnter;
|
||||
}
|
||||
|
||||
public List<PayMessageHandler> getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public void setHandlers(List<PayMessageHandler> handlers) {
|
||||
this.handlers = handlers;
|
||||
}
|
||||
|
||||
public List<PayMessageInterceptor> getInterceptors() {
|
||||
return interceptors;
|
||||
}
|
||||
|
||||
public void setInterceptors(List<PayMessageInterceptor> interceptors) {
|
||||
this.interceptors = interceptors;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
import in.egan.pay.common.bean.MethodType;
|
||||
import in.egan.pay.common.bean.PayOrder;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 支付通知
|
||||
*
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public interface PayService {
|
||||
/**
|
||||
* 回调校验URL
|
||||
* @return
|
||||
*/
|
||||
String getHttpsVerifyUrl();
|
||||
|
||||
/**
|
||||
* 设置支付配置
|
||||
* @param payConfigStorage
|
||||
*/
|
||||
void setPayConfigStorage(PayConfigStorage payConfigStorage);
|
||||
|
||||
/**
|
||||
* 获取支付配置
|
||||
* @return
|
||||
*/
|
||||
PayConfigStorage getPayConfigStorage();
|
||||
|
||||
/**
|
||||
* 回调校验
|
||||
* @param params 回调回来的参数集
|
||||
* @return
|
||||
*/
|
||||
boolean verify(Map<String, String> params);
|
||||
|
||||
/**
|
||||
* 签名校验
|
||||
* @param params 参数集
|
||||
* @param sign 签名
|
||||
* @return
|
||||
*/
|
||||
boolean getSignVerify(Map<String, String> params, String sign);
|
||||
|
||||
/**
|
||||
* URL校验
|
||||
* @param notify_id
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
String verifyUrl(String notify_id) throws PayErrorException;
|
||||
|
||||
/**
|
||||
* 请求接口
|
||||
* @param executor 请求的具体执行者
|
||||
* @param uri 请求地址
|
||||
* @param data 请求数据
|
||||
* @param <T> 返回类型
|
||||
* @param <E> 请求数据类型
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
<T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException;
|
||||
|
||||
/**
|
||||
* 返回创建的订单信息
|
||||
*
|
||||
* @param order 支付订单
|
||||
* @return
|
||||
* @see in.egan.pay.common.bean.PayOrder
|
||||
*/
|
||||
Map orderInfo(PayOrder order);
|
||||
|
||||
/**
|
||||
* 创建签名
|
||||
*
|
||||
* @param content 需要签名的内容
|
||||
* @param characterEncoding 字符编码
|
||||
* @return
|
||||
*/
|
||||
String createSign(String content, String characterEncoding);
|
||||
|
||||
/**
|
||||
* 将请求参数或者请求流转化为 Map
|
||||
*
|
||||
* @param parameterMap 请求参数
|
||||
* @param is 请求流
|
||||
* @return
|
||||
*/
|
||||
Map<String, String> getParameter2Map(Map<String, String[]> parameterMap, InputStream is);
|
||||
|
||||
/**
|
||||
* 获取输出消息,用户返回给支付端
|
||||
* @param code
|
||||
* @param message
|
||||
* @return
|
||||
*/
|
||||
PayOutMessage getPayOutMessage(String code, String message);
|
||||
|
||||
/**
|
||||
* 获取输出消息,用户返回给支付端, 针对于web端
|
||||
* @param orderInfo 发起支付的订单信息
|
||||
* @param method 请求方式 "post" "get",
|
||||
* @see in.egan.pay.common.bean.MethodType
|
||||
* @return
|
||||
*/
|
||||
String buildRequest(Map<String, Object> orderInfo, MethodType method);
|
||||
|
||||
/**
|
||||
* 获取输出二维码,用户返回给支付端,
|
||||
* @param orderInfo 发起支付的订单信息
|
||||
* @return
|
||||
*/
|
||||
BufferedImage genQrPay(Map<String, Object> orderInfo);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package in.egan.pay.common.api;
|
||||
|
||||
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* http请求执行器
|
||||
*
|
||||
* @param <T> 返回值类型
|
||||
* @param <E> 请求参数类型
|
||||
*/
|
||||
public interface RequestExecutor<T, E> {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param httpclient 传入的httpClient
|
||||
* @param httpProxy http代理对象,如果没有配置代理则为空
|
||||
* @param uri uri
|
||||
* @param data 数据
|
||||
* @return
|
||||
* @throws ClientProtocolException
|
||||
* @throws java.io.IOException
|
||||
*/
|
||||
public T execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, E data) throws PayErrorException, ClientProtocolException,IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
/**
|
||||
* 基础的支付类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/20 0:47
|
||||
*/
|
||||
public interface BasePayType {
|
||||
|
||||
|
||||
/**
|
||||
* 根据支付类型获取交易类型
|
||||
* @param transactionType 类型值
|
||||
* @return
|
||||
*/
|
||||
public abstract TransactionType getTransactionType(String transactionType);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package in.egan.pay.common.bean;/**
|
||||
* Created by Fuzx on 2017/1/24 0024.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @author Fuzx 货币类型
|
||||
* @create 2017 2017/1/24 0024
|
||||
*/
|
||||
public interface CurType {
|
||||
String getCurType();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original huodull or egan.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
/**
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/2/7 9:52
|
||||
*/
|
||||
public enum MethodType {
|
||||
GET, POST
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original huodull or egan.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 0:59
|
||||
*/
|
||||
public enum MsgType {
|
||||
text, xml,json
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 支付回调消息
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class PayCallMessage {
|
||||
private Boolean sign;
|
||||
private String sign_type;
|
||||
private String out_trade_no;
|
||||
private BigDecimal total_fee;
|
||||
|
||||
public Boolean getSign() {
|
||||
return sign;
|
||||
}
|
||||
|
||||
public void setSign(Boolean sign) {
|
||||
this.sign = sign;
|
||||
}
|
||||
|
||||
public String getSign_type() {
|
||||
return sign_type;
|
||||
}
|
||||
|
||||
public void setSign_type(String sign_type) {
|
||||
this.sign_type = sign_type;
|
||||
}
|
||||
|
||||
public String getOut_trade_no() {
|
||||
return out_trade_no;
|
||||
}
|
||||
|
||||
public void setOut_trade_no(String out_trade_no) {
|
||||
this.out_trade_no = out_trade_no;
|
||||
}
|
||||
|
||||
public BigDecimal getTotal_fee() {
|
||||
return total_fee;
|
||||
}
|
||||
|
||||
public void setTotal_fee(BigDecimal total_fee) {
|
||||
this.total_fee = total_fee;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
import in.egan.pay.common.api.PayConsts;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 支付回调消息
|
||||
* 基础实现,具体可根据具体支付回调的消息去实现
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 14:2:3
|
||||
*/
|
||||
public class PayMessage implements Serializable {
|
||||
private Map<String, String> payMessage = null;
|
||||
private String msgType;
|
||||
private String event;
|
||||
private String eventKey;
|
||||
private String fromPay;
|
||||
private String describe;
|
||||
|
||||
public PayMessage(Map<String, String> payMessage) {
|
||||
this.payMessage = payMessage;
|
||||
}
|
||||
|
||||
public PayMessage(Map<String, String> payMessage, String event, String msgType) {
|
||||
this(payMessage);
|
||||
this.event = event;
|
||||
this.msgType = msgType;
|
||||
}
|
||||
|
||||
public String getMsgType() {
|
||||
return msgType;
|
||||
}
|
||||
|
||||
public void setMsgType(String msgType) {
|
||||
this.msgType = msgType;
|
||||
}
|
||||
|
||||
public String getEvent() {
|
||||
return event;
|
||||
}
|
||||
|
||||
public void setEvent(String event) {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
public String getEventKey() {
|
||||
return eventKey;
|
||||
}
|
||||
|
||||
public void setEventKey(String eventKey) {
|
||||
this.eventKey = eventKey;
|
||||
}
|
||||
|
||||
public String getFromPay() {
|
||||
return fromPay;
|
||||
}
|
||||
|
||||
public void setFromPay(String fromPay) {
|
||||
this.fromPay = fromPay;
|
||||
}
|
||||
|
||||
public String getDescribe() {
|
||||
return describe;
|
||||
}
|
||||
|
||||
public void setDescribe(String describe) {
|
||||
this.describe = describe;
|
||||
}
|
||||
public String getDiscount(){
|
||||
return payMessage.get("discount");
|
||||
}
|
||||
public String getSubject(){
|
||||
return payMessage.get("subject");
|
||||
}
|
||||
//////////////////支付宝
|
||||
/* public Date getNotifyTime(){
|
||||
return parseDate(payMessage.get("notify_time"));
|
||||
}
|
||||
|
||||
public String getNotifyType(){
|
||||
return payMessage.get("notify_type");
|
||||
}
|
||||
public String getNotifyId(){
|
||||
return payMessage.get("notify_id");
|
||||
}
|
||||
|
||||
public String getSignType(){
|
||||
return payMessage.get("sign_type");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public String getPaymentType(){
|
||||
return payMessage.get("payment_type");
|
||||
}
|
||||
|
||||
public String getTradeNo(){
|
||||
return payMessage.get("trade_no");
|
||||
}
|
||||
|
||||
public String getTradeStatus(){
|
||||
return payMessage.get("trade_status");
|
||||
}
|
||||
public String getSellerId(){
|
||||
return payMessage.get("seller_id");
|
||||
}
|
||||
public String getSellerEmail(){
|
||||
return payMessage.get("seller_email");
|
||||
}
|
||||
public String getBuyerId(){
|
||||
return payMessage.get("buyer_id");
|
||||
}
|
||||
|
||||
public String getBuyerEmail(){
|
||||
return payMessage.get("buyer_email");
|
||||
}
|
||||
|
||||
|
||||
public Number getQuantity(){
|
||||
String quantity = payMessage.get("quantity");
|
||||
if (null == quantity || "".equals(quantity)){ return 1; }
|
||||
if (isNumber(quantity)){
|
||||
return Integer.parseInt(quantity);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
public Number getPrice(){
|
||||
String price = payMessage.get("price");
|
||||
if (null == price || "".equals(price)){ return 1; }
|
||||
if (isNumber(price)){
|
||||
return new BigDecimal(price);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
public String getBody(){
|
||||
return payMessage.get("body");
|
||||
}
|
||||
|
||||
public Date getGmtCreate(){
|
||||
|
||||
return parseDate(payMessage.get("gmt_create"));
|
||||
}
|
||||
|
||||
public Date getGmtPayment(){
|
||||
|
||||
return parseDate(payMessage.get("gmt_payment"));
|
||||
}
|
||||
public String getIsTotalFeeAdjust (){
|
||||
return payMessage.get("is_total_fee_adjust");
|
||||
|
||||
}
|
||||
|
||||
|
||||
public String getUseCoupon(){
|
||||
return payMessage.get("use_coupon");
|
||||
|
||||
}
|
||||
|
||||
public String getRefundStatus(){
|
||||
return payMessage.get("refund_status");
|
||||
|
||||
}
|
||||
public Date getGmtRefund(){
|
||||
return parseDate(payMessage.get("gmt_refund"));
|
||||
|
||||
}*/
|
||||
/////////////////支付宝
|
||||
|
||||
|
||||
|
||||
//////////////////微信
|
||||
/* public String getIsSubscribe(){
|
||||
return payMessage.get("is_subscribe");
|
||||
}
|
||||
public String getAppid(){
|
||||
return payMessage.get("appid");
|
||||
}
|
||||
|
||||
public String getFeeType(){
|
||||
return payMessage.get("fee_type");
|
||||
}
|
||||
public String getNonceStr(){
|
||||
return payMessage.get("nonce_str");
|
||||
}
|
||||
public String getTransactionId(){
|
||||
return payMessage.get("transaction_id");
|
||||
}
|
||||
|
||||
public String getTradeType(){
|
||||
return payMessage.get("trade_type");
|
||||
}
|
||||
|
||||
public String getResultCode(){
|
||||
return payMessage.get("result_code");
|
||||
}
|
||||
|
||||
public String getMchId(){
|
||||
return payMessage.get("mch_id");
|
||||
}
|
||||
|
||||
public String getAttach(){
|
||||
return payMessage.get("attach");
|
||||
}
|
||||
|
||||
public String getTimeEnd(){
|
||||
return payMessage.get("time_end");
|
||||
}
|
||||
public String getBankType(){
|
||||
return payMessage.get("bank_type");
|
||||
}
|
||||
public String getOpenid(){
|
||||
return payMessage.get("openid");
|
||||
}
|
||||
public String getReturnCode(){
|
||||
return payMessage.get("return_code");
|
||||
}
|
||||
public Number getCashFee(){
|
||||
String cashFee = payMessage.get("cash_fee");
|
||||
if (null == cashFee || "".equals(cashFee)){ return 0; }
|
||||
if (isNumber(cashFee)){
|
||||
return new BigDecimal(cashFee).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
|
||||
}
|
||||
return 0;
|
||||
}*/
|
||||
//////////////////微信
|
||||
|
||||
|
||||
|
||||
/////////微信与支付宝共用
|
||||
public String getOutTradeNo(){
|
||||
return payMessage.get("out_trade_no");
|
||||
}
|
||||
|
||||
public String getSign(){
|
||||
return payMessage.get("sign");
|
||||
}
|
||||
|
||||
public Number getTotalFee(){
|
||||
String total_fee = payMessage.get("total_fee");
|
||||
if (null == total_fee || "".equals(total_fee)){ return 0; }
|
||||
if (isNumber(total_fee)){
|
||||
BigDecimal totalFee = new BigDecimal(total_fee);
|
||||
return totalFee;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/////////微信与支付宝共用
|
||||
|
||||
|
||||
|
||||
public boolean isNumber(String str){
|
||||
return str.matches("^(-?[1-9]\\d*\\.?\\d*)|(-?0\\.\\d*[1-9])|(-?[0])|(-?[0]\\.\\d*)$");
|
||||
}
|
||||
|
||||
public Date parseDate(String str){
|
||||
|
||||
if (null == str || "".equals(str)){
|
||||
return null;
|
||||
}
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
try {
|
||||
return format.parse(str);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return payMessage.toString();
|
||||
}
|
||||
|
||||
public Map<String, String> getPayMessage() {
|
||||
return payMessage;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 支付订单信息
|
||||
*
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/10/19 22:34
|
||||
*/
|
||||
public class PayOrder {
|
||||
//商品名称
|
||||
private String subject;
|
||||
//商品描述
|
||||
private String body;
|
||||
//价格
|
||||
private BigDecimal price;
|
||||
//商户单号
|
||||
private String tradeNo;
|
||||
//银行卡类型
|
||||
private String bankType;
|
||||
//设备号
|
||||
private String deviceInfo;
|
||||
//交易类型
|
||||
private TransactionType transactionType;
|
||||
//支付币种
|
||||
private CurType curType;
|
||||
|
||||
|
||||
public CurType getCurType() {
|
||||
return curType;
|
||||
}
|
||||
|
||||
public void setCurType(CurType curType) {
|
||||
this.curType = curType;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getTradeNo() {
|
||||
return tradeNo;
|
||||
}
|
||||
|
||||
public void setTradeNo(String tradeNo) {
|
||||
this.tradeNo = tradeNo;
|
||||
}
|
||||
|
||||
public TransactionType getTransactionType() {
|
||||
return transactionType;
|
||||
}
|
||||
|
||||
public void setTransactionType(TransactionType transactionType) {
|
||||
this.transactionType = transactionType;
|
||||
}
|
||||
|
||||
public String getBankType() {
|
||||
return bankType;
|
||||
}
|
||||
|
||||
public void setBankType(String bankType) {
|
||||
this.bankType = bankType;
|
||||
}
|
||||
|
||||
public String getDeviceInfo() {
|
||||
return deviceInfo;
|
||||
}
|
||||
|
||||
public void setDeviceInfo(String deviceInfo) {
|
||||
this.deviceInfo = deviceInfo;
|
||||
}
|
||||
|
||||
public PayOrder() {
|
||||
}
|
||||
|
||||
|
||||
public PayOrder(String subject, String body, BigDecimal price, String tradeNo, TransactionType transactionType) {
|
||||
|
||||
this.subject = subject;
|
||||
this.body = body;
|
||||
this.price = price;
|
||||
this.tradeNo = tradeNo;
|
||||
this.transactionType = transactionType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import in.egan.pay.common.bean.outbuilder.JsonBuilder;
|
||||
import in.egan.pay.common.bean.outbuilder.TextBuilder;
|
||||
import in.egan.pay.common.bean.outbuilder.XmlBuilder;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 支付回调通知返回消息
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public abstract class PayOutMessage implements Serializable {
|
||||
protected String content;
|
||||
protected String msgType;
|
||||
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public String getMsgType() {
|
||||
return msgType;
|
||||
}
|
||||
|
||||
public void setMsgType(String msgType) {
|
||||
this.msgType = msgType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得文本消息builder
|
||||
* @return
|
||||
*/
|
||||
public static TextBuilder TEXT() {
|
||||
return new TextBuilder();
|
||||
}
|
||||
/**
|
||||
* 获得XML消息builder
|
||||
* @return
|
||||
*/
|
||||
public static XmlBuilder XML() {
|
||||
return new XmlBuilder();
|
||||
}
|
||||
/**
|
||||
* 获得Json消息builder
|
||||
* @return
|
||||
*/
|
||||
public static JsonBuilder JSON() {
|
||||
return new JsonBuilder(new JSONObject());
|
||||
}
|
||||
public abstract String toMessage();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package in.egan.pay.common.bean;
|
||||
|
||||
/**
|
||||
* 交易类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/10/19 22:30
|
||||
*/
|
||||
public interface TransactionType {
|
||||
/**
|
||||
* 获取交易类型
|
||||
* @return
|
||||
*/
|
||||
String getType();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public abstract class BaseBuilder<BuilderType, ValueType> {
|
||||
|
||||
|
||||
public abstract ValueType build();
|
||||
|
||||
public void setCommon(PayOutMessage m) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original huodull or egan.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
|
||||
/**
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/1/13 14:30
|
||||
*/
|
||||
public class JsonBuilder extends BaseBuilder<TextBuilder, PayOutMessage>{
|
||||
JSONObject json = null;
|
||||
|
||||
public JsonBuilder(JSONObject json) {
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public JsonBuilder content(String key, Object content) {
|
||||
this.json.put(key, content);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject getJson() {
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayOutMessage build() {
|
||||
PayJsonOutMessage message = new PayJsonOutMessage();
|
||||
setCommon(message);
|
||||
message.setContent(json.toJSONString());
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import in.egan.pay.common.api.PayConsts;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public class PayJsonOutMessage extends PayOutMessage{
|
||||
|
||||
public PayJsonOutMessage() {
|
||||
this.msgType = PayConsts.OUT_MSG_JSON;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toMessage() {
|
||||
return getContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import in.egan.pay.common.api.PayConsts;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public class PayTextOutMessage extends PayOutMessage{
|
||||
|
||||
public PayTextOutMessage() {
|
||||
this.msgType = PayConsts.OUT_MSG_TEXT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toMessage() {
|
||||
return getContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import in.egan.pay.common.api.PayConsts;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 13:53:3
|
||||
*/
|
||||
public class PayXmlOutMessage extends PayOutMessage{
|
||||
|
||||
private String code;
|
||||
|
||||
public PayXmlOutMessage() {
|
||||
this.msgType = PayConsts.OUT_MSG_XML;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toMessage() {
|
||||
return "<xml><return_code><![CDATA[" + code + "]]></return_code><return_msg><![CDATA[" + content
|
||||
+ "]]></return_msg></xml>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public class TextBuilder extends BaseBuilder<TextBuilder, PayOutMessage> {
|
||||
private String content;
|
||||
|
||||
public TextBuilder content(String content) {
|
||||
this.content = content;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayOutMessage build() {
|
||||
PayTextOutMessage message = new PayTextOutMessage();
|
||||
setCommon(message);
|
||||
message.setContent(content);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package in.egan.pay.common.bean.outbuilder;
|
||||
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:40:30
|
||||
*/
|
||||
public class XmlBuilder extends BaseBuilder<XmlBuilder, PayOutMessage> {
|
||||
private String content;
|
||||
private String code;
|
||||
public XmlBuilder content(String content) {
|
||||
this.content = content;
|
||||
return this;
|
||||
}
|
||||
|
||||
public XmlBuilder code(String code) {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public PayOutMessage build() {
|
||||
PayXmlOutMessage message = new PayXmlOutMessage();
|
||||
setCommon(message);
|
||||
message.setContent(content);
|
||||
message.setCode(code);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package in.egan.pay.common.bean.result;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import in.egan.pay.common.util.XML;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 支付错误码说明
|
||||
* @author Daniel Qian
|
||||
* @dete 2017/1/12 9:57
|
||||
* @author: egan
|
||||
*/
|
||||
|
||||
public class PayError implements Serializable {
|
||||
|
||||
private int errorCode;
|
||||
|
||||
private String errorMsg;
|
||||
|
||||
private JSONObject json;
|
||||
private String responseContent;
|
||||
|
||||
public PayError() {
|
||||
}
|
||||
public PayError(int errorCode, String errorMsg) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
|
||||
public PayError(int errorCode, String errorMsg, String responseContent) {
|
||||
this(errorCode, errorMsg);
|
||||
this.responseContent = responseContent;
|
||||
}
|
||||
|
||||
|
||||
public int getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public void setErrorCode(int errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
public JSONObject getJson() {
|
||||
return json;
|
||||
}
|
||||
|
||||
public void setJson(JSONObject json) {
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public String getResponseContent() {
|
||||
return responseContent;
|
||||
}
|
||||
|
||||
public void setResponseContent(String responseContent) {
|
||||
this.responseContent = responseContent;
|
||||
}
|
||||
|
||||
public static PayError fromJson(String json) {
|
||||
|
||||
JSONObject jsonObject = JSON.parseObject(json);
|
||||
PayError error = jsonObject.toJavaObject(PayError.class);
|
||||
error.setJson(jsonObject);
|
||||
error.setResponseContent(json);
|
||||
return error;
|
||||
}
|
||||
|
||||
public static PayError fromXml(String xml) {
|
||||
JSONObject jsonObject = XML.toJSONObject(xml);
|
||||
if (null == jsonObject.get("return_code")){
|
||||
PayError error = new PayError(403, null == jsonObject.get("return_msg") ? "未知错误!" : jsonObject.get("return_msg").toString());
|
||||
return error;
|
||||
}
|
||||
|
||||
if ("FAIL".equals( jsonObject.get("return_code"))){
|
||||
PayError error = new PayError(-1, jsonObject.get("return_msg").toString());
|
||||
return error;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "支付错误: errcode=" + errorCode + ", errmsg=" + errorMsg + "\njson:" + json;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package in.egan.pay.common.exception;
|
||||
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class PayErrorException extends Exception {
|
||||
|
||||
private PayError error;
|
||||
|
||||
public PayErrorException(PayError error) {
|
||||
super(error.toString());
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public PayError getError() {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package in.egan.pay.common.util;
|
||||
|
||||
import in.egan.pay.common.api.PayErrorExceptionHandler;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* LogExceptionHandler 日志处理器
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-1 11:28:01
|
||||
*/
|
||||
public class LogExceptionHandler implements PayErrorExceptionHandler {
|
||||
|
||||
protected final Log log = LogFactory.getLog(PayErrorExceptionHandler.class);
|
||||
|
||||
@Override
|
||||
public void handle(PayErrorException e) {
|
||||
|
||||
log.error("Error happens", e);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package in.egan.pay.common.util;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.MultiFormatWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成工具
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/2/7 10:35
|
||||
*/
|
||||
public class MatrixToImageWriter {
|
||||
|
||||
|
||||
private static final int BLACK = 0xFF000000;
|
||||
private static final int WHITE = 0xFFFFFFFF;
|
||||
|
||||
private MatrixToImageWriter() {}
|
||||
|
||||
/**
|
||||
* 根据二维矩阵的碎片 生成对应的二维码图像缓冲
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @see com.google.zxing.common.BitMatrix
|
||||
* @return
|
||||
*/
|
||||
public static BufferedImage toBufferedImage(BitMatrix matrix) {
|
||||
int width = matrix.getWidth();
|
||||
int height = matrix.getHeight();
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成文件
|
||||
* @param matrix
|
||||
* @param format
|
||||
* @param file
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void writeToFile(BitMatrix matrix, String format, File file)
|
||||
throws IOException {
|
||||
BufferedImage image = toBufferedImage(matrix);
|
||||
if (!ImageIO.write(image, format, file)) {
|
||||
throw new IOException("Could not write an image of format " + format + " to " + file);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成流
|
||||
* @param matrix
|
||||
* @param format
|
||||
* @param stream
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
|
||||
throws IOException {
|
||||
BufferedImage image = toBufferedImage(matrix);
|
||||
if (!ImageIO.write(image, format, stream)) {
|
||||
throw new IOException("Could not write an image of format " + format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码信息写成JPG文件
|
||||
* @param content
|
||||
* @param fileUrl
|
||||
*/
|
||||
public static void writeInfoToJpgFile(String content, String fileUrl){
|
||||
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
|
||||
Map hints = new HashMap();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
try {
|
||||
BitMatrix bitMatrix = multiFormatWriter.encode(content,
|
||||
BarcodeFormat.QR_CODE, 250, 250, hints);
|
||||
File file1 = new File(fileUrl);
|
||||
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码信息写成JPG BufferedImage
|
||||
* @param content
|
||||
* @return
|
||||
*/
|
||||
public static BufferedImage writeInfoToJpgBuff(String content){
|
||||
BufferedImage re=null;
|
||||
|
||||
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
|
||||
Map hints = new HashMap();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
try {
|
||||
BitMatrix bitMatrix = multiFormatWriter.encode(content,
|
||||
BarcodeFormat.QR_CODE, 250, 250, hints);
|
||||
re=MatrixToImageWriter.toBufferedImage(bitMatrix);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
146
pay-java-common/src/main/java/in/egan/pay/common/util/XML.java
Normal file
146
pay-java-common/src/main/java/in/egan/pay/common/util/XML.java
Normal file
@@ -0,0 +1,146 @@
|
||||
package in.egan.pay.common.util;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.jdom2.Document;
|
||||
import org.jdom2.Element;
|
||||
import org.jdom2.JDOMException;
|
||||
import org.jdom2.input.SAXBuilder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.SortedMap;
|
||||
|
||||
|
||||
/**
|
||||
* XML工具
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-6-2 19:45:06
|
||||
*/
|
||||
public class XML {
|
||||
/**
|
||||
* 解析xml并转化为Json值
|
||||
* @param content json字符串
|
||||
* @return
|
||||
*/
|
||||
public static JSONObject toJSONObject(String content){
|
||||
|
||||
if (null == content || "".equals(content)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))){
|
||||
return (JSONObject) inputStream2Map(in, null);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析xml并转化为json值
|
||||
* @param in 输入流
|
||||
* @return
|
||||
*/
|
||||
public static JSONObject toJSONObject(InputStream in) {
|
||||
|
||||
if (null == in) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return (JSONObject)inputStream2Map(in, null);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static Map inputStream2Map(InputStream in, Map m) throws IOException {
|
||||
if (null == m){
|
||||
m = new JSONObject();
|
||||
}
|
||||
SAXBuilder builder = new SAXBuilder();
|
||||
try {
|
||||
Document doc = builder.build(in);
|
||||
Element root = doc.getRootElement();
|
||||
List list = root.getChildren();
|
||||
Iterator it = list.iterator();
|
||||
while (it.hasNext()) {
|
||||
Element e = (Element) it.next();
|
||||
String k = e.getName();
|
||||
String v = "";
|
||||
List children = e.getChildren();
|
||||
if (children.isEmpty()) {
|
||||
v = e.getTextNormalize();
|
||||
} else {
|
||||
v = getChildrenText(children);
|
||||
}
|
||||
m.put(k, v);
|
||||
}
|
||||
} catch (JDOMException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获取子结点的xml
|
||||
*
|
||||
* @param children
|
||||
* @return String
|
||||
*/
|
||||
public static String getChildrenText(List children) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (!children.isEmpty()) {
|
||||
Iterator it = children.iterator();
|
||||
while (it.hasNext()) {
|
||||
Element e = (Element) it.next();
|
||||
String name = e.getName();
|
||||
String value = e.getTextNormalize();
|
||||
List list = e.getChildren();
|
||||
sb.append("<" + name + ">");
|
||||
if (!list.isEmpty()) {
|
||||
sb.append(getChildrenText(list));
|
||||
}
|
||||
sb.append(value);
|
||||
sb.append("</" + name + ">");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description:将请求参数转换为xml格式的string
|
||||
* @param parameters 请求参数
|
||||
* @return
|
||||
*/
|
||||
public static String getMap2Xml(Map<String, Object> parameters) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("<xml>");
|
||||
for (String key : parameters.keySet()){
|
||||
if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "attach".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
|
||||
sb.append("<" + key + ">" + "<![CDATA[" + parameters.get(key) + "]]></" + key + ">");
|
||||
} else {
|
||||
sb.append("<" + key + ">" + parameters.get(key) + "</" + key + ">");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
sb.append("</xml>");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* Copyright (C) 2010 The MobileSecurePay Project
|
||||
* All right reserved.
|
||||
* author: shiqun.shi@alipay.com
|
||||
*/
|
||||
|
||||
package in.egan.pay.common.util.encrypt;
|
||||
|
||||
public final class Base64 {
|
||||
|
||||
static private final int BASELENGTH = 128;
|
||||
static private final int LOOKUPLENGTH = 64;
|
||||
static private final int TWENTYFOURBITGROUP = 24;
|
||||
static private final int EIGHTBIT = 8;
|
||||
static private final int SIXTEENBIT = 16;
|
||||
static private final int FOURBYTE = 4;
|
||||
static private final int SIGN = -128;
|
||||
static private final char PAD = '=';
|
||||
static private final boolean fDebug = false;
|
||||
static final private byte[] base64Alphabet = new byte[BASELENGTH];
|
||||
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
|
||||
|
||||
static {
|
||||
for (int i = 0; i < BASELENGTH; ++i) {
|
||||
base64Alphabet[i] = -1;
|
||||
}
|
||||
for (int i = 'Z'; i >= 'A'; i--) {
|
||||
base64Alphabet[i] = (byte) (i - 'A');
|
||||
}
|
||||
for (int i = 'z'; i >= 'a'; i--) {
|
||||
base64Alphabet[i] = (byte) (i - 'a' + 26);
|
||||
}
|
||||
|
||||
for (int i = '9'; i >= '0'; i--) {
|
||||
base64Alphabet[i] = (byte) (i - '0' + 52);
|
||||
}
|
||||
|
||||
base64Alphabet['+'] = 62;
|
||||
base64Alphabet['/'] = 63;
|
||||
|
||||
for (int i = 0; i <= 25; i++) {
|
||||
lookUpBase64Alphabet[i] = (char) ('A' + i);
|
||||
}
|
||||
|
||||
for (int i = 26, j = 0; i <= 51; i++, j++) {
|
||||
lookUpBase64Alphabet[i] = (char) ('a' + j);
|
||||
}
|
||||
|
||||
for (int i = 52, j = 0; i <= 61; i++, j++) {
|
||||
lookUpBase64Alphabet[i] = (char) ('0' + j);
|
||||
}
|
||||
lookUpBase64Alphabet[62] = (char) '+';
|
||||
lookUpBase64Alphabet[63] = (char) '/';
|
||||
|
||||
}
|
||||
|
||||
private static boolean isWhiteSpace(char octect) {
|
||||
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
|
||||
}
|
||||
|
||||
private static boolean isPad(char octect) {
|
||||
return (octect == PAD);
|
||||
}
|
||||
|
||||
private static boolean isData(char octect) {
|
||||
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes hex octects into Base64
|
||||
*
|
||||
* @param binaryData Array containing binaryData
|
||||
* @return Encoded Base64 array
|
||||
*/
|
||||
public static String encode(byte[] binaryData) {
|
||||
|
||||
if (binaryData == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int lengthDataBits = binaryData.length * EIGHTBIT;
|
||||
if (lengthDataBits == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
|
||||
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
|
||||
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
|
||||
char encodedData[] = null;
|
||||
|
||||
encodedData = new char[numberQuartet * 4];
|
||||
|
||||
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
|
||||
|
||||
int encodedIndex = 0;
|
||||
int dataIndex = 0;
|
||||
if (fDebug) {
|
||||
System.out.println("number of triplets = " + numberTriplets);
|
||||
}
|
||||
|
||||
for (int i = 0; i < numberTriplets; i++) {
|
||||
b1 = binaryData[dataIndex++];
|
||||
b2 = binaryData[dataIndex++];
|
||||
b3 = binaryData[dataIndex++];
|
||||
|
||||
if (fDebug) {
|
||||
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
|
||||
}
|
||||
|
||||
l = (byte) (b2 & 0x0f);
|
||||
k = (byte) (b1 & 0x03);
|
||||
|
||||
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
|
||||
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
|
||||
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
|
||||
|
||||
if (fDebug) {
|
||||
System.out.println("val2 = " + val2);
|
||||
System.out.println("k4 = " + (k << 4));
|
||||
System.out.println("vak = " + (val2 | (k << 4)));
|
||||
}
|
||||
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
|
||||
}
|
||||
|
||||
// form integral number of 6-bit groups
|
||||
if (fewerThan24bits == EIGHTBIT) {
|
||||
b1 = binaryData[dataIndex];
|
||||
k = (byte) (b1 & 0x03);
|
||||
if (fDebug) {
|
||||
System.out.println("b1=" + b1);
|
||||
System.out.println("b1<<2 = " + (b1 >> 2));
|
||||
}
|
||||
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
|
||||
encodedData[encodedIndex++] = PAD;
|
||||
encodedData[encodedIndex++] = PAD;
|
||||
} else if (fewerThan24bits == SIXTEENBIT) {
|
||||
b1 = binaryData[dataIndex];
|
||||
b2 = binaryData[dataIndex + 1];
|
||||
l = (byte) (b2 & 0x0f);
|
||||
k = (byte) (b1 & 0x03);
|
||||
|
||||
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
|
||||
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
|
||||
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
|
||||
encodedData[encodedIndex++] = PAD;
|
||||
}
|
||||
|
||||
return new String(encodedData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes Base64 data into octects
|
||||
*
|
||||
* @param encoded string containing Base64 data
|
||||
* @return Array containind decoded data.
|
||||
*/
|
||||
public static byte[] decode(String encoded) {
|
||||
|
||||
if (encoded == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
char[] base64Data = encoded.toCharArray();
|
||||
// remove white spaces
|
||||
int len = removeWhiteSpace(base64Data);
|
||||
|
||||
if (len % FOURBYTE != 0) {
|
||||
return null;//should be divisible by four
|
||||
}
|
||||
|
||||
int numberQuadruple = (len / FOURBYTE);
|
||||
|
||||
if (numberQuadruple == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
byte decodedData[] = null;
|
||||
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
|
||||
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
|
||||
|
||||
int i = 0;
|
||||
int encodedIndex = 0;
|
||||
int dataIndex = 0;
|
||||
decodedData = new byte[(numberQuadruple) * 3];
|
||||
|
||||
for (; i < numberQuadruple - 1; i++) {
|
||||
|
||||
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|
||||
|| !isData((d3 = base64Data[dataIndex++]))
|
||||
|| !isData((d4 = base64Data[dataIndex++]))) {
|
||||
return null;
|
||||
}//if found "no data" just return null
|
||||
|
||||
b1 = base64Alphabet[d1];
|
||||
b2 = base64Alphabet[d2];
|
||||
b3 = base64Alphabet[d3];
|
||||
b4 = base64Alphabet[d4];
|
||||
|
||||
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
|
||||
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
|
||||
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
|
||||
}
|
||||
|
||||
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
|
||||
return null;//if found "no data" just return null
|
||||
}
|
||||
|
||||
b1 = base64Alphabet[d1];
|
||||
b2 = base64Alphabet[d2];
|
||||
|
||||
d3 = base64Data[dataIndex++];
|
||||
d4 = base64Data[dataIndex++];
|
||||
if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
|
||||
if (isPad(d3) && isPad(d4)) {
|
||||
if ((b2 & 0xf) != 0)//last 4 bits should be zero
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] tmp = new byte[i * 3 + 1];
|
||||
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
|
||||
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
|
||||
return tmp;
|
||||
} else if (!isPad(d3) && isPad(d4)) {
|
||||
b3 = base64Alphabet[d3];
|
||||
if ((b3 & 0x3) != 0)//last 2 bits should be zero
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] tmp = new byte[i * 3 + 2];
|
||||
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
|
||||
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
|
||||
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
|
||||
return tmp;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else { //No PAD e.g 3cQl
|
||||
b3 = base64Alphabet[d3];
|
||||
b4 = base64Alphabet[d4];
|
||||
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
|
||||
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
|
||||
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
|
||||
|
||||
}
|
||||
|
||||
return decodedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* remove WhiteSpace from MIME containing encoded Base64 data.
|
||||
*
|
||||
* @param data the byte array of base64 data (with WS)
|
||||
* @return the new length
|
||||
*/
|
||||
private static int removeWhiteSpace(char[] data) {
|
||||
if (data == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// count characters that's not whitespace
|
||||
int newSize = 0;
|
||||
int len = data.length;
|
||||
for (int i = 0; i < len; i++) {
|
||||
if (!isWhiteSpace(data[i])) {
|
||||
data[newSize++] = data[i];
|
||||
}
|
||||
}
|
||||
return newSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
|
||||
package in.egan.pay.common.util.encrypt;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
|
||||
public class RSA{
|
||||
|
||||
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 商户私钥
|
||||
* @param input_charset 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, String privateKey, String signType ,String input_charset)
|
||||
{
|
||||
try
|
||||
{
|
||||
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
|
||||
KeyFactory keyf = KeyFactory.getInstance(signType);
|
||||
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
|
||||
|
||||
java.security.Signature signature = java.security.Signature
|
||||
.getInstance(SIGN_ALGORITHMS);
|
||||
|
||||
signature.initSign(priKey);
|
||||
signature.update( content.getBytes(input_charset) );
|
||||
|
||||
byte[] signed = signature.sign();
|
||||
|
||||
return Base64.encode(signed);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA验签名检查
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param ali_public_key 支付宝公钥
|
||||
* @param input_charset 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, String ali_public_key, String input_charset)
|
||||
{
|
||||
try
|
||||
{
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
byte[] encodedKey = Base64.decode(ali_public_key);
|
||||
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
|
||||
|
||||
|
||||
java.security.Signature signature = java.security.Signature
|
||||
.getInstance(SIGN_ALGORITHMS);
|
||||
|
||||
signature.initVerify(pubKey);
|
||||
signature.update( content.getBytes(input_charset) );
|
||||
|
||||
boolean bverify = signature.verify( Base64.decode(sign) );
|
||||
return bverify;
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
* @param content 密文
|
||||
* @param private_key 商户私钥
|
||||
* @param input_charset 编码格式
|
||||
* @return 解密后的字符串
|
||||
*/
|
||||
public static String decrypt(String content, String private_key, String input_charset) throws Exception {
|
||||
PrivateKey prikey = getPrivateKey(private_key);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.DECRYPT_MODE, prikey);
|
||||
|
||||
InputStream ins = new ByteArrayInputStream(Base64.decode(content));
|
||||
ByteArrayOutputStream writer = new ByteArrayOutputStream();
|
||||
//rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
|
||||
byte[] buf = new byte[128];
|
||||
int bufl;
|
||||
|
||||
while ((bufl = ins.read(buf)) != -1) {
|
||||
byte[] block = null;
|
||||
|
||||
if (buf.length == bufl) {
|
||||
block = buf;
|
||||
} else {
|
||||
block = new byte[bufl];
|
||||
for (int i = 0; i < bufl; i++) {
|
||||
block[i] = buf[i];
|
||||
}
|
||||
}
|
||||
|
||||
writer.write(cipher.doFinal(block));
|
||||
}
|
||||
|
||||
return new String(writer.toByteArray(), input_charset);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 得到私钥
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @throws Exception
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(String key) throws Exception {
|
||||
|
||||
byte[] keyBytes;
|
||||
|
||||
keyBytes = Base64.decode(key);
|
||||
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
|
||||
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
|
||||
|
||||
return privateKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package in.egan.pay.common.util.http;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-24
|
||||
*/
|
||||
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
|
||||
/**
|
||||
* 简单的GET请求执行器,请求的参数是String, 返回的结果也是String
|
||||
* @author Daniel Qian
|
||||
*
|
||||
*/
|
||||
public class SimpleGetRequestExecutor implements RequestExecutor<String, String> {
|
||||
|
||||
@Override
|
||||
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws IOException, PayErrorException {
|
||||
if (queryParam != null) {
|
||||
if (uri.indexOf('?') == -1) {
|
||||
uri += '?';
|
||||
}
|
||||
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
|
||||
}
|
||||
HttpGet httpGet = new HttpGet(uri);
|
||||
if (httpProxy != null) {
|
||||
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
|
||||
httpGet.setConfig(config);
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
|
||||
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
return responseContent;
|
||||
}finally {
|
||||
httpGet.releaseConnection();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package in.egan.pay.common.util.http;
|
||||
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import org.apache.http.Consts;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
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 java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class SimplePostRequestExecutor implements RequestExecutor<String, Object> {
|
||||
|
||||
@Override
|
||||
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, Object postEntity) throws PayErrorException, ClientProtocolException, IOException {
|
||||
HttpPost httpPost = new HttpPost(uri);
|
||||
if (httpProxy != null) {
|
||||
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
|
||||
httpPost.setConfig(config);
|
||||
}
|
||||
|
||||
|
||||
if (postEntity instanceof Map) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Map pe = (Map) postEntity;
|
||||
for (Object key : pe.keySet()) {
|
||||
builder.append(key).append("=").append(pe.get(key)).append("&");
|
||||
}
|
||||
if (builder.length() > 1) {
|
||||
builder.deleteCharAt(builder.length() - 1);
|
||||
}
|
||||
StringEntity entity = new StringEntity(builder.toString(), Consts.UTF_8);
|
||||
httpPost.setEntity(entity);
|
||||
} else if (postEntity instanceof String) {
|
||||
|
||||
StringEntity entity = new StringEntity((String) postEntity, Consts.UTF_8);
|
||||
httpPost.setEntity(entity);
|
||||
}
|
||||
|
||||
|
||||
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
|
||||
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
|
||||
return responseContent;
|
||||
}finally {
|
||||
httpPost.releaseConnection();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package in.egan.pay.common.util.http;
|
||||
|
||||
import org.apache.http.Consts;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.StatusLine;
|
||||
import org.apache.http.client.HttpResponseException;
|
||||
import org.apache.http.client.ResponseHandler;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-24
|
||||
*/
|
||||
public class Utf8ResponseHandler implements ResponseHandler<String> {
|
||||
|
||||
public static final ResponseHandler<String> INSTANCE = new Utf8ResponseHandler();
|
||||
|
||||
public String handleResponse(final HttpResponse response) throws IOException {
|
||||
final StatusLine statusLine = response.getStatusLine();
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (statusLine.getStatusCode() >= 300) {
|
||||
EntityUtils.consume(entity);
|
||||
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
|
||||
}
|
||||
return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original huodull or egan.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
package in.egan.pay.common.util.sign;
|
||||
|
||||
|
||||
import in.egan.pay.common.util.str.StringUtils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 签名 工具
|
||||
*
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/9 17:45
|
||||
*/
|
||||
public enum SignUtils {
|
||||
|
||||
MD5 {
|
||||
/**
|
||||
*
|
||||
* @param content 需要签名的内容
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 字符编码
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String createSign(String content, String key, String characterEncoding) {
|
||||
|
||||
return in.egan.pay.common.util.sign.encrypt.MD5.sign(content, key, characterEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名字符串
|
||||
* @param text 需要签名的字符串
|
||||
* @param sign 签名结果
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名结果
|
||||
*/
|
||||
public boolean verify(String text, String sign, String key, String characterEncoding) {
|
||||
return in.egan.pay.common.util.sign.encrypt.MD5.verify(text, sign, key, characterEncoding);
|
||||
}
|
||||
},
|
||||
|
||||
RSA {
|
||||
@Override
|
||||
public String createSign(String content, String key, String characterEncoding) {
|
||||
return in.egan.pay.common.util.sign.encrypt.RSA.sign(content, key, characterEncoding);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String text, String sign, String publicKey, String characterEncoding) {
|
||||
return in.egan.pay.common.util.sign.encrypt.RSA.verify(text, sign, publicKey, characterEncoding);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* 把数组所有元素排序,并按照“参数=参数值”的模式用“@param separator”字符拼接成字符串
|
||||
* @param parameters 参数
|
||||
* @return 去掉空值与签名参数后的新签名,拼接后字符串
|
||||
*/
|
||||
public static String parameterText(Map parameters) {
|
||||
return parameterText(parameters, "&");
|
||||
|
||||
}
|
||||
/**
|
||||
*
|
||||
* 把数组所有元素排序,并按照“参数=参数值”的模式用“@param separator”字符拼接成字符串
|
||||
* @param parameters 参数
|
||||
* @param separator 分隔符
|
||||
* @return 去掉空值与签名参数后的新签名,拼接后字符串
|
||||
*/
|
||||
public static String parameterText(Map parameters, String separator) {
|
||||
if(parameters == null){
|
||||
return "";
|
||||
}
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
// TODO 2016/11/11 10:14 author: egan 已经排序好处理
|
||||
if (parameters instanceof SortedMap) {
|
||||
for (String k : ((Set<String>) parameters.keySet())) {
|
||||
Object v = parameters.get(k);
|
||||
if (null == v || "".equals(v.toString().trim()) || "sign".equals(k) || "key".equals(k) || "appId".equals(k) || "sign_type".equalsIgnoreCase(k)) {
|
||||
continue;
|
||||
}
|
||||
sb.append(k ).append("=").append( v.toString().trim()).append(separator);
|
||||
}
|
||||
if (sb.length() > 0 && !"".equals(separator)) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
|
||||
|
||||
// TODO 2016/11/11 10:14 author: egan 未排序须处理
|
||||
List<String> keys = new ArrayList<String>(parameters.keySet());
|
||||
//排序
|
||||
Collections.sort(keys);
|
||||
for (String k : keys) {
|
||||
String valueStr = "";
|
||||
Object o = parameters.get(k);
|
||||
if (o instanceof String[]) {
|
||||
String[] values = (String[]) o;
|
||||
if (null == values){continue;}
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
String value = values[i].trim();
|
||||
if ("".equals(value)){ continue;}
|
||||
valueStr = (i == values.length - 1) ? valueStr + value
|
||||
: valueStr + value + ",";
|
||||
}
|
||||
} else if (o != null) {
|
||||
valueStr = o.toString();
|
||||
}
|
||||
if (null == valueStr || "".equals(valueStr.toString().trim()) || "sign".equals(k) || "key".equals(k) || "appId".equals(k) || "sign_type".equalsIgnoreCase(k)) {
|
||||
continue;
|
||||
}
|
||||
sb.append(k ).append("=").append( valueStr).append(separator);
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将参数集合(事前做好排序)按分割符号拼凑字符串并加密为MD5
|
||||
* example: mchnt_cd+"|" +order_id+"|"+order_amt+"|"+order_pay_type+"|"+page_notify_url+"|"+back_notify_url+"|"+order_valid_time+"|"+iss_ins_cd+"|"+goods_name+"|"+"+goods_display_url+"|"+rem+"|"+ver+"|"+mchnt_key
|
||||
* @param parameters
|
||||
* @param separator
|
||||
* @return
|
||||
*/
|
||||
public static String parameters2MD5Str(Map parameters, String separator){
|
||||
StringBuffer sb = new StringBuffer();
|
||||
Set<String > keys = (Set<String>) parameters.keySet();
|
||||
|
||||
if (parameters instanceof LinkedHashMap) {
|
||||
for(String key : keys){
|
||||
String val = parameters.get(key).toString();
|
||||
if(StringUtils.isNotBlank(val)){
|
||||
sb.append(val).append(separator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return StringUtils.isBlank(sb.toString())?"":sb.deleteCharAt(sb.length() - 1).toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取随机字符串
|
||||
* @return
|
||||
*/
|
||||
public static String randomStr(){
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名
|
||||
*
|
||||
* @param parameters 需要进行排序签名的参数
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return
|
||||
*/
|
||||
public String sign(Map parameters, String key, String characterEncoding) {
|
||||
|
||||
return createSign(parameterText(parameters, "&"), key, characterEncoding);
|
||||
}
|
||||
/**
|
||||
* 签名
|
||||
* @param parameters 需要进行排序签名的参数
|
||||
* @param key 密钥
|
||||
* @param separator 分隔符 默认 &
|
||||
* @param characterEncoding 编码格式
|
||||
* @return
|
||||
*/
|
||||
public String sign(Map parameters, String key, String separator, String characterEncoding) {
|
||||
|
||||
return createSign(parameterText(parameters, separator), key, characterEncoding);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名
|
||||
*
|
||||
* @param content 需要签名的内容
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 字符编码
|
||||
* @return
|
||||
*/
|
||||
public abstract String createSign(String content, String key, String characterEncoding);
|
||||
|
||||
/**
|
||||
* 签名字符串
|
||||
*
|
||||
* @param params 需要签名的字符串
|
||||
* @param sign 签名结果
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名结果
|
||||
*/
|
||||
public boolean verify(Map params, String sign, String key, String characterEncoding){
|
||||
//判断是否一样
|
||||
// return StringUtils.equals(sign(params, key, characterEncoding), sign);
|
||||
return this.verify(parameterText(params), sign, key, characterEncoding);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 签名字符串
|
||||
*
|
||||
* @param text 需要签名的字符串
|
||||
* @param sign 签名结果
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名结果
|
||||
*/
|
||||
public abstract boolean verify(String text, String sign, String key, String characterEncoding);
|
||||
|
||||
|
||||
|
||||
//签名错误代码
|
||||
public static final int SIGN_ERROR = 91;
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* Copyright (C) 2010 The MobileSecurePay Project
|
||||
* All right reserved.
|
||||
* author: shiqun.shi@alipay.com
|
||||
*/
|
||||
|
||||
package in.egan.pay.common.util.sign.encrypt;
|
||||
|
||||
public final class Base64 {
|
||||
|
||||
static private final int BASELENGTH = 128;
|
||||
static private final int LOOKUPLENGTH = 64;
|
||||
static private final int TWENTYFOURBITGROUP = 24;
|
||||
static private final int EIGHTBIT = 8;
|
||||
static private final int SIXTEENBIT = 16;
|
||||
static private final int FOURBYTE = 4;
|
||||
static private final int SIGN = -128;
|
||||
static private final char PAD = '=';
|
||||
static private final boolean fDebug = false;
|
||||
static final private byte[] base64Alphabet = new byte[BASELENGTH];
|
||||
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
|
||||
|
||||
static {
|
||||
for (int i = 0; i < BASELENGTH; ++i) {
|
||||
base64Alphabet[i] = -1;
|
||||
}
|
||||
for (int i = 'Z'; i >= 'A'; i--) {
|
||||
base64Alphabet[i] = (byte) (i - 'A');
|
||||
}
|
||||
for (int i = 'z'; i >= 'a'; i--) {
|
||||
base64Alphabet[i] = (byte) (i - 'a' + 26);
|
||||
}
|
||||
|
||||
for (int i = '9'; i >= '0'; i--) {
|
||||
base64Alphabet[i] = (byte) (i - '0' + 52);
|
||||
}
|
||||
|
||||
base64Alphabet['+'] = 62;
|
||||
base64Alphabet['/'] = 63;
|
||||
|
||||
for (int i = 0; i <= 25; i++) {
|
||||
lookUpBase64Alphabet[i] = (char) ('A' + i);
|
||||
}
|
||||
|
||||
for (int i = 26, j = 0; i <= 51; i++, j++) {
|
||||
lookUpBase64Alphabet[i] = (char) ('a' + j);
|
||||
}
|
||||
|
||||
for (int i = 52, j = 0; i <= 61; i++, j++) {
|
||||
lookUpBase64Alphabet[i] = (char) ('0' + j);
|
||||
}
|
||||
lookUpBase64Alphabet[62] = (char) '+';
|
||||
lookUpBase64Alphabet[63] = (char) '/';
|
||||
|
||||
}
|
||||
|
||||
private static boolean isWhiteSpace(char octect) {
|
||||
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
|
||||
}
|
||||
|
||||
private static boolean isPad(char octect) {
|
||||
return (octect == PAD);
|
||||
}
|
||||
|
||||
private static boolean isData(char octect) {
|
||||
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes hex octects into Base64
|
||||
*
|
||||
* @param binaryData Array containing binaryData
|
||||
* @return Encoded Base64 array
|
||||
*/
|
||||
public static String encode(byte[] binaryData) {
|
||||
|
||||
if (binaryData == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int lengthDataBits = binaryData.length * EIGHTBIT;
|
||||
if (lengthDataBits == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
|
||||
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
|
||||
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
|
||||
char encodedData[] = null;
|
||||
|
||||
encodedData = new char[numberQuartet * 4];
|
||||
|
||||
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
|
||||
|
||||
int encodedIndex = 0;
|
||||
int dataIndex = 0;
|
||||
if (fDebug) {
|
||||
System.out.println("number of triplets = " + numberTriplets);
|
||||
}
|
||||
|
||||
for (int i = 0; i < numberTriplets; i++) {
|
||||
b1 = binaryData[dataIndex++];
|
||||
b2 = binaryData[dataIndex++];
|
||||
b3 = binaryData[dataIndex++];
|
||||
|
||||
if (fDebug) {
|
||||
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
|
||||
}
|
||||
|
||||
l = (byte) (b2 & 0x0f);
|
||||
k = (byte) (b1 & 0x03);
|
||||
|
||||
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
|
||||
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
|
||||
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
|
||||
|
||||
if (fDebug) {
|
||||
System.out.println("val2 = " + val2);
|
||||
System.out.println("k4 = " + (k << 4));
|
||||
System.out.println("vak = " + (val2 | (k << 4)));
|
||||
}
|
||||
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
|
||||
}
|
||||
|
||||
// form integral number of 6-bit groups
|
||||
if (fewerThan24bits == EIGHTBIT) {
|
||||
b1 = binaryData[dataIndex];
|
||||
k = (byte) (b1 & 0x03);
|
||||
if (fDebug) {
|
||||
System.out.println("b1=" + b1);
|
||||
System.out.println("b1<<2 = " + (b1 >> 2));
|
||||
}
|
||||
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
|
||||
encodedData[encodedIndex++] = PAD;
|
||||
encodedData[encodedIndex++] = PAD;
|
||||
} else if (fewerThan24bits == SIXTEENBIT) {
|
||||
b1 = binaryData[dataIndex];
|
||||
b2 = binaryData[dataIndex + 1];
|
||||
l = (byte) (b2 & 0x0f);
|
||||
k = (byte) (b1 & 0x03);
|
||||
|
||||
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
|
||||
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
|
||||
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
|
||||
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
|
||||
encodedData[encodedIndex++] = PAD;
|
||||
}
|
||||
|
||||
return new String(encodedData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes Base64 data into octects
|
||||
*
|
||||
* @param encoded string containing Base64 data
|
||||
* @return Array containind decoded data.
|
||||
*/
|
||||
public static byte[] decode(String encoded) {
|
||||
|
||||
if (encoded == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
char[] base64Data = encoded.toCharArray();
|
||||
// remove white spaces
|
||||
int len = removeWhiteSpace(base64Data);
|
||||
|
||||
if (len % FOURBYTE != 0) {
|
||||
return null;//should be divisible by four
|
||||
}
|
||||
|
||||
int numberQuadruple = (len / FOURBYTE);
|
||||
|
||||
if (numberQuadruple == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
byte decodedData[] = null;
|
||||
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
|
||||
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
|
||||
|
||||
int i = 0;
|
||||
int encodedIndex = 0;
|
||||
int dataIndex = 0;
|
||||
decodedData = new byte[(numberQuadruple) * 3];
|
||||
|
||||
for (; i < numberQuadruple - 1; i++) {
|
||||
|
||||
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|
||||
|| !isData((d3 = base64Data[dataIndex++]))
|
||||
|| !isData((d4 = base64Data[dataIndex++]))) {
|
||||
return null;
|
||||
}//if found "no data" just return null
|
||||
|
||||
b1 = base64Alphabet[d1];
|
||||
b2 = base64Alphabet[d2];
|
||||
b3 = base64Alphabet[d3];
|
||||
b4 = base64Alphabet[d4];
|
||||
|
||||
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
|
||||
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
|
||||
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
|
||||
}
|
||||
|
||||
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
|
||||
return null;//if found "no data" just return null
|
||||
}
|
||||
|
||||
b1 = base64Alphabet[d1];
|
||||
b2 = base64Alphabet[d2];
|
||||
|
||||
d3 = base64Data[dataIndex++];
|
||||
d4 = base64Data[dataIndex++];
|
||||
if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
|
||||
if (isPad(d3) && isPad(d4)) {
|
||||
if ((b2 & 0xf) != 0)//last 4 bits should be zero
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] tmp = new byte[i * 3 + 1];
|
||||
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
|
||||
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
|
||||
return tmp;
|
||||
} else if (!isPad(d3) && isPad(d4)) {
|
||||
b3 = base64Alphabet[d3];
|
||||
if ((b3 & 0x3) != 0)//last 2 bits should be zero
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] tmp = new byte[i * 3 + 2];
|
||||
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
|
||||
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
|
||||
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
|
||||
return tmp;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else { //No PAD e.g 3cQl
|
||||
b3 = base64Alphabet[d3];
|
||||
b4 = base64Alphabet[d4];
|
||||
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
|
||||
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
|
||||
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
|
||||
|
||||
}
|
||||
|
||||
return decodedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* remove WhiteSpace from MIME containing encoded Base64 data.
|
||||
*
|
||||
* @param data the byte array of base64 data (with WS)
|
||||
* @return the new length
|
||||
*/
|
||||
private static int removeWhiteSpace(char[] data) {
|
||||
if (data == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// count characters that's not whitespace
|
||||
int newSize = 0;
|
||||
int len = data.length;
|
||||
for (int i = 0; i < len; i++) {
|
||||
if (!isWhiteSpace(data[i])) {
|
||||
data[newSize++] = data[i];
|
||||
}
|
||||
}
|
||||
return newSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package in.egan.pay.common.util.sign.encrypt;
|
||||
|
||||
|
||||
import in.egan.pay.common.util.str.StringUtils;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.SignatureException;
|
||||
|
||||
/**
|
||||
* MD5签名工具
|
||||
*/
|
||||
public class MD5 {
|
||||
|
||||
/**
|
||||
* 签名字符串
|
||||
*
|
||||
* @param text 需要签名的字符串
|
||||
* @param key 密钥
|
||||
* @param input_charset 编码格式
|
||||
* @return 签名结果
|
||||
*/
|
||||
public static String sign(String text, String key, String input_charset) {
|
||||
//拼接key
|
||||
text = text + key;
|
||||
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名字符串
|
||||
*
|
||||
* @param text 需要签名的字符串
|
||||
* @param sign 签名结果
|
||||
* @param key 密钥
|
||||
* @param input_charset 编码格式
|
||||
* @return 签名结果
|
||||
*/
|
||||
public static boolean verify(String text, String sign, String key, String input_charset) {
|
||||
//判断是否一样
|
||||
return StringUtils.equals(sign(text, key, input_charset).toUpperCase(), sign.toUpperCase());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param content 需要加密串
|
||||
* @param charset 字符集
|
||||
* @return
|
||||
* @throws SignatureException
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static byte[] getContentBytes(String content, String charset) {
|
||||
if (StringUtils.isEmpty(charset)) {
|
||||
return content.getBytes();
|
||||
}
|
||||
try {
|
||||
return content.getBytes(charset);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
|
||||
package in.egan.pay.common.util.sign.encrypt;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
|
||||
public class RSA{
|
||||
|
||||
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, String privateKey ,String characterEncoding)
|
||||
{
|
||||
try
|
||||
{
|
||||
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
|
||||
KeyFactory keyf = KeyFactory.getInstance("RSA");
|
||||
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
|
||||
|
||||
java.security.Signature signature = java.security.Signature
|
||||
.getInstance(SIGN_ALGORITHMS);
|
||||
|
||||
signature.initSign(priKey);
|
||||
signature.update( content.getBytes(characterEncoding) );
|
||||
|
||||
byte[] signed = signature.sign();
|
||||
|
||||
return Base64.encode(signed);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA验签名检查
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, String publicKey, String characterEncoding)
|
||||
{
|
||||
try
|
||||
{
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
byte[] encodedKey = Base64.decode(publicKey);
|
||||
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
|
||||
|
||||
|
||||
java.security.Signature signature = java.security.Signature
|
||||
.getInstance(SIGN_ALGORITHMS);
|
||||
|
||||
signature.initVerify(pubKey);
|
||||
signature.update( content.getBytes(characterEncoding) );
|
||||
|
||||
boolean bverify = signature.verify( Base64.decode(sign) );
|
||||
return bverify;
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
* @param content 密文
|
||||
* @param privateKey 商户私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 解密后的字符串
|
||||
*/
|
||||
public static String decrypt(String content, String privateKey, String characterEncoding) throws Exception {
|
||||
PrivateKey prikey = getPrivateKey(privateKey);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.DECRYPT_MODE, prikey);
|
||||
|
||||
InputStream ins = new ByteArrayInputStream(Base64.decode(content));
|
||||
ByteArrayOutputStream writer = new ByteArrayOutputStream();
|
||||
//rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
|
||||
byte[] buf = new byte[128];
|
||||
int bufl;
|
||||
|
||||
while ((bufl = ins.read(buf)) != -1) {
|
||||
byte[] block = null;
|
||||
|
||||
if (buf.length == bufl) {
|
||||
block = buf;
|
||||
} else {
|
||||
block = new byte[bufl];
|
||||
for (int i = 0; i < bufl; i++) {
|
||||
block[i] = buf[i];
|
||||
}
|
||||
}
|
||||
|
||||
writer.write(cipher.doFinal(block));
|
||||
}
|
||||
|
||||
return new String(writer.toByteArray(), characterEncoding);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 得到私钥
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @throws Exception
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(String key) throws Exception {
|
||||
|
||||
byte[] keyBytes;
|
||||
|
||||
keyBytes = Base64.decode(key);
|
||||
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
|
||||
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
|
||||
|
||||
return privateKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package in.egan.pay.common.util.str;
|
||||
|
||||
/**
|
||||
* Created by ZaoSheng on 2016/6/4.
|
||||
*/
|
||||
public class StringUtils {
|
||||
|
||||
/**
|
||||
* 比较两个字符串(大小写敏感)。
|
||||
* <pre>
|
||||
* StringUtil.equals(null, null) = true
|
||||
* StringUtil.equals(null, "abc") = false
|
||||
* StringUtil.equals("abc", null) = false
|
||||
* StringUtil.equals("abc", "abc") = true
|
||||
* StringUtil.equals("abc", "ABC") = false
|
||||
* </pre>
|
||||
*
|
||||
* @param str1 要比较的字符串1
|
||||
* @param str2 要比较的字符串2
|
||||
*
|
||||
* @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
|
||||
*/
|
||||
public static boolean equals(String str1, String str2) {
|
||||
if (str1 == null) {
|
||||
return str2 == null;
|
||||
}
|
||||
|
||||
return str1.equals(str2);
|
||||
}
|
||||
// Empty checks
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>Checks if a CharSequence is empty ("") or null.</p>
|
||||
* <pre>
|
||||
* StringUtils.isEmpty(null) = true
|
||||
* StringUtils.isEmpty("") = true
|
||||
* StringUtils.isEmpty(" ") = false
|
||||
* StringUtils.isEmpty("bob") = false
|
||||
* StringUtils.isEmpty(" bob ") = false
|
||||
* </pre>
|
||||
* @param cs the CharSequence to check, may be null
|
||||
* @return {@code true} if the CharSequence is empty or null
|
||||
*/
|
||||
public static boolean isEmpty(CharSequence cs) {
|
||||
return cs == null || cs.length() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.isNotEmpty(null) = false
|
||||
* StringUtils.isNotEmpty("") = false
|
||||
* StringUtils.isNotEmpty(" ") = true
|
||||
* StringUtils.isNotEmpty("bob") = true
|
||||
* StringUtils.isNotEmpty(" bob ") = true
|
||||
* </pre>
|
||||
*
|
||||
* @param cs the CharSequence to check, may be null
|
||||
* @return {@code true} if the CharSequence is not empty and not null
|
||||
*/
|
||||
public static boolean isNotEmpty(CharSequence cs) {
|
||||
return !StringUtils.isEmpty(cs);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.isBlank(null) = true
|
||||
* StringUtils.isBlank("") = true
|
||||
* StringUtils.isBlank(" ") = true
|
||||
* StringUtils.isBlank("bob") = false
|
||||
* StringUtils.isBlank(" bob ") = false
|
||||
* </pre>
|
||||
* @param cs the CharSequence to check, may be null
|
||||
* @return {@code true} if the CharSequence is null, empty or whitespace
|
||||
* @since 2.0
|
||||
*/
|
||||
public static boolean isBlank(CharSequence cs) {
|
||||
int strLen;
|
||||
if (cs == null || (strLen = cs.length()) == 0) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
if (Character.isWhitespace(cs.charAt(i)) == false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.isNotBlank(null) = false
|
||||
* StringUtils.isNotBlank("") = false
|
||||
* StringUtils.isNotBlank(" ") = false
|
||||
* StringUtils.isNotBlank("bob") = true
|
||||
* StringUtils.isNotBlank(" bob ") = true
|
||||
* </pre>
|
||||
* @param cs the CharSequence to check, may be null
|
||||
* @return {@code true} if the CharSequence is
|
||||
* not empty and not null and not whitespace
|
||||
*/
|
||||
public static boolean isNotBlank(CharSequence cs) {
|
||||
return !StringUtils.isBlank(cs);
|
||||
}
|
||||
|
||||
}
|
||||
145
pay-java-demo/pom.xml
Normal file
145
pay-java-demo/pom.xml
Normal file
@@ -0,0 +1,145 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<artifactId>pay-java-parent</artifactId>
|
||||
<groupId>in.egan</groupId>
|
||||
<version>1.0.RELEASE</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>war</packaging>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-demo</artifactId>
|
||||
|
||||
<properties>
|
||||
<spring.version>4.3.4.RELEASE</spring.version>
|
||||
<junit.version>4.10</junit.version>
|
||||
<hibernate.version>4.3.6.Final</hibernate.version>
|
||||
<pay.version>2.0.SNAPSHOT</pay.version>
|
||||
</properties>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<!--支付-->
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-wx</artifactId>
|
||||
<version>${pay.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-ali</artifactId>
|
||||
<version>${pay.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-wx-youdian</artifactId>
|
||||
<version>${pay.version}</version>
|
||||
</dependency>
|
||||
<!--/支付-->
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jsp-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<type>jar</type>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<type>jar</type>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<!-- /spring -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.8.4</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>port8080</id>
|
||||
<properties>
|
||||
<port>8080</port>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>port9096</id>
|
||||
<properties>
|
||||
<port>9096</port>
|
||||
</properties>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>local</id>
|
||||
<properties>
|
||||
<env>local</env>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>proc</id>
|
||||
<properties>
|
||||
<env>proc</env>
|
||||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
<build>
|
||||
<finalName>pay-java-demo</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.tomcat.maven</groupId>
|
||||
<artifactId>tomcat7-maven-plugin</artifactId>
|
||||
<version>2.0</version>
|
||||
<configuration>
|
||||
<port>${port}</port>
|
||||
<path>/</path>
|
||||
<uriEncoding>UTF-8</uriEncoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<encoding>utf8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<filtering>true</filtering>
|
||||
<directory>src/main/resources</directory>
|
||||
<includes>
|
||||
<include>*</include>
|
||||
<include>*/**</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,155 @@
|
||||
|
||||
package in.egan.pay.demo.controller;
|
||||
|
||||
|
||||
import in.egan.pay.common.util.str.StringUtils;
|
||||
import in.egan.pay.demo.entity.ApyAccount;
|
||||
import in.egan.pay.demo.entity.PayType;
|
||||
import in.egan.pay.demo.service.ApyAccountService;
|
||||
import in.egan.pay.demo.service.PayResponse;
|
||||
import in.egan.pay.common.api.PayConfigStorage;
|
||||
import in.egan.pay.common.bean.MethodType;
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOrder;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static in.egan.pay.demo.dao.ApyAccountRepository.apyAccounts;
|
||||
|
||||
/**
|
||||
* 发起支付入口
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 0:25
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping
|
||||
public class PayController{
|
||||
|
||||
@Resource
|
||||
private ApyAccountService service;
|
||||
|
||||
|
||||
/**
|
||||
* 这里模拟账户信息增加
|
||||
* @param account
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("add")
|
||||
public Map<String, Object> add(ApyAccount account){
|
||||
apyAccounts.put(account.getPayId(), account);
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("code", 0);
|
||||
data.put("account", account);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 跳到支付页面
|
||||
* 针对实时支付,即时付款
|
||||
*
|
||||
* @param payId 账户id
|
||||
* @param transactionType 交易类型, 这个针对于每一个 支付类型的对应的几种交易方式
|
||||
* @param bankType 针对刷卡支付,卡的类型,类型值
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "toPay.html", produces = "text/html;charset=UTF-8")
|
||||
public String toPay( Integer payId, String transactionType, String bankType, @RequestParam(value = "0.01")BigDecimal price) {
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
|
||||
PayOrder order = new PayOrder("订单title", "摘要", price, UUID.randomUUID().toString().replace("-", ""), PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType));
|
||||
|
||||
//此处只有刷卡支付(银行卡支付)时需要
|
||||
if (StringUtils.isNotEmpty(bankType)){
|
||||
order.setBankType(bankType);
|
||||
}
|
||||
Map orderInfo = payResponse.getService().orderInfo(order);
|
||||
return payResponse.getService().buildRequest(orderInfo, MethodType.POST);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取二维码图像
|
||||
* 二维码支付
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "toQrPay.jpg", produces = "image/jpeg;charset=UTF-8")
|
||||
public byte[] toWxQrPay(Integer payId, String transactionType, @RequestParam(value = "0.01") BigDecimal price) throws IOException {
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
//获取订单信息
|
||||
Map<String, Object> orderInfo = payResponse.getService().orderInfo(new PayOrder("订单title", "摘要", price, UUID.randomUUID().toString().replace("-", ""), PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType)));
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(payResponse.getService().genQrPay(orderInfo), "JPEG", baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 获取支付预订单信息
|
||||
* @param payId 支付账户id
|
||||
* @param transactionType 交易类型
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("getOrderInfo")
|
||||
public Map<String, Object> getOrderInfo(Integer payId, String transactionType, @RequestParam(value = "0.01") BigDecimal price){
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("code", 0);
|
||||
PayOrder order = new PayOrder("订单title", "摘要", price, UUID.randomUUID().toString().replace("-", ""), PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType));
|
||||
data.put("orderInfo", payResponse.getService().orderInfo(order));
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 微信或者支付宝回调地址
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "payBack{payId}.json")
|
||||
public String payBack(HttpServletRequest request, @PathVariable Integer payId) throws IOException {
|
||||
//根据账户id,获取对应的支付账户操作工具
|
||||
PayResponse payResponse = service.getPayResponse(payId);
|
||||
PayConfigStorage storage = payResponse.getStorage();
|
||||
//获取支付方返回的对应参数
|
||||
Map<String, String> params = payResponse.getService().getParameter2Map(request.getParameterMap(), request.getInputStream());
|
||||
if (null == params){
|
||||
return payResponse.getService().getPayOutMessage("fail","失败").toMessage();
|
||||
}
|
||||
|
||||
//校验
|
||||
if (payResponse.getService().verify(params)){
|
||||
PayMessage message = new PayMessage(params, storage.getPayType(), storage.getMsgType().name());
|
||||
PayOutMessage outMessage = payResponse.getRouter().route(message);
|
||||
return outMessage.toMessage();
|
||||
}
|
||||
|
||||
return payResponse.getService().getPayOutMessage("fail","失败").toMessage();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
|
||||
|
||||
|
||||
package in.egan.pay.demo.dao;
|
||||
|
||||
import in.egan.pay.common.bean.MsgType;
|
||||
import in.egan.pay.demo.entity.ApyAccount;
|
||||
import in.egan.pay.demo.entity.PayType;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 账户
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 1:21
|
||||
*/
|
||||
//@Repository
|
||||
public class ApyAccountRepository {
|
||||
|
||||
// 这里简单模拟,引入orm等框架之后可自行删除
|
||||
public static Map<Integer, ApyAccount > apyAccounts = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 这里简单初始化,引入orm等框架之后可自行删除
|
||||
*/
|
||||
{
|
||||
ApyAccount apyAccount1 = new ApyAccount();
|
||||
apyAccount1.setPayId(1);
|
||||
apyAccount1.setPartner("12******01");
|
||||
apyAccount1.setAppid("wxa**********ba9e9");
|
||||
// TODO 2017/2/9 16:20 author: egan sign_type只有单一key时public_key与private_key相等,比如sign_type=MD5的情况
|
||||
apyAccount1.setPublicKey("48gf0iwuhr***********r9weh9eiut9");
|
||||
apyAccount1.setPrivateKey("48gf0iwuhr***********r9weh9eiut9");
|
||||
apyAccount1.setNotifyUrl("http://pay.egan.in/payBack2.json");
|
||||
// 无需同步回调可不填
|
||||
apyAccount1.setReturnUrl("");
|
||||
apyAccount1.setInputCharset("UTF-8");
|
||||
apyAccount1.setSignType("MD5");
|
||||
apyAccount1.setPayType(PayType.wxPay);
|
||||
apyAccount1.setMsgType(MsgType.xml);
|
||||
apyAccounts.put(1, apyAccount1);
|
||||
|
||||
ApyAccount apyAccount2 = new ApyAccount();
|
||||
apyAccount2.setPayId(2);
|
||||
apyAccount2.setPartner("2088****8307");
|
||||
apyAccount2.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4*****IZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB");
|
||||
apyAccount2.setPrivateKey("MIICdwIBADANBgkqhkiG9w0BAQ**********g51Vx8BvyypnIfKgw=");
|
||||
apyAccount2.setNotifyUrl("http://pay.egan.in/payBack3.json");
|
||||
// 无需同步回调可不填 app填这个就可以
|
||||
apyAccount2.setReturnUrl("m.alipay.com");
|
||||
apyAccount2.setSeller("egzosn@gmail.com");
|
||||
apyAccount2.setInputCharset("UTF-8");
|
||||
apyAccount2.setSignType("RSA");
|
||||
apyAccount2.setPayType(PayType.aliPay);
|
||||
apyAccount2.setMsgType(MsgType.text);
|
||||
apyAccounts.put(2, apyAccount2);
|
||||
|
||||
}
|
||||
//_____________________________________________________________
|
||||
|
||||
|
||||
/**
|
||||
* 根据id获取对应的账户信息
|
||||
* @param payId 账户id
|
||||
* @return
|
||||
*/
|
||||
public ApyAccount findByPayId(Integer payId){
|
||||
// TODO 2016/11/18 1:23 author: egan 这里简单模拟 具体实现 略。。
|
||||
return apyAccounts.get(payId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
|
||||
|
||||
package in.egan.pay.demo.entity;
|
||||
|
||||
import in.egan.pay.common.bean.MsgType;
|
||||
|
||||
//import javax.persistence.*;
|
||||
|
||||
/**
|
||||
* 支付账户
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 0:36
|
||||
*/
|
||||
//@Table(name = "apy_account")
|
||||
//@Entity
|
||||
public class ApyAccount {
|
||||
// 支付账号id
|
||||
// @Id
|
||||
// @GeneratedValue
|
||||
// @Column(name = "pay_id")
|
||||
private Integer payId;
|
||||
// 支付合作id,商户id,差不多是支付平台的账号或id
|
||||
// @Column(name = "partner")
|
||||
private String partner;
|
||||
// 应用id
|
||||
// @Column(name = "appid")
|
||||
private String appid;
|
||||
// 支付公钥,sign_type只有单一key时public_key与private_key相等,比如sign_type=MD5的情况
|
||||
private String publicKey;
|
||||
// 支付私钥
|
||||
// @Column(name = "private_key")
|
||||
private String privateKey;
|
||||
// 异步回调地址
|
||||
// @Column(name = "notify_url")
|
||||
private String notifyUrl;
|
||||
// 同步回调地址
|
||||
// @Column(name = "return_url")
|
||||
private String returnUrl;
|
||||
// 收款账号
|
||||
// @Column(name = "seller")
|
||||
private String seller;
|
||||
// 签名类型
|
||||
// @Column(name = "sign_type")
|
||||
private String signType;
|
||||
// 编码类型 枚举值,字符编码 utf-8,gbk等等
|
||||
// @Column(name = "input_charset")
|
||||
private String inputCharset;
|
||||
//支付类型,aliPay:支付宝,wxPay:微信, youdianPay: 友店微信,此处开发者自定义对应in.egan.pay.demo.entity.PayType枚举值
|
||||
// @Enumerated(EnumType.STRING)
|
||||
// @Column(name = "pay_type")
|
||||
private PayType payType;
|
||||
// 消息类型,text,xml,json
|
||||
// @Enumerated(EnumType.STRING)
|
||||
// @Column(name = "msg_type")
|
||||
private MsgType msgType;
|
||||
|
||||
public Integer getPayId() {
|
||||
return payId;
|
||||
}
|
||||
|
||||
public void setPayId(Integer payId) {
|
||||
this.payId = payId;
|
||||
}
|
||||
|
||||
public String getPartner() {
|
||||
return partner;
|
||||
}
|
||||
|
||||
public void setPartner(String partner) {
|
||||
this.partner = partner;
|
||||
}
|
||||
|
||||
public String getAppid() {
|
||||
return appid;
|
||||
}
|
||||
|
||||
public void setAppid(String appid) {
|
||||
this.appid = appid;
|
||||
}
|
||||
|
||||
public String getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public void setPublicKey(String publicKey) {
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
|
||||
public String getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
public void setPrivateKey(String privateKey) {
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public String getNotifyUrl() {
|
||||
return notifyUrl;
|
||||
}
|
||||
|
||||
public void setNotifyUrl(String notifyUrl) {
|
||||
this.notifyUrl = notifyUrl;
|
||||
}
|
||||
|
||||
public String getReturnUrl() {
|
||||
return returnUrl;
|
||||
}
|
||||
|
||||
public void setReturnUrl(String returnUrl) {
|
||||
this.returnUrl = returnUrl;
|
||||
}
|
||||
|
||||
public String getSeller() {
|
||||
return seller;
|
||||
}
|
||||
|
||||
public void setSeller(String seller) {
|
||||
this.seller = seller;
|
||||
}
|
||||
|
||||
public String getSignType() {
|
||||
return signType;
|
||||
}
|
||||
|
||||
public void setSignType(String signType) {
|
||||
this.signType = signType;
|
||||
}
|
||||
|
||||
public PayType getPayType() {
|
||||
return payType;
|
||||
}
|
||||
|
||||
public void setPayType(PayType payType) {
|
||||
this.payType = payType;
|
||||
}
|
||||
|
||||
public MsgType getMsgType() {
|
||||
return msgType;
|
||||
}
|
||||
|
||||
public void setMsgType(MsgType msgType) {
|
||||
this.msgType = msgType;
|
||||
}
|
||||
|
||||
public String getInputCharset() {
|
||||
return inputCharset;
|
||||
}
|
||||
|
||||
public void setInputCharset(String inputCharset) {
|
||||
this.inputCharset = inputCharset;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ApyAccount{" +
|
||||
"payId=" + payId +
|
||||
", partner='" + partner + '\'' +
|
||||
", appid='" + appid + '\'' +
|
||||
", publicKey='" + publicKey + '\'' +
|
||||
", privateKey='" + privateKey + '\'' +
|
||||
", notifyUrl='" + notifyUrl + '\'' +
|
||||
", returnUrl='" + returnUrl + '\'' +
|
||||
", seller='" + seller + '\'' +
|
||||
", signType='" + signType + '\'' +
|
||||
", inputCharset='" + inputCharset + '\'' +
|
||||
", payType=" + payType +
|
||||
", msgType=" + msgType +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
109
pay-java-demo/src/main/java/in/egan/pay/demo/entity/PayType.java
Normal file
109
pay-java-demo/src/main/java/in/egan/pay/demo/entity/PayType.java
Normal file
@@ -0,0 +1,109 @@
|
||||
package in.egan.pay.demo.entity;
|
||||
|
||||
import in.egan.pay.ali.api.AliPayConfigStorage;
|
||||
import in.egan.pay.ali.api.AliPayService;
|
||||
import in.egan.pay.ali.bean.AliTransactionType;
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.BasePayType;
|
||||
import in.egan.pay.common.bean.TransactionType;
|
||||
import in.egan.pay.wx.api.WxPayConfigStorage;
|
||||
import in.egan.pay.wx.api.WxPayService;
|
||||
import in.egan.pay.wx.bean.WxTransactionType;
|
||||
import in.egan.pay.wx.youdian.api.WxYouDianPayConfigStorage;
|
||||
import in.egan.pay.wx.youdian.api.WxYouDianPayService;
|
||||
import in.egan.pay.wx.youdian.bean.YoudianTransactionType;
|
||||
|
||||
|
||||
/**
|
||||
* 支付类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/20 0:30
|
||||
*/
|
||||
public enum PayType implements BasePayType {
|
||||
|
||||
aliPay{
|
||||
@Override
|
||||
public PayService getPayService(ApyAccount apyAccount) {
|
||||
AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
|
||||
aliPayConfigStorage.setPartner(apyAccount.getPartner());
|
||||
aliPayConfigStorage.setAliPublicKey(apyAccount.getPublicKey());
|
||||
aliPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey());
|
||||
aliPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl());
|
||||
aliPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl());
|
||||
aliPayConfigStorage.setSignType(apyAccount.getSignType());
|
||||
aliPayConfigStorage.setSeller(apyAccount.getSeller());
|
||||
aliPayConfigStorage.setPayType(apyAccount.getPayType().toString());
|
||||
aliPayConfigStorage.setMsgType(apyAccount.getMsgType());
|
||||
aliPayConfigStorage.setInputCharset(apyAccount.getInputCharset());
|
||||
return new AliPayService(aliPayConfigStorage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransactionType getTransactionType(String transactionType) {
|
||||
return AliTransactionType.valueOf(transactionType);
|
||||
}
|
||||
|
||||
|
||||
},wxPay {
|
||||
@Override
|
||||
public PayService getPayService(ApyAccount apyAccount) {
|
||||
WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
|
||||
wxPayConfigStorage.setMchId(apyAccount.getPartner());
|
||||
wxPayConfigStorage.setAppSecret(apyAccount.getPublicKey());
|
||||
wxPayConfigStorage.setKeyPublic(apyAccount.getPublicKey());
|
||||
wxPayConfigStorage.setAppid(apyAccount.getAppid());
|
||||
wxPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey());
|
||||
wxPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl());
|
||||
wxPayConfigStorage.setSignType(apyAccount.getSignType());
|
||||
wxPayConfigStorage.setPayType(apyAccount.getPayType().toString());
|
||||
wxPayConfigStorage.setMsgType(apyAccount.getMsgType());
|
||||
wxPayConfigStorage.setInputCharset(apyAccount.getInputCharset());
|
||||
return new WxPayService(wxPayConfigStorage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据支付类型获取交易类型
|
||||
* @param transactionType 类型值
|
||||
* @see WxTransactionType
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public TransactionType getTransactionType(String transactionType) {
|
||||
|
||||
return WxTransactionType.valueOf(transactionType);
|
||||
}
|
||||
},youdianPay {
|
||||
@Override
|
||||
public PayService getPayService(ApyAccount apyAccount) {
|
||||
// TODO 2017/1/23 14:12 author: egan 集群的话,友店可能会有bug。暂未测试集群环境
|
||||
WxYouDianPayConfigStorage wxPayConfigStorage = new WxYouDianPayConfigStorage();
|
||||
wxPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey());
|
||||
wxPayConfigStorage.setKeyPublic(apyAccount.getPublicKey());
|
||||
// wxPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl());
|
||||
// wxPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl());
|
||||
wxPayConfigStorage.setSignType(apyAccount.getSignType());
|
||||
wxPayConfigStorage.setPayType(apyAccount.getPayType().toString());
|
||||
wxPayConfigStorage.setMsgType(apyAccount.getMsgType());
|
||||
wxPayConfigStorage.setSeller(apyAccount.getSeller());
|
||||
wxPayConfigStorage.setInputCharset(apyAccount.getInputCharset());
|
||||
return new WxYouDianPayService(wxPayConfigStorage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据支付类型获取交易类型
|
||||
* @param transactionType 类型值
|
||||
* @see YoudianTransactionType
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public TransactionType getTransactionType(String transactionType) {
|
||||
|
||||
return YoudianTransactionType.valueOf(transactionType);
|
||||
}
|
||||
};
|
||||
|
||||
public abstract PayService getPayService(ApyAccount apyAccount);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
|
||||
package in.egan.pay.demo.service;
|
||||
|
||||
import in.egan.pay.demo.dao.ApyAccountRepository;
|
||||
import in.egan.pay.demo.entity.ApyAccount;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 1:11
|
||||
*/
|
||||
@Service
|
||||
public class ApyAccountService {
|
||||
|
||||
// @Resource
|
||||
private ApyAccountRepository dao;
|
||||
|
||||
@Resource
|
||||
private AutowireCapableBeanFactory spring;
|
||||
|
||||
//缓存
|
||||
private final static Map<Integer, PayResponse> payResponses = new HashMap<Integer, PayResponse>();
|
||||
|
||||
/**
|
||||
* 这里简单初始化,引入orm等框架之后可自行删除
|
||||
*/
|
||||
{
|
||||
|
||||
dao = new ApyAccountRepository();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取支付响应
|
||||
* @param id 账户id
|
||||
* @return
|
||||
*/
|
||||
public PayResponse getPayResponse(Integer id) {
|
||||
|
||||
PayResponse payResponse = payResponses.get(id);
|
||||
if (payResponse == null) {
|
||||
ApyAccount apyAccount = dao.findByPayId(id);
|
||||
if (apyAccount == null) {
|
||||
throw new IllegalArgumentException ("无法查询");
|
||||
}
|
||||
payResponse = new PayResponse();
|
||||
spring.autowireBean(payResponse);
|
||||
payResponse.init(apyAccount);
|
||||
payResponses.put(id, payResponse);
|
||||
// 查询
|
||||
}
|
||||
return payResponse;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
|
||||
|
||||
package in.egan.pay.demo.service;
|
||||
|
||||
import in.egan.pay.demo.entity.ApyAccount;
|
||||
import in.egan.pay.demo.entity.PayType;
|
||||
import in.egan.pay.demo.service.handler.AliPayMessageHandler;
|
||||
import in.egan.pay.demo.service.handler.FuiouPayMessageHandler;
|
||||
import in.egan.pay.demo.service.handler.WxPayMessageHandler;
|
||||
import in.egan.pay.demo.service.handler.YouDianPayMessageHandler;
|
||||
import in.egan.pay.demo.service.interceptor.AliPayMessageInterceptor;
|
||||
import in.egan.pay.common.api.PayConfigStorage;
|
||||
import in.egan.pay.common.api.PayMessageHandler;
|
||||
import in.egan.pay.common.api.PayMessageRouter;
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.MsgType;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 支付响应对象
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/11/18 0:34
|
||||
*/
|
||||
public class PayResponse {
|
||||
|
||||
@Resource
|
||||
private AutowireCapableBeanFactory spring;
|
||||
|
||||
private PayConfigStorage storage;
|
||||
|
||||
private PayService service;
|
||||
|
||||
private PayMessageRouter router;
|
||||
|
||||
public PayResponse() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化支付配置
|
||||
* @param apyAccount 账户信息
|
||||
* @see ApyAccount 对应表结构详情--》 /pay-java-demo/resources/apy_account.sql
|
||||
*/
|
||||
public void init(ApyAccount apyAccount) {
|
||||
//根据不同的账户类型 初始化支付配置
|
||||
this.service = apyAccount.getPayType().getPayService(apyAccount);
|
||||
this.storage = service.getPayConfigStorage();
|
||||
|
||||
buildRouter(apyAccount.getPayId());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 配置路由
|
||||
* @param payId 指定账户id,用户多微信支付多支付宝支付
|
||||
*/
|
||||
private void buildRouter(Integer payId) {
|
||||
router = new PayMessageRouter(this.service);
|
||||
router
|
||||
.rule()
|
||||
.async(false)
|
||||
.msgType(MsgType.text.name()) //消息类型
|
||||
.event(PayType.aliPay.name()) //支付账户事件类型
|
||||
.interceptor(new AliPayMessageInterceptor(payId)) //拦截器
|
||||
.handler(autowire(new AliPayMessageHandler(payId))) //处理器
|
||||
.end()
|
||||
.rule()
|
||||
.async(false)
|
||||
.msgType(MsgType.xml.name())
|
||||
.event(PayType.wxPay.name())
|
||||
.handler(autowire(new WxPayMessageHandler(payId)))
|
||||
.end()
|
||||
.rule()
|
||||
.async(false)
|
||||
.msgType(MsgType.json.name())
|
||||
.event(PayType.youdianPay.name())
|
||||
.handler(autowire(new YouDianPayMessageHandler(payId)))
|
||||
.end()
|
||||
|
||||
;
|
||||
}
|
||||
|
||||
|
||||
private PayMessageHandler autowire(PayMessageHandler handler) {
|
||||
spring.autowireBean(handler);
|
||||
return handler;
|
||||
}
|
||||
|
||||
public PayConfigStorage getStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public PayService getService() {
|
||||
return service;
|
||||
}
|
||||
|
||||
public PayMessageRouter getRouter() {
|
||||
return router;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package in.egan.pay.demo.service.handler;
|
||||
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 支付宝支付回调处理器
|
||||
* Created by ZaoSheng on 2016/6/1.
|
||||
*
|
||||
*/
|
||||
public class AliPayMessageHandler extends BasePayMessageHandler {
|
||||
|
||||
|
||||
public AliPayMessageHandler(Integer payId) {
|
||||
super(payId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
//交易状态
|
||||
String trade_status = null;
|
||||
try {
|
||||
trade_status = new String(payMessage.getPayMessage().get("trade_status").getBytes("ISO-8859-1"),"UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if(trade_status.equals("TRADE_FINISHED")){
|
||||
|
||||
//判断该笔订单是否在商户网站中已经做过处理
|
||||
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
|
||||
//如果有做过处理,不执行商户的业务程序
|
||||
//注意:
|
||||
//退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
|
||||
} else if (trade_status.equals("TRADE_SUCCESS")){
|
||||
|
||||
//判断该笔订单是否在商户网站中已经做过处理
|
||||
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
|
||||
//如果有做过处理,不执行商户的业务程序
|
||||
//注意:
|
||||
//付款完成后,支付宝系统发送该交易状态通知
|
||||
|
||||
|
||||
}else if (trade_status.equals("TRADE_SUCCESS")){
|
||||
// 交易创建
|
||||
}
|
||||
|
||||
return payService.getPayOutMessage("success", "成功");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package in.egan.pay.demo.service.handler;
|
||||
|
||||
import in.egan.pay.common.api.PayMessageHandler;
|
||||
|
||||
/**
|
||||
*
|
||||
* Created by ZaoSheng on 2016/6/1.
|
||||
*/
|
||||
public abstract class BasePayMessageHandler implements PayMessageHandler {
|
||||
//支付账户id
|
||||
private Integer payId;
|
||||
|
||||
public BasePayMessageHandler(Integer payId) {
|
||||
this.payId = payId;
|
||||
}
|
||||
|
||||
public Integer getPayId() {
|
||||
return payId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package in.egan.pay.demo.service.handler;
|
||||
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author Fuzx
|
||||
* @create 2017 2017/1/24 0024
|
||||
*/
|
||||
public class FuiouPayMessageHandler extends BasePayMessageHandler {
|
||||
|
||||
|
||||
|
||||
|
||||
public FuiouPayMessageHandler(Integer payId) {
|
||||
super(payId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
//交易状态
|
||||
if ("0000".equals(payMessage.getPayMessage().get("order_pay_code"))){
|
||||
/////这里进行成功的处理
|
||||
|
||||
return PayOutMessage.JSON().content("order_pay_error","成功").build();
|
||||
}
|
||||
|
||||
return PayOutMessage.JSON().content("order_pay_error",payMessage.getPayMessage().get("order_pay_error")).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package in.egan.pay.demo.service.handler;
|
||||
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.demo.service.handler.BasePayMessageHandler;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 微信支付回调处理器
|
||||
* Created by ZaoSheng on 2016/6/1.
|
||||
*/
|
||||
public class WxPayMessageHandler extends BasePayMessageHandler {
|
||||
|
||||
|
||||
|
||||
|
||||
public WxPayMessageHandler(Integer payId) {
|
||||
super(payId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
//交易状态
|
||||
if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))){
|
||||
/////这里进行成功的处理
|
||||
|
||||
return payService.getPayOutMessage("SUCCESS", "OK");
|
||||
}
|
||||
|
||||
return payService.getPayOutMessage("FAIL", "失败");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package in.egan.pay.demo.service.handler;
|
||||
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author Fuzx
|
||||
* @create 2017 2017/1/24 0024
|
||||
*/
|
||||
public class YouDianPayMessageHandler extends BasePayMessageHandler {
|
||||
|
||||
|
||||
|
||||
|
||||
public YouDianPayMessageHandler(Integer payId) {
|
||||
super(payId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
//交易状态
|
||||
if ("0000".equals(payMessage.getPayMessage().get("order_pay_code"))){
|
||||
/////这里进行成功的处理
|
||||
|
||||
return PayOutMessage.JSON().content("order_pay_error","成功").build();
|
||||
}
|
||||
|
||||
return PayOutMessage.JSON().content("order_pay_error",payMessage.getPayMessage().get("order_pay_error")).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
|
||||
package in.egan.pay.demo.service.interceptor;
|
||||
|
||||
import in.egan.pay.common.api.PayMessageHandler;
|
||||
import in.egan.pay.common.api.PayMessageInterceptor;
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.bean.PayMessage;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 支付宝回调信息拦截器
|
||||
* @author: egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/1/18 19:28
|
||||
*/
|
||||
public class AliPayMessageInterceptor implements PayMessageInterceptor {
|
||||
|
||||
//支付账户id
|
||||
private Integer payId;
|
||||
public AliPayMessageInterceptor(Integer payId) {
|
||||
|
||||
this.payId = payId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截支付消息
|
||||
*
|
||||
* @param payMessage 支付回调消息
|
||||
* @param context 上下文,如果handler或interceptor之间有信息要传递,可以用这个
|
||||
* @param payService
|
||||
* @return true代表OK,false代表不OK并直接中断对应的支付处理器
|
||||
* @see PayMessageHandler 支付处理器
|
||||
*/
|
||||
@Override
|
||||
public boolean intercept(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
|
||||
|
||||
//这里进行拦截器处理,自行实现
|
||||
return true;
|
||||
}
|
||||
}
|
||||
18
pay-java-demo/src/main/resources/applicationContext.xml
Normal file
18
pay-java-demo/src/main/resources/applicationContext.xml
Normal file
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context.xsd"
|
||||
>
|
||||
|
||||
<!-- 使用annotation注解的方式时,需要添加上此行配置 -->
|
||||
<context:annotation-config />
|
||||
|
||||
<context:component-scan base-package="in.egan.pay.demo" />
|
||||
|
||||
|
||||
|
||||
</beans>
|
||||
31
pay-java-demo/src/main/resources/apy_account.sql
Normal file
31
pay-java-demo/src/main/resources/apy_account.sql
Normal file
@@ -0,0 +1,31 @@
|
||||
|
||||
/*Table structure for table `apy_account` */
|
||||
|
||||
DROP TABLE IF EXISTS `apy_account`;
|
||||
|
||||
CREATE TABLE `apy_account` (
|
||||
`pay_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '支付账号id',
|
||||
`partner` varchar(32) DEFAULT NULL COMMENT '支付合作id,商户id,差不多是支付平台的账号或id',
|
||||
`appid` varchar(32) DEFAULT NULL COMMENT '应用id',
|
||||
`public_key` varchar(1204) DEFAULT NULL COMMENT '支付公钥,sign_type只有单一key时public_key与private_key相等,比如sign_type=MD5的情况',
|
||||
`private_key` varchar(2048) DEFAULT NULL COMMENT '支付私钥',
|
||||
`notify_url` varchar(1024) DEFAULT NULL COMMENT '异步回调地址',
|
||||
`return_url` varchar(1024) DEFAULT NULL COMMENT '同步回调地址',
|
||||
`seller` varchar(256) DEFAULT NULL COMMENT '收款账号, 针对支付宝',
|
||||
`sign_type` varchar(16) DEFAULT NULL COMMENT '签名类型',
|
||||
`input_charset` varchar(16) DEFAULT NULL COMMENT '枚举值,字符编码 utf-8,gbk等等',
|
||||
`pay_type` char(16) DEFAULT NULL COMMENT '支付类型,aliPay:支付宝,wxPay:微信, youdianPay: 友店微信,此处开发者自定义对应in.egan.pay.demo.entity.PayType枚举值',
|
||||
`msg_type` char(8) DEFAULT NULL COMMENT '消息类型,text,xml,json',
|
||||
`create_by` char(32) DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',
|
||||
PRIMARY KEY (`pay_id`)
|
||||
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
|
||||
|
||||
/*Data for the table `apy_account` */
|
||||
|
||||
insert into `apy_account`(`pay_id`,`partner`,`appid`,`public_key`,`private_key`,`notify_url`,`return_url`,`seller`,`sign_type`,`input_charset`,`pay_type`,`msg_type`,`create_by`,`create_time`) values
|
||||
(1,'12******01','wxa**********ba9e9','48gf0iwuhr***********r9weh9eiut9','48gf0iwuhr***********r9weh9eiut9','http://pay.egan.in/payBack2.json','同步回调地址','','MD5','utf-8','wxPay','xml','egan','2017-01-20 17:07:48'),
|
||||
(2,'20889119449*****','','MIGfMA0GCSqGSIb3DQEB*********gmLCUYuLkxpLQIDAQAB','IqZg51Vx8BvyypnIfKgw=*********MIICdwIBADANBgkqhkiG9w0BAQE','http://pay.egan.in/payBack3.json','同步回调地址','egzosn@gmail.com','RSA','utf-8','aliPay','text','egan','2017-01-20 17:11:46'),
|
||||
|
||||
|
||||
|
||||
34
pay-java-demo/src/main/resources/mvc-servlet-context.xml
Normal file
34
pay-java-demo/src/main/resources/mvc-servlet-context.xml
Normal file
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context.xsd
|
||||
">
|
||||
|
||||
<!-- 使用annotation注解的方式时,需要添加上此行配置 -->
|
||||
<context:annotation-config/>
|
||||
|
||||
<!-- 只扫描控制器Action -->
|
||||
<context:component-scan base-package="in.egan.pay.demo.controller" />
|
||||
|
||||
<!-- MVC 注解 -->
|
||||
<mvc:annotation-driven>
|
||||
<!-- <mvc:message-converters >
|
||||
<!– 配置Fastjson支持 –>
|
||||
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
|
||||
|
||||
</bean>
|
||||
</mvc:message-converters>-->
|
||||
</mvc:annotation-driven>
|
||||
|
||||
<!-- 静态资源,当找不到对应的处理时,调用这个 -->
|
||||
<mvc:default-servlet-handler/>
|
||||
|
||||
|
||||
</beans>
|
||||
37
pay-java-demo/src/main/webapp/WEB-INF/web.xml
Normal file
37
pay-java-demo/src/main/webapp/WEB-INF/web.xml
Normal file
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
version="3.0">
|
||||
<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
</welcome-file-list>
|
||||
<context-param>
|
||||
<description>Spring 配置文件</description>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>
|
||||
classpath:applicationContext.xml
|
||||
</param-value>
|
||||
</context-param>
|
||||
<servlet>
|
||||
<servlet-name>spring</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<init-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>classpath:mvc-servlet-context.xml</param-value>
|
||||
</init-param>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>spring</servlet-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<listener>
|
||||
<description>Spring 监听器</description>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
</web-app>
|
||||
120
pay-java-demo/src/main/webapp/index.html
Normal file
120
pay-java-demo/src/main/webapp/index.html
Normal file
@@ -0,0 +1,120 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>TEST</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
账户信息添加用于下面测试
|
||||
<div>
|
||||
<form id="form">
|
||||
账户id<input type="text" name="payId">
|
||||
<br>
|
||||
支付合作id<input type="text" name="partner">
|
||||
<br>
|
||||
应用id<input type="text" name="appid">
|
||||
<br>
|
||||
支付公钥<input type="text" name="publicKey"><b>如签名类型为MD5时,当前的值与支付私钥想等</b>
|
||||
<br>
|
||||
支付私钥<input type="text" name="privateKey">
|
||||
<br>
|
||||
异步回调地址<input type="text" name="notifyUrl"><b>友店支付用不到此参数,在友店管理端进行配置</b>
|
||||
<br>
|
||||
同步回调地址<input type="text" name="returnUrl"><b>同上</b>
|
||||
<br>
|
||||
收款账号(即时付款填写支付合作id)<input type="text" name="seller"><b>针对支付宝</b>
|
||||
<br/>
|
||||
签名类型<select name="signType">
|
||||
<option>MD5</option>
|
||||
<option>RSA</option>
|
||||
</select>
|
||||
<br>
|
||||
编码类型(建议UTF-8)<input type="text" name="inputCharset">
|
||||
<br>
|
||||
支付账户类型 <select name="payType">
|
||||
<option value="aliPay">aliPay</option>
|
||||
<option value="wxPay">wxPay</option>
|
||||
<option value="youdianPay">youdianPay</option>
|
||||
</select><b>此处为开发者自定义,详情请查看 in.egan.pay.demo.entity.PayType</b>
|
||||
<br>
|
||||
消息类型 <select name="msgType">
|
||||
<option>text</option>
|
||||
<option>xml</option>
|
||||
<option>json</option>
|
||||
</select>
|
||||
<br>
|
||||
</form>
|
||||
<button id="submit">提交</button>
|
||||
</div>
|
||||
|
||||
<br/>
|
||||
<div>各个支付对应的<b>交易类型</b>可自行查看对应的官方文档,本项目已实现几种交易类型,对应各个支付类型的<code>in.egan.pay.common.bean.TransactionType</code>具体实现</div>
|
||||
<div>支付宝(<code>in.egan.pay.ali.bean.AliTransactionType</code>): 即时付款=DIRECT , 移动支付=APP , 手机网站支付=WAP</div>
|
||||
<div>微信(<code>in.egan.pay.wx.bean.WxTransactionType</code>): 公众号支付=JSAPI , 移动支付=APP , 扫码付=NATIVE</div>
|
||||
<div>友店微信(<code>in.egan.pay.wx.youdian.bean.YoudianTransactionType</code>): 扫码付=NATIVE</div>
|
||||
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
APP提交(返回对应的json,具体实现,app端demo暂时未实现)
|
||||
<form action="getOrderInfo" target="_blank">
|
||||
账户id<input type="text" name="payId">
|
||||
<br>
|
||||
金额<input type="text" name="price">
|
||||
<br>
|
||||
交易类型<input type="text" name="transactionType" value="APP" readonly>
|
||||
<br>
|
||||
<input type="submit" value="提交">
|
||||
</form>
|
||||
|
||||
<br>
|
||||
普通web提交
|
||||
<form action="toPay.html" target="_blank">
|
||||
账户id<input type="text" name="payId">
|
||||
<br>
|
||||
金额<input type="text" name="price">
|
||||
<br>
|
||||
交易类型<input type="text" name="transactionType">
|
||||
<br>
|
||||
<input type="submit" value="提交">
|
||||
</form>
|
||||
|
||||
<br>
|
||||
二维码
|
||||
<form action="toQrPay.jpg" target="_blank">
|
||||
账户id<input type="text" name="payId">
|
||||
<br>
|
||||
金额<input type="text" name="price">
|
||||
<br>
|
||||
交易类型<input type="text" name="transactionType">
|
||||
<br>
|
||||
<input type="submit" value="提交">
|
||||
</form>
|
||||
<script src="jquery-3.1.1.min.js"></script>
|
||||
<script>
|
||||
$(function ($) {
|
||||
$("#submit").click(function () {
|
||||
$.ajax({
|
||||
url : "add",
|
||||
type : "post",
|
||||
data : $("#form").serialize(),
|
||||
dataType : 'json',
|
||||
success : function(data) {
|
||||
if (data.code == 0){
|
||||
alert("保存成功");
|
||||
return;
|
||||
}
|
||||
alert("保存失败");
|
||||
},
|
||||
error : function(edata) {
|
||||
alert("服务器异常")
|
||||
}
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
4
pay-java-demo/src/main/webapp/jquery-3.1.1.min.js
vendored
Normal file
4
pay-java-demo/src/main/webapp/jquery-3.1.1.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
26
pay-java-wx-youdian/pom.xml
Normal file
26
pay-java-wx-youdian/pom.xml
Normal file
@@ -0,0 +1,26 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<artifactId>pay-java-parent</artifactId>
|
||||
<groupId>in.egan</groupId>
|
||||
<version>2.0.SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>pay-java-wx-youdian</artifactId>
|
||||
|
||||
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- pay-java -->
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-common</artifactId>
|
||||
</dependency>
|
||||
<!-- /pay-java -->
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,68 @@
|
||||
package in.egan.pay.wx.youdian.api;
|
||||
|
||||
import in.egan.pay.common.api.BasePayConfigStorage;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
* 支付客户端配置存储
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/01/12 22:58
|
||||
*/
|
||||
public class WxYouDianPayConfigStorage extends BasePayConfigStorage {
|
||||
|
||||
public volatile String secretKey;
|
||||
//账号
|
||||
public volatile String seller;
|
||||
|
||||
|
||||
|
||||
public void setSecretKey(String secretKey) {
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSecretKey() {
|
||||
return secretKey;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getAppid() {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getPartner() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setSeller(String seller) {
|
||||
this.seller = seller;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSeller() {
|
||||
return seller;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void setToken(String accessToken) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package in.egan.pay.wx.youdian.api;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import in.egan.pay.common.api.BasePayService;
|
||||
import in.egan.pay.common.api.PayConfigStorage;
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.MethodType;
|
||||
import in.egan.pay.common.bean.PayOrder;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.bean.outbuilder.JsonBuilder;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.MatrixToImageWriter;
|
||||
import in.egan.pay.common.util.sign.SignUtils;
|
||||
import in.egan.pay.wx.youdian.utils.SimpleGetRequestExecutor;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
/**
|
||||
* 友店支付服务
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/01/12 22:58
|
||||
*/
|
||||
public class WxYouDianPayService extends BasePayService {
|
||||
protected final Log log = LogFactory.getLog(WxYouDianPayService.class);
|
||||
//登录获取授权码
|
||||
public final static String loginUrl = "http://life.51youdian.com/Api/CheckoutCounter/login";
|
||||
//刷新授权码
|
||||
public final static String resetLoginUrl = "http://life.51youdian.com/Api/CheckoutCounter/resetLogin";
|
||||
//查看付款订单状态
|
||||
public final static String unifiedorderStatusUrl = "http://life.51youdian.com/Api/CheckoutCounter/unifiedorderStatus";
|
||||
//预下单链接
|
||||
public final static String unifiedOrderUrl = "http://life.51youdian.com/Api/CheckoutCounter/unifiedorder";
|
||||
|
||||
|
||||
public String getAccessToken() {
|
||||
try {
|
||||
return getAccessToken(false);
|
||||
} catch (PayErrorException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权令牌
|
||||
* @param forceRefresh
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
public String getAccessToken(boolean forceRefresh) throws PayErrorException {
|
||||
Lock lock = payConfigStorage.getAccessTokenLock();
|
||||
try {
|
||||
lock.lock();
|
||||
|
||||
if (forceRefresh) {
|
||||
payConfigStorage.expireAccessToken();
|
||||
}
|
||||
|
||||
if (payConfigStorage.isAccessTokenExpired()) {
|
||||
if (null == payConfigStorage.getAccessToken()){
|
||||
login();
|
||||
return payConfigStorage.getAccessToken();
|
||||
}
|
||||
String apbNonce = SignUtils.randomStr();
|
||||
StringBuilder param = new StringBuilder().append("access_token=").append(payConfigStorage.getAccessToken());
|
||||
String sign = createSign(param.toString() + apbNonce, payConfigStorage.getInputCharset());
|
||||
param.append("&apb_nonce=").append(apbNonce).append("&sign=").append(sign);
|
||||
JSONObject json = execute(new SimpleGetRequestExecutor(), resetLoginUrl, param.toString());
|
||||
int errorcode = json.getIntValue("errorcode");
|
||||
if (0 == errorcode){
|
||||
payConfigStorage.updateAccessToken(payConfigStorage.getAccessToken(), 7200);
|
||||
}else {
|
||||
throw new PayErrorException(new PayError(errorcode, json.getString("msg"), json.toJSONString()));
|
||||
}
|
||||
|
||||
/* try {
|
||||
HttpGet httpGet = new HttpGet(resetLoginUrl+ "?" + param.toString());
|
||||
if (this.httpProxy != null) {
|
||||
RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build();
|
||||
httpGet.setConfig(config);
|
||||
}
|
||||
try (CloseableHttpResponse response = getHttpClient().execute(httpGet)) {
|
||||
String responseObj = new BasicResponseHandler().handleResponse(response);
|
||||
JSONObject json = JSON.parseObject(responseObj);
|
||||
int errorcode = json.getIntValue("errorcode");
|
||||
|
||||
switch (errorcode){
|
||||
//成功
|
||||
case 0:
|
||||
//刷新
|
||||
payConfigStorage.updateAccessToken(payConfigStorage.getAccessToken(), 7200);
|
||||
break;
|
||||
//登录已过期
|
||||
case 401:
|
||||
//进行重新登陆
|
||||
JSONObject login = login();
|
||||
payConfigStorage.updateAccessToken(login.getString("access_token"), login.getLongValue("viptime"));
|
||||
break;
|
||||
default:
|
||||
throw new PayErrorException(new PayError(errorcode, json.getString("msg"), responseObj));
|
||||
|
||||
}
|
||||
}finally {
|
||||
httpGet.releaseConnection();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}*/
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
return payConfigStorage.getAccessToken();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 登录 获取授权码
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
public JSONObject login() throws PayErrorException {
|
||||
TreeMap<String, String> data = new TreeMap<>();
|
||||
data.put("username", payConfigStorage.getSeller());
|
||||
data.put("password", payConfigStorage.getKeyPrivate());
|
||||
String apbNonce = "6863fc0308af4550993ad4a57693ed9d";//SignUtils.randomStr();
|
||||
// 1、确定请求主体为用户登录,即需要传登录的用户名username和密码password并且要生成唯一的随机数命名为apb_nonce,长度为32位
|
||||
// 2、将所有的参数集进行key排序
|
||||
// 3、将排序后的数组从起始位置拼接成字符串如:password=XXXXXXXusername=XXXXX
|
||||
// 4、将拼接出来的字符串连接上apb_nonce的值即AAAAAAAAAA。再连接 password=XXXXXXXusername=XXXXXAAAAAAAAAA
|
||||
String sign = createSign(SignUtils.parameterText(data, "") + apbNonce, payConfigStorage.getInputCharset());
|
||||
String queryParam = SignUtils.parameterText(data) + "&apb_nonce=" + apbNonce + "&sign=" + sign;
|
||||
JSONObject json = execute(new SimpleGetRequestExecutor(), loginUrl, queryParam);
|
||||
payConfigStorage.updateAccessToken(json.getString("access_token"), json.getLongValue("viptime"));
|
||||
return json;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 微信友店2支付状态校验
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String getHttpsVerifyUrl() {
|
||||
return unifiedorderStatusUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(Map<String, String> params) {
|
||||
if (!"SUCCESS".equals(params.get("return_code"))){
|
||||
log.debug(String.format("友店微信支付异常:return_code=%s,参数集=%s", params.get("return_code"), params));
|
||||
return false;
|
||||
}
|
||||
if(params.get("sign") == null) {log.debug("友店微信支付异常:签名为空!out_trade_no=" + params.get("out_trade_no"));}
|
||||
|
||||
try {
|
||||
return getSignVerify(params, params.get("sign")) && "0".equals(verifyUrl(params.get("out_trade_no")));
|
||||
} catch (PayErrorException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据反馈回来的信息,生成签名结果
|
||||
* @param params 通知返回来的参数数组
|
||||
* @param sign 比对的签名结果
|
||||
* @return 生成的签名结果
|
||||
*/
|
||||
public boolean getSignVerify(Map<String, String> params, String sign) {
|
||||
return SignUtils.valueOf(payConfigStorage.getSignType()).verify(params, sign, "&key=" + payConfigStorage.getKeyPrivate(), payConfigStorage.getInputCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证链接来源是否有效
|
||||
* @param outTradeNo 商户订单号(扫码收款返回的order_sn)
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
@Override
|
||||
public String verifyUrl(String outTradeNo) throws PayErrorException {
|
||||
String apbNonce = SignUtils.randomStr();
|
||||
TreeMap<String, String> data = new TreeMap<>();
|
||||
data.put("access_token", payConfigStorage.getAccessToken());
|
||||
data.put("order_sn", outTradeNo);
|
||||
String sign = createSign(SignUtils.parameterText(data, "") + apbNonce, payConfigStorage.getInputCharset());
|
||||
String queryParam = SignUtils.parameterText(data) + "&apb_nonce=" + apbNonce + "&sign=" + sign;
|
||||
|
||||
JSONObject jsonObject = execute(new SimpleGetRequestExecutor(), getHttpsVerifyUrl(), queryParam);
|
||||
|
||||
return jsonObject.getIntValue("errorcode") + "";
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 向友店端发送请求,在这里执行的策略是当发生access_token过期时才去刷新,然后重新执行请求,而不是全局定时请求
|
||||
*
|
||||
* @param executor
|
||||
* @param uri
|
||||
* @param data
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
@Override
|
||||
public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException {
|
||||
int retryTimes = 0;
|
||||
do {
|
||||
try {
|
||||
return executeInternal(executor, uri, data);
|
||||
} catch (PayErrorException e) {
|
||||
PayError error = e.getError();
|
||||
if (error.getErrorCode() == 401) {
|
||||
// 强制设置wxMpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token
|
||||
payConfigStorage.expireAccessToken();
|
||||
//进行重新登陆授权
|
||||
login();
|
||||
int sleepMillis = retrySleepMillis * (1 << retryTimes);
|
||||
try {
|
||||
log.debug(String.format("友店微信系统繁忙,(%s)ms 后重试(第%s次)", sleepMillis, retryTimes + 1));
|
||||
Thread.sleep(sleepMillis);
|
||||
} catch (InterruptedException e1) {
|
||||
throw new RuntimeException(e1);
|
||||
}
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
} while (++retryTimes < maxRetryTimes);
|
||||
|
||||
throw new PayErrorException(new PayError(-1, "友店微信服务端异常,超出重试次数"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取支付平台所需的订单信息
|
||||
*
|
||||
* @param order 支付订单
|
||||
* @return
|
||||
* @see in.egan.pay.common.bean.PayOrder
|
||||
*/
|
||||
@Override
|
||||
public JSONObject orderInfo(PayOrder order) {
|
||||
TreeMap<String, String> data = new TreeMap<>();
|
||||
data.put("access_token", getAccessToken());
|
||||
data.put("paymoney", order.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
|
||||
String apbNonce = SignUtils.randomStr();
|
||||
String sign = createSign(SignUtils.parameterText(data, "") + apbNonce, payConfigStorage.getInputCharset());
|
||||
data.put("PayMoney", data.remove("paymoney"));
|
||||
String params = SignUtils.parameterText(data) + "&apb_nonce=" + apbNonce + "&sign=" + sign;
|
||||
try {
|
||||
JSONObject json = execute(new SimpleGetRequestExecutor(), unifiedOrderUrl, params);
|
||||
//友店比较特殊,需要在下完预订单后,自己存储 order_sn 对应 微信官方文档 out_trade_no
|
||||
order.setTradeNo(json.getString("order_sn"));
|
||||
return json;
|
||||
} catch (PayErrorException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 签名
|
||||
* @param content 需要签名的内容
|
||||
* @param characterEncoding 字符编码
|
||||
*
|
||||
* 1、确定请求主体为用户登录,即需要传登录的用户名username和密码password并且要生成唯一的随机数命名为apb_nonce,长度为32位
|
||||
* 2、将所有的参数集进行key排序
|
||||
* 3、将排序后的数组从起始位置拼接成字符串如:password=XXXXXXXusername=XXXXX
|
||||
* 4、将拼接出来的字符串连接上apb_nonce的值即AAAAAAAAAA。再连接 password=XXXXXXXusername=XXXXXAAAAAAAAAA
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String createSign(String content, String characterEncoding) {
|
||||
return SignUtils.valueOf(payConfigStorage.getSignType().toUpperCase()).createSign(content, payConfigStorage.getKeyPublic(), characterEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param parameterMap 请求参数
|
||||
* @param is 请求流
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Map<String, String> getParameter2Map(Map<String, String[]> parameterMap, InputStream is) {
|
||||
Map<String,String> params = new TreeMap<>();
|
||||
for (Iterator iter = parameterMap.keySet().iterator(); iter.hasNext();) {
|
||||
String name = (String) iter.next();
|
||||
String[] values = parameterMap.get(name);
|
||||
String valueStr = "";
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
valueStr = (i == values.length - 1) ? valueStr + values[i]
|
||||
: valueStr + values[i] + ",";
|
||||
}
|
||||
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
|
||||
//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
|
||||
params.put(name, valueStr.trim());
|
||||
}
|
||||
|
||||
return params;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 具体需要返回的数据为
|
||||
*return_code 返回码只有SUCCESS和FAIL
|
||||
*return_msg 返回具体信息
|
||||
*nonce_str 您的服务器新生成随机生成32位字符串
|
||||
*sign 为签名,签名规则是您需要发送的所有数据(除了sign)按照字典升序排列后加上&key=xxxxxxxx您的密钥后md5加密,最后转成小写
|
||||
*最后把得到的所有需要返回的数据用json格式化成json对象格式如下
|
||||
*{‘return_code’:’SUCCESS’,’return_msg’:’ok’,’nonce_str’:’dddddddddddddddddddd’,’sign’:’sdddddddddddddddddd’}
|
||||
* @param code return_code
|
||||
* @param message return_msg
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public PayOutMessage getPayOutMessage(String code, String message) {
|
||||
|
||||
JsonBuilder builder = PayOutMessage.JSON()
|
||||
.content("return_code", code.toUpperCase())
|
||||
.content("return_msg", message)
|
||||
.content("nonce_str", SignUtils.randomStr());
|
||||
return builder.content("sign", SignUtils.valueOf(payConfigStorage.getSignType()).sign(builder.getJson(), "&key=" + payConfigStorage.getKeyPrivate(), payConfigStorage.getInputCharset())).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对web端的即时付款
|
||||
* 暂未实现或无此功能
|
||||
* @param orderInfo 发起支付的订单信息
|
||||
* @param method 请求方式 "post" "get",
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String buildRequest(Map<String, Object> orderInfo, MethodType method) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedImage genQrPay(Map<String, Object> orderInfo) {
|
||||
return MatrixToImageWriter.writeInfoToJpgBuff((String) orderInfo.get("code_url"));
|
||||
}
|
||||
|
||||
public WxYouDianPayService(PayConfigStorage payConfigStorage) {
|
||||
setPayConfigStorage(payConfigStorage);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package in.egan.pay.wx.youdian.bean;
|
||||
|
||||
import in.egan.pay.common.bean.TransactionType;
|
||||
|
||||
/**
|
||||
* 友店交易类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/01/12 22:58
|
||||
*/
|
||||
public enum YoudianTransactionType implements TransactionType {
|
||||
|
||||
//扫码付
|
||||
NATIVE,
|
||||
//刷卡付
|
||||
MICROPAY;//暂未接触
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return this.name();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package in.egan.pay.wx.youdian.utils;
|
||||
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.http.Utf8ResponseHandler;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
/**
|
||||
* 简单的GET请求执行器,请求的参数是String, 返回的结果JSONObject
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2017/01/12 22:58
|
||||
*/
|
||||
public class SimpleGetRequestExecutor implements RequestExecutor<JSONObject, String> {
|
||||
|
||||
@Override
|
||||
public JSONObject execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws IOException, PayErrorException {
|
||||
if (queryParam != null) {
|
||||
if (uri.indexOf('?') == -1) {
|
||||
uri += '?';
|
||||
}
|
||||
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
|
||||
}
|
||||
HttpGet httpGet = new HttpGet(uri);
|
||||
if (httpProxy != null) {
|
||||
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
|
||||
httpGet.setConfig(config);
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
|
||||
String text = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
JSONObject jsonObject = JSON.parseObject(text);
|
||||
PayError payError = new PayError(jsonObject.getIntValue("errorcode"), jsonObject.getString("msg"), text);
|
||||
if (0 != payError.getErrorCode()){
|
||||
throw new PayErrorException(payError);
|
||||
}
|
||||
return jsonObject;
|
||||
}finally {
|
||||
httpGet.releaseConnection();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
29
pay-java-wx/pom.xml
Normal file
29
pay-java-wx/pom.xml
Normal file
@@ -0,0 +1,29 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<artifactId>pay-java-parent</artifactId>
|
||||
<groupId>in.egan</groupId>
|
||||
<version>2.0.SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>pay-java-wx</artifactId>
|
||||
|
||||
<dependencies>
|
||||
|
||||
|
||||
<!-- pay-java -->
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-common</artifactId>
|
||||
</dependency>
|
||||
<!-- /pay-java -->
|
||||
|
||||
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,63 @@
|
||||
package in.egan.pay.wx.api;
|
||||
|
||||
import in.egan.pay.common.api.BasePayConfigStorage;
|
||||
|
||||
/**
|
||||
* 支付客户端配置存储
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class WxPayConfigStorage extends BasePayConfigStorage {
|
||||
|
||||
|
||||
public String appSecret;
|
||||
public String appid ;
|
||||
public String mchId;// 商户号
|
||||
|
||||
|
||||
@Override
|
||||
public String getSecretKey() {
|
||||
return appSecret;
|
||||
}
|
||||
|
||||
public void setAppSecret(String appSecret) {
|
||||
this.appSecret = appSecret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAppid() {
|
||||
return appid;
|
||||
}
|
||||
|
||||
public void setAppid(String appid) {
|
||||
this.appid = appid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPartner() {
|
||||
return mchId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSeller() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMchId() {
|
||||
return mchId;
|
||||
}
|
||||
|
||||
public void setMchId(String mchId) {
|
||||
this.mchId = mchId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
336
pay-java-wx/src/main/java/in/egan/pay/wx/api/WxPayService.java
Normal file
336
pay-java-wx/src/main/java/in/egan/pay/wx/api/WxPayService.java
Normal file
@@ -0,0 +1,336 @@
|
||||
package in.egan.pay.wx.api;
|
||||
|
||||
import in.egan.pay.common.api.PayConfigStorage;
|
||||
import in.egan.pay.common.api.PayService;
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.MethodType;
|
||||
import in.egan.pay.common.bean.PayOrder;
|
||||
import in.egan.pay.common.bean.PayOutMessage;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.MatrixToImageWriter;
|
||||
import in.egan.pay.common.util.sign.SignUtils;
|
||||
import in.egan.pay.common.util.str.StringUtils;
|
||||
import in.egan.pay.wx.bean.WxTransactionType;
|
||||
import in.egan.pay.wx.utils.SimplePostRequestExecutor;
|
||||
import in.egan.pay.common.util.XML;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 支付宝支付通知
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class WxPayService implements PayService {
|
||||
protected final Log log = LogFactory.getLog(WxPayService.class);
|
||||
|
||||
protected PayConfigStorage payConfigStorage;
|
||||
|
||||
protected CloseableHttpClient httpClient;
|
||||
|
||||
protected HttpHost httpProxy;
|
||||
|
||||
private int retrySleepMillis = 1000;
|
||||
|
||||
private int maxRetryTimes = 5;
|
||||
|
||||
public final static String httpsVerifyUrl = "https://gw.tenpay.com/gateway";
|
||||
public final static String unifiedOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
|
||||
// public final static String orderqueryUrl = "https://api.mch.weixin.qq.com/pay/orderquery";
|
||||
|
||||
/**
|
||||
* 微信支付V2版本所需
|
||||
* 当前版本不需要
|
||||
* @return
|
||||
*/
|
||||
@Deprecated
|
||||
@Override
|
||||
public String getHttpsVerifyUrl() {
|
||||
return httpsVerifyUrl + "/verifynotifyid.xml";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(Map<String, String> params) {
|
||||
if (!"SUCCESS".equals(params.get("return_code"))){
|
||||
log.debug(String.format("微信支付异常:return_code=%s,参数集=%s", params.get("return_code"), params));
|
||||
return false;
|
||||
}
|
||||
|
||||
if(params.get("sign") == null) {
|
||||
|
||||
log.debug("微信支付异常:签名为空!out_trade_no=" + params.get("out_trade_no"));
|
||||
}
|
||||
|
||||
try {
|
||||
return getSignVerify(params, params.get("sign")) && "true".equals(verifyUrl(params.get("out_trade_no")));
|
||||
} catch (PayErrorException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 根据反馈回来的信息,生成签名结果
|
||||
* @param params 通知返回来的参数数组
|
||||
* @param sign 比对的签名结果
|
||||
* @return 生成的签名结果
|
||||
*/
|
||||
public boolean getSignVerify(Map<String, String> params, String sign) {
|
||||
return SignUtils.valueOf(payConfigStorage.getSignType()).verify(params, sign, "&key=" + payConfigStorage.getKeyPublic(), payConfigStorage.getInputCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付宝需要,暂时预留
|
||||
* @param out_trade_no 商户单号
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
@Override
|
||||
public String verifyUrl(String out_trade_no) throws PayErrorException {
|
||||
// return execute(new SimplePostRequestExecutor(), getHttpsVerifyUrl(), "partner=" + payConfigStorage.getPartner() + "¬ify_id=" + notify_id);
|
||||
|
||||
return "true";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 向支付端发送请求,在这里执行的策略是当发生access_token过期时才去刷新,然后重新执行请求,而不是全局定时请求
|
||||
*
|
||||
* @param executor
|
||||
* @param uri
|
||||
* @param data
|
||||
* @return
|
||||
* @throws PayErrorException
|
||||
*/
|
||||
@Override
|
||||
public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException {
|
||||
int retryTimes = 0;
|
||||
do {
|
||||
try {
|
||||
return executeInternal(executor, uri, data);
|
||||
} catch (PayErrorException e) {
|
||||
PayError error = e.getError();
|
||||
if (error.getErrorCode() == 403) {
|
||||
int sleepMillis = retrySleepMillis * (1 << retryTimes);
|
||||
try {
|
||||
log.debug(String.format("微信支付系统繁忙,(%s)ms 后重试(第%s次)", sleepMillis, retryTimes + 1));
|
||||
Thread.sleep(sleepMillis);
|
||||
} catch (InterruptedException e1) {
|
||||
throw new RuntimeException(e1);
|
||||
}
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
} while (++retryTimes < maxRetryTimes);
|
||||
|
||||
throw new PayErrorException(new PayError(-1, "微信支付服务端异常,超出重试次数"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取支付平台所需的订单信息
|
||||
*
|
||||
* @param order 支付订单
|
||||
* @return
|
||||
* @see in.egan.pay.common.bean.PayOrder
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> orderInfo(PayOrder order) {
|
||||
|
||||
|
||||
// Map<String, Object> results = new HashMap<String, Object>();
|
||||
////统一下单
|
||||
SortedMap<String, Object> parameters = new TreeMap<String, Object>();
|
||||
parameters.put("appid", payConfigStorage.getAppid());
|
||||
parameters.put("mch_id", payConfigStorage.getPartner());
|
||||
parameters.put("nonce_str", SignUtils.randomStr());
|
||||
parameters.put("body", order.getSubject());// 购买支付信息
|
||||
parameters.put("notify_url", payConfigStorage.getNotifyUrl());
|
||||
parameters.put("out_trade_no", order.getTradeNo());// 订单号
|
||||
parameters.put("spbill_create_ip", "192.168.1.150");
|
||||
parameters.put("total_fee", order.getPrice().multiply(new BigDecimal(100)).intValue());// 总金额单位为分
|
||||
parameters.put("trade_type", order.getTransactionType().getType());
|
||||
parameters.put("attach", order.getBody());
|
||||
if (WxTransactionType.NATIVE == order.getTransactionType()){
|
||||
parameters.put("product_id", order.getTradeNo());
|
||||
}
|
||||
String sign = createSign(SignUtils.parameterText(parameters), payConfigStorage.getInputCharset());
|
||||
parameters.put("sign", sign);
|
||||
|
||||
String requestXML = XML.getMap2Xml(parameters);
|
||||
log.debug("requestXML:" + requestXML);
|
||||
String result = null;
|
||||
try {
|
||||
result = execute(new SimplePostRequestExecutor(), unifiedOrderUrl, requestXML);
|
||||
log.debug("获取预支付订单返回结果33:" + result);
|
||||
|
||||
/////////APP端调起支付的参数列表
|
||||
Map map = XML.toJSONObject(result);
|
||||
if (!"SUCCESS".equals(map.get("return_code"))){
|
||||
throw new PayErrorException(new PayError(-1, (String) map.get("return_msg"), result));
|
||||
}
|
||||
//如果是扫码支付无需处理,直接返回
|
||||
if (WxTransactionType.NATIVE == order.getTransactionType()){
|
||||
return map;
|
||||
}
|
||||
|
||||
SortedMap<String, Object> params = new TreeMap<String, Object>();
|
||||
params.put("appid", payConfigStorage.getAppid());
|
||||
params.put("partnerid", payConfigStorage.getPartner());
|
||||
params.put("prepayid", map.get("prepay_id"));
|
||||
params.put("timestamp", System.currentTimeMillis() / 1000);
|
||||
params.put("noncestr", map.get("nonce_str")/*WxpayCore.genNonceStr()*/);
|
||||
|
||||
if (WxTransactionType.JSAPI == order.getTransactionType()){
|
||||
params.put("package", "prepay_id=" + map.get("prepay_id"));
|
||||
params.put("signType", payConfigStorage.getSignType());
|
||||
}else if (WxTransactionType.APP == order.getTransactionType()){
|
||||
params.put("package", "Sign=WXPay");
|
||||
}
|
||||
String paySign = createSign(SignUtils.parameterText(params), payConfigStorage.getInputCharset());
|
||||
params.put("sign", paySign);
|
||||
return params;
|
||||
} catch (PayErrorException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
// result = WxpayCore.httpsRequest2(httpsVerifyUrl, "POST", requestXML);
|
||||
//////////////////////////
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 签名
|
||||
* @param content 需要签名的内容 不包含key
|
||||
* @param characterEncoding 字符编码
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String createSign(String content, String characterEncoding) {
|
||||
return SignUtils.valueOf(payConfigStorage.getSignType().toUpperCase()).createSign(content, "&key=" + payConfigStorage.getKeyPrivate(), characterEncoding).toUpperCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getParameter2Map(Map<String, String[]> parameterMap, InputStream is) {
|
||||
TreeMap<String, String> map = new TreeMap();
|
||||
try {
|
||||
return XML.inputStream2Map(is, map);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public PayOutMessage getPayOutMessage(String code, String message) {
|
||||
return PayOutMessage.XML().code(code.toUpperCase()).content(message).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对web端的即时付款
|
||||
* 暂未实现或无此功能
|
||||
* @param orderInfo 发起支付的订单信息
|
||||
* @param method 请求方式 "post" "get",
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String buildRequest(Map<String, Object> orderInfo, MethodType method) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedImage genQrPay(Map<String, Object> orderInfo) {
|
||||
//获取对应的支付账户操作工具(可根据账户id)
|
||||
if (!"SUCCESS".equals(orderInfo.get("result_code"))){
|
||||
throw new RuntimeException(new PayError(-1, (String) orderInfo.get("err_code")).toString());
|
||||
}
|
||||
|
||||
|
||||
return MatrixToImageWriter.writeInfoToJpgBuff((String) orderInfo.get("code_url"));
|
||||
}
|
||||
|
||||
|
||||
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws PayErrorException {
|
||||
|
||||
try {
|
||||
return executor.execute(getHttpClient(), httpProxy, uri, data);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public HttpHost getHttpProxy() {
|
||||
return httpProxy;
|
||||
}
|
||||
|
||||
public CloseableHttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置支付配置
|
||||
* @param payConfigStorage 支付配置
|
||||
*/
|
||||
public void setPayConfigStorage(PayConfigStorage payConfigStorage) {
|
||||
this.payConfigStorage = payConfigStorage;
|
||||
|
||||
String http_proxy_host = payConfigStorage.getHttpProxyHost();
|
||||
int http_proxy_port = payConfigStorage.getHttpProxyPort();
|
||||
String http_proxy_username = payConfigStorage.getHttpProxyUsername();
|
||||
String http_proxy_password = payConfigStorage.getHttpProxyPassword();
|
||||
|
||||
if (StringUtils.isNotBlank(http_proxy_host)) {
|
||||
// 使用代理服务器
|
||||
if (StringUtils.isNotBlank(http_proxy_username)) {
|
||||
// 需要用户认证的代理服务器
|
||||
CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
credsProvider.setCredentials(
|
||||
new AuthScope(http_proxy_host, http_proxy_port),
|
||||
new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
|
||||
httpClient = HttpClients
|
||||
.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider)
|
||||
.build();
|
||||
} else {
|
||||
// 无需用户认证的代理服务器
|
||||
httpClient = HttpClients.createDefault();
|
||||
}
|
||||
httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
|
||||
} else {
|
||||
httpClient = HttpClients.createDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayConfigStorage getPayConfigStorage() {
|
||||
return payConfigStorage;
|
||||
}
|
||||
|
||||
public WxPayService() {
|
||||
}
|
||||
|
||||
public WxPayService(PayConfigStorage payConfigStorage) {
|
||||
setPayConfigStorage(payConfigStorage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package in.egan.pay.wx.bean;
|
||||
|
||||
import in.egan.pay.common.bean.TransactionType;
|
||||
|
||||
/**
|
||||
* 微信交易类型
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016/10/19 22:58
|
||||
*/
|
||||
public enum WxTransactionType implements TransactionType {
|
||||
//公众号支付
|
||||
JSAPI,//暂未接触
|
||||
//扫码付
|
||||
NATIVE,
|
||||
//移动支付
|
||||
APP,
|
||||
//刷卡付
|
||||
MICROPAY;//暂未接触
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return this.name();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package in.egan.pay.wx.utils;
|
||||
|
||||
import in.egan.pay.common.api.RequestExecutor;
|
||||
import in.egan.pay.common.bean.result.PayError;
|
||||
import in.egan.pay.common.exception.PayErrorException;
|
||||
import in.egan.pay.common.util.XML;
|
||||
import in.egan.pay.common.util.http.Utf8ResponseHandler;
|
||||
import org.apache.http.Consts;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
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 java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author egan
|
||||
* @email egzosn@gmail.com
|
||||
* @date 2016-5-18 14:09:01
|
||||
*/
|
||||
public class SimplePostRequestExecutor implements RequestExecutor<String, String> {
|
||||
|
||||
@Override
|
||||
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String postEntity) throws PayErrorException, ClientProtocolException, IOException {
|
||||
HttpPost httpPost = new HttpPost(uri);
|
||||
if (httpProxy != null) {
|
||||
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
|
||||
httpPost.setConfig(config);
|
||||
}
|
||||
|
||||
if (postEntity != null) {
|
||||
StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
|
||||
httpPost.setEntity(entity);
|
||||
}
|
||||
|
||||
|
||||
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
|
||||
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
/* Map<String, Object> map = XML.toMap(responseContent);
|
||||
|
||||
PayError error = PayError.fromMap(map);
|
||||
if (null != error) {
|
||||
throw new PayErrorException(error);
|
||||
}*/
|
||||
return responseContent;
|
||||
}
|
||||
|
||||
/* CloseableHttpResponse response = null;
|
||||
try {
|
||||
response = httpclient.execute(httpPost);
|
||||
// String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
|
||||
Map<String, Object> map = XML.toMap(responseContent);
|
||||
|
||||
PayError error = PayError.fromMap(map);
|
||||
if (null != error) {
|
||||
throw new PayErrorException(error);
|
||||
}
|
||||
return responseContent;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}finally {
|
||||
if (response != null) {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
return null;*/
|
||||
}
|
||||
|
||||
}
|
||||
96
pom.xml
Normal file
96
pom.xml
Normal file
@@ -0,0 +1,96 @@
|
||||
<?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>in.egan</groupId>
|
||||
<artifactId>pay-java-parent</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>2.0.SNAPSHOT</version>
|
||||
|
||||
<name>Pay Java Tools - Parent</name>
|
||||
<description>支付宝支付、微信支付上级POM</description>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>The Apache License, Version 2.0</name>
|
||||
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
|
||||
</license>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer>
|
||||
<name>Egan</name>
|
||||
<email>egzosn@gmail.com</email>
|
||||
<url>https://github.com/egzosn/pay-java-parent</url>
|
||||
</developer>
|
||||
</developers>
|
||||
|
||||
<modules>
|
||||
<module>pay-java-common</module>
|
||||
<module>pay-java-ali</module>
|
||||
<module>pay-java-wx</module>
|
||||
<module>pay-java-demo</module>
|
||||
<module>pay-java-wx-youdian</module>
|
||||
</modules>
|
||||
|
||||
|
||||
<properties>
|
||||
<httpmime.version>4.5.2</httpmime.version>
|
||||
<log4j.version>1.2.17</log4j.version>
|
||||
<pay.version>2.0.SNAPSHOT</pay.version>
|
||||
</properties>
|
||||
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>in.egan</groupId>
|
||||
<artifactId>pay-java-common</artifactId>
|
||||
<version>${pay.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--httpcomponents-->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>${httpmime.version}</version>
|
||||
</dependency>
|
||||
<!--/httpcomponents-->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- log4j -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<!-- / log4j -->
|
||||
<dependency>
|
||||
<groupId>org.jdom</groupId>
|
||||
<artifactId>jdom</artifactId>
|
||||
<version>2.0.2</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Reference in New Issue
Block a user