mirror of
https://gitee.com/egzosn/pay-java-parent.git
synced 2026-05-13 00:49:58 +08:00
初始版本
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user