Commit 324ccaaf authored by jmdhappy's avatar jmdhappy
Browse files

初始化提交

parents
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.xxpay</groupId>
<artifactId>xxpay-common</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>xxpay-common</name>
<description>xxpay-master</description>
<properties>
<fastjson.version>1.2.7</fastjson.version>
</properties>
<dependencies>
<!-- Logging -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies>
<build>
<finalName>xxpay-common</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource> <!-- 配置需要被替换的资源文件路径 -->
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
package org.xxpay.common.constant;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: 支付常量类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class PayConstant {
public final static String PAY_CHANNEL_WX_JSAPI = "WX_JSAPI"; // 微信公众号支付
public final static String PAY_CHANNEL_WX_NATIVE = "WX_NATIVE"; // 微信原生扫码支付
public final static String PAY_CHANNEL_WX_APP = "WX_APP"; // 微信APP支付
public final static String PAY_CHANNEL_IAP = "IAP"; // 苹果应用内支付
public final static String PAY_CHANNEL_ALIPAY_MOBILE = "ALIPAY_MOBILE"; // 支付宝移动支付
public final static String PAY_CHANNEL_ALIPAY_PC = "ALIPAY_PC"; // 支付宝PC支付
public final static String PAY_CHANNEL_ALIPAY_WAP = "ALIPAY_WAP"; // 支付宝WAP支付
public final static String TRANS_CHANNEL_WX_APP = "TRANS_WX_APP"; // 微信APP转账
public final static String TRANS_CHANNEL_WX_JSAPI = "TRANS_WX_JSAPI"; // 微信公众号转账
public final static byte PAY_STATUS_EXPIRED = -2; // 订单过期
public final static byte PAY_STATUS_FAILED = -1; // 支付失败
public final static byte PAY_STATUS_INIT = 0; // 初始态
public final static byte PAY_STATUS_PAYING = 1; // 支付中
public final static byte PAY_STATUS_SUCCESS = 2; // 支付成功
public final static byte PAY_STATUS_COMPLETE = 3; // 业务完成
public final static byte TRANS_STATUS_INIT = 0; // 初始态
public final static byte TRANS_STATUS_TRANING = 1; // 转账中
public final static byte TRANS_STATUS_SUCCESS = 2; // 成功
public final static byte TRANS_STATUS_FAIL = 3; // 失败
public final static byte TRANS_STATUS_COMPLETE = 4; // 业务完成
public final static String RESP_UTF8 = "UTF-8"; // 通知业务系统使用的编码
public static final String RETURN_PARAM_RETCODE = "retCode";
public static final String RETURN_PARAM_RETMSG = "retMsg";
public static final String RESULT_PARAM_RESCODE = "resCode";
public static final String RESULT_PARAM_ERRCODE = "errCode";
public static final String RESULT_PARAM_ERRCODEDES = "errCodeDes";
public static final String RESULT_PARAM_SIGN = "sign";
public static final String RETURN_VALUE_SUCCESS = "SUCCESS";
public static final String RETURN_VALUE_FAIL = "FAIL";
public static final String RETURN_ALIPAY_VALUE_SUCCESS = "success";
public static final String RETURN_ALIPAY_VALUE_FAIL = "failed";
public static class JdConstant {
public final static String CONFIG_PATH = "jd" + File.separator + "jd"; // 京东支付配置文件路径
}
public static class WxConstant {
public final static String TRADE_TYPE_APP = "APP"; // APP支付
public final static String TRADE_TYPE_JSPAI = "JSAPI"; // 公众号支付
public final static String TRADE_TYPE_NATIVE = "NATIVE"; // 原生扫码支付
}
public static class IapConstant {
public final static String CONFIG_PATH = "iap" + File.separator + "iap"; // 苹果应用内支付
}
public static class AlipayConstant {
public final static String CONFIG_PATH = "alipay" + File.separator + "alipay"; // 支付宝移动支付
public final static String TRADE_STATUS_WAIT = "WAIT_BUYER_PAY"; // 交易创建,等待买家付款
public final static String TRADE_STATUS_CLOSED = "TRADE_CLOSED"; // 交易关闭
public final static String TRADE_STATUS_SUCCESS = "TRADE_SUCCESS"; // 交易成功
public final static String TRADE_STATUS_FINISHED = "TRADE_FINISHED"; // 交易成功且结束
}
public static final String NOTIFY_BUSI_PAY = "NOTIFY_VV_PAY_RES";
public static final String NOTIFY_BUSI_TRANS = "NOTIFY_VV_TRANS_RES";
}
package org.xxpay.common.constant;
/**
* @Description: 支付返回码定义
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public enum PayEnum {
/*
0010|系统错误 |系统超时或异常|系统异常,请用相同参数重新调用
0011|请使用post方法 |未使用post传递参数|请检查请求参数是否通过post方法提交
0012|post数据为空 |post数据不能为空|请检查post数据是否为空
0013|签名错误 |参数签名结果不正确|请检查签名参数和方法是否都符合签名算法要求
0014|参数错误 |缺少参数或参数格式不正确|请根据具体的原因检查参数
0015|商户不存在 |传入的商户ID在支付中心不存在|请检查mchID参数是否正确
0110|第三方超时 |调用第三方支付系统超时|请重新调用
0111|第三方异常 |调用第三方支付系统异常|根据提示错误信息检查
0112|订单不存在 |商户订单不存在|请检查商户订单payOrderId参数
0113|订单已支付 |商户订单已支付,无需重复操作|商户订单已支付,无需重复操作
*/
ERR_0001("0001", "商户签名异常"),
ERR_0010("0010", "系统错误"),
ERR_0011("0011", "请使用post方法"),
ERR_0012("0012", "post数据为空"),
ERR_0013("0013", "签名错误"),
ERR_0014("0014", "参数错误"),
ERR_0015("0015", "商户不存在"),
ERR_0110("0110", "第三方超时"),
ERR_0111("0111", "第三方异常"),
ERR_0112("0112", "订单不存在"),
ERR_0113("0113", "订单已支付"),
ERR_0114("0114", "商品不存在"),
ERR_0115("0115", "价格不对"),
ERR_0116("0116", "物品数量不对"),
ERR_0117("0117", "过程返回255"),
ERR_0118("0118", "DB错误");
private String code;
private String message;
PayEnum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode()
{
return this.code;
}
public String getMessage() {
return this.message;
}
}
package org.xxpay.common.util;
import java.text.DecimalFormat;
import java.text.FieldPosition;
/**
* @Description: 金额工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class AmountUtil {
/**
* 将字符串"元"转换成"分"
* @param str
* @return
*/
public static String convertDollar2Cent(String str) {
DecimalFormat df = new DecimalFormat("0.00");
StringBuffer sb = df.format(Double.parseDouble(str),
new StringBuffer(), new FieldPosition(0));
int idx = sb.toString().indexOf(".");
sb.deleteCharAt(idx);
for (; sb.length() != 1;) {
if(sb.charAt(0) == '0') {
sb.deleteCharAt(0);
} else {
break;
}
}
return sb.toString();
}
/**
* 将字符串"分"转换成"元"(长格式),如:100分被转换为1.00元。
* @param s
* @return
*/
public static String convertCent2Dollar(String s) {
if("".equals(s) || s ==null){
return "";
}
long l;
if(s.length() != 0) {
if(s.charAt(0) == '+') {
s = s.substring(1);
}
l = Long.parseLong(s);
} else {
return "";
}
boolean negative = false;
if(l < 0) {
negative = true;
l = Math.abs(l);
}
s = Long.toString(l);
if(s.length() == 1)
return(negative ? ("-0.0" + s) : ("0.0" + s));
if(s.length() == 2)
return(negative ? ("-0." + s) : ("0." + s));
else
return(negative ? ("-" + s.substring(0, s.length() - 2) + "." + s
.substring(s.length() - 2)) : (s.substring(0,
s.length() - 2)
+ "." + s.substring(s.length() - 2)));
}
/**
* 将字符串"分"转换成"元"(短格式),如:100分被转换为1元。
* @param s
* @return
*/
public static String convertCent2DollarShort(String s) {
String ss = convertCent2Dollar(s);
ss = "" + Double.parseDouble(ss);
if(ss.endsWith(".0"))
return ss.substring(0, ss.length() - 2);
if(ss.endsWith(".00"))
return ss.substring(0, ss.length() - 3);
else
return ss;
}
}
package org.xxpay.common.util;
import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Description: 日期时间工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class DateUtil {
public static final String FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_YYYYMMDDHHMMSSSSS = "yyyyMMddhhmmssSSS";
public static final String FORMAT_YYYYMMDDHHMMSS = "yyyyMMddhhmmss";
public static String getCurrentDate() {
String formatPattern_Short = "yyyyMMddhhmmss";
SimpleDateFormat format = new SimpleDateFormat(formatPattern_Short);
return format.format(new Date());
}
public static String getSeqString() {
SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddHHmmss"); // "yyyyMMdd G
return fm.format(new Date());
}
public static Timestamp getCurrentTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* 获取当前时间,格式为 yyyyMMddHHmmss
*
* @return
*/
public static String getCurrentTimeStr(String format) {
format = StringUtils.isBlank(format) ? FORMAT_YYYY_MM_DD_HH_MM_SS : format;
Date now = new Date();
return date2Str(now, format);
}
public static String date2Str(Date date) {
return date2Str(date, FORMAT_YYYY_MM_DD_HH_MM_SS);
}
/**
* 时间转换成 Date 类型
*
* @param date
* @param format
* @return
*/
public static String date2Str(Date date, String format) {
if ((format == null) || format.equals("")) {
format = FORMAT_YYYY_MM_DD_HH_MM_SS;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
if (date != null) {
return sdf.format(date);
}
return "";
}
/**
* 获取批量付款预约时间
* @return
*/
public static String getRevTime() {
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
String dateString = new SimpleDateFormat(DateUtil.FORMAT_YYYYMMDDHHMMSS).format(cal.getTime());
System.out.println(dateString);
return dateString;
}
/**
* 时间比较
* @param date1
* @param date2
* @return DATE1>DATE2返回1,DATE1<DATE2返回-1,等于返回0
*/
public static int compareDate(String date1, String date2, String format) {
DateFormat df = new SimpleDateFormat(format);
try {
Date dt1 = df.parse(date1);
Date dt2 = df.parse(date2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
/**
* 把给定的时间减掉给定的分钟数
* @param date
* @param minute
* @return
*/
public static Date minusDateByMinute(Date date, int minute) {
Date newDate = new Date(date.getTime() - (minute * 60 * 1000));
return newDate;
}
}
package org.xxpay.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class HttpClient {
private static final String USER_AGENT_VALUE =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";
private static final String JKS_CA_FILENAME =
"tenpay_cacert.jks";
private static final String JKS_CA_ALIAS = "tenpay";
private static final String JKS_CA_PASSWORD = "";
private static Logger _log = LoggerFactory.getLogger(HttpClient.class);
/**
* ca证书文件
*/
private File caFile;
/**
* 证书文件
*/
private File certFile;
/**
* 证书密码
*/
private String certPasswd;
/**
* 请求内容,无论post和get,都用get方式提供
*/
private String reqContent;
/**
* 应答内容
*/
private String resContent;
/**
* 请求方法
*/
private String method;
/**
* 错误信息
*/
private String errInfo;
/**
* 超时时间,以秒为单位
*/
private int timeOut;
/**
* http应答编码
*/
private int responseCode;
/**
* 字符编码
*/
private String charset;
private InputStream inputStream;
public HttpClient() {
this.caFile = null;
this.certFile = null;
this.certPasswd = "";
this.reqContent = "";
this.resContent = "";
this.method = "POST";
this.errInfo = "";
this.timeOut = 30;//30秒
this.responseCode = 0;
this.charset = "UTF-8";
this.inputStream = null;
}
public HttpClient(String url, String method, int timeOut, String charset) {
this.caFile = null;
this.certFile = null;
this.certPasswd = "";
this.reqContent = url;
this.resContent = "";
this.method = method;
this.errInfo = "";
this.timeOut = timeOut;//30秒
this.responseCode = 0;
this.charset = charset;
this.inputStream = null;
}
/**
* 设置证书信息
*
* @param certFile 证书文件
* @param certPasswd 证书密码
*/
public void setCertInfo(File certFile, String certPasswd) {
this.certFile = certFile;
this.certPasswd = certPasswd;
}
/**
* 设置ca
*
* @param caFile
*/
public void setCaInfo(File caFile) {
this.caFile = caFile;
}
/**
* 设置请求内容
*
* @param reqContent 表求内容
*/
public void setReqContent(String reqContent) {
this.reqContent = reqContent;
}
/**
* 获取结果内容
*
* @return String
* @throws IOException
*/
public String getResContent() {
try {
this.doResponse();
} catch (IOException e) {
_log.error("", e);
this.errInfo = e.getMessage();
//return "";
}
return this.resContent;
}
/**
* 设置请求方法post或者get
*
* @param method 请求方法post/get
*/
public void setMethod(String method) {
this.method = method;
}
/**
* 获取错误信息
*
* @return String
*/
public String getErrInfo() {
return this.errInfo;
}
/**
* 设置超时时间,以秒为单位
*
* @param timeOut 超时时间,以秒为单位
*/
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
/**
* 获取http状态码
*
* @return int
*/
public int getResponseCode() {
return this.responseCode;
}
/**
* 执行http调用。true:成功 false:失败
*
* @return boolean
*/
public boolean call() {
boolean isRet = false;
//http
if (null == this.caFile && null == this.certFile) {
try {
this.callHttp();
isRet = true;
} catch (IOException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (Exception e) {
_log.error("", e);
this.errInfo = e.getMessage();
}
return isRet;
}
//https
return calls();
}
public boolean calls() {
boolean isRet = false;
//https
try {
this.callHttps();
isRet = true;
} catch (UnrecoverableKeyException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (KeyManagementException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (CertificateException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (KeyStoreException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (NoSuchAlgorithmException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (IOException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (Exception e) {
_log.error("", e);
this.errInfo = e.getMessage();
}
return isRet;
}
protected void callHttp() throws IOException {
if ("POST".equals(this.method.toUpperCase())) {
String url = HttpClientUtil.getURL(this.reqContent);
String queryString = HttpClientUtil.getQueryString(this.reqContent);
byte[] postData = queryString.getBytes(this.charset);
this.httpPostMethod(url, postData);
return;
}
this.httpGetMethod(this.reqContent);
}
protected void callHttps() throws IOException, CertificateException,
KeyStoreException, NoSuchAlgorithmException,
UnrecoverableKeyException, KeyManagementException {
// ca目录
/*String caPath = this.caFile.getParent();
File jksCAFile = new File(caPath + "/"
+ HttpClient.JKS_CA_FILENAME);
if (!jksCAFile.isFile()) {
X509Certificate cert = (X509Certificate) HttpClientUtil
.getCertificate(this.caFile);
FileOutputStream out = new FileOutputStream(jksCAFile);
// store jks file
HttpClientUtil.storeCACert(cert, HttpClient.JKS_CA_ALIAS,
HttpClient.JKS_CA_PASSWORD, out);
out.close();
}
FileInputStream trustStream = new FileInputStream(jksCAFile);
FileInputStream keyStream = new FileInputStream(this.certFile);*/
/*SSLContext sslContext = HttpClientUtil.getSSLContext(trustStream,
HttpClient.JKS_CA_PASSWORD, keyStream, this.certPasswd);*/
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()},
new java.security.SecureRandom());
//关闭流
//keyStream.close();
//trustStream.close();
if ("POST".equals(this.method.toUpperCase())) {
String url = HttpClientUtil.getURL(this.reqContent);
String queryString = HttpClientUtil.getQueryString(this.reqContent);
byte[] postData = queryString.getBytes(this.charset);
this.httpsPostMethod(url, postData, sslContext);
return;
}
this.httpsGetMethod(this.reqContent, sslContext);
}
/**
* 以http post方式通信
*
* @param url
* @param postData
* @throws IOException
*/
protected void httpPostMethod(String url, byte[] postData)
throws IOException {
HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url);
this.doPost(conn, postData);
}
/**
* 以http get方式通信
*
* @param url
* @throws IOException
*/
protected void httpGetMethod(String url) throws IOException {
HttpURLConnection httpConnection =
HttpClientUtil.getHttpURLConnection(url);
this.setHttpRequest(httpConnection);
httpConnection.setRequestMethod("GET");
this.responseCode = httpConnection.getResponseCode();
this.inputStream = httpConnection.getInputStream();
}
/**
* 以https get方式通信
*
* @param url
* @param sslContext
* @throws IOException
*/
protected void httpsGetMethod(String url, SSLContext sslContext)
throws IOException {
SSLSocketFactory sf = sslContext.getSocketFactory();
HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
conn.setSSLSocketFactory(sf);
this.doGet(conn);
}
protected void httpsPostMethod(String url, byte[] postData,
SSLContext sslContext) throws IOException {
SSLSocketFactory sf = sslContext.getSocketFactory();
HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
conn.setSSLSocketFactory(sf);
this.doPost(conn, postData);
}
/**
* 设置http请求默认属性
*
* @param httpConnection
*/
protected void setHttpRequest(HttpURLConnection httpConnection) {
//设置连接超时时间
httpConnection.setConnectTimeout(this.timeOut * 1000);
//User-Agent
httpConnection.setRequestProperty("User-Agent",
HttpClient.USER_AGENT_VALUE);
//不使用缓存
httpConnection.setUseCaches(false);
//允许输入输出
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
}
/**
* 处理应答
*
* @throws IOException
*/
protected void doResponse() throws IOException {
if (null == this.inputStream) {
return;
}
//获取应答内容
this.resContent = HttpClientUtil.InputStreamTOString(this.inputStream, this.charset);
//关闭输入流
this.inputStream.close();
}
/**
* post方式处理
*
* @param conn
* @param postData
* @throws IOException
*/
protected void doPost(HttpURLConnection conn, byte[] postData)
throws IOException {
// 以post方式通信
conn.setRequestMethod("POST");
// 设置请求默认属性
this.setHttpRequest(conn);
// Content-Type
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
BufferedOutputStream out = new BufferedOutputStream(conn
.getOutputStream());
final int len = 1024; // 1KB
HttpClientUtil.doOutput(out, postData, len);
/*PrintWriter out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(new String(postData));
// flush输出流的缓冲
out.flush();*/
// 关闭流
out.close();
// 获取响应返回状态码
this.responseCode = conn.getResponseCode();
// 获取应答输入流
this.inputStream = conn.getInputStream();
}
/**
* get方式处理
*
* @param conn
* @throws IOException
*/
protected void doGet(HttpURLConnection conn) throws IOException {
//以GET方式通信
conn.setRequestMethod("GET");
//设置请求默认属性
this.setHttpRequest(conn);
//获取响应返回状态码
this.responseCode = conn.getResponseCode();
//获取应答输入流
this.inputStream = conn.getInputStream();
}
public static String callHttpPost(String url) {
return callHttpPost(url, 60); // 默认超时时间60秒
}
public static String callHttpPost(String url, int connect_timeout) {
return callHttpPost(url, connect_timeout, "UTF-8"); // 默认编码 UTF-8
}
public static String callHttpPost(String url, int connect_timeout, String encode) {
HttpClient client = new HttpClient(url, "POST", connect_timeout, encode);
client.call();
return client.getResContent();
}
public static String callHttpsPost(String url) {
HttpClient client = new HttpClient(url, "POST", 60, "UTF-8");
client.calls();
return client.getResContent();
}
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
}
package org.xxpay.common.util;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class HttpClientUtil {
public static final String SunX509 = "SunX509";
public static final String JKS = "JKS";
public static final String PKCS12 = "PKCS12";
public static final String TLS = "TLS";
private static final String encoding = "UTF-8";
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* get HttpURLConnection
* @param strUrl url地址
* @return HttpURLConnection
* @throws IOException
*/
public static HttpURLConnection getHttpURLConnection(String strUrl)
throws IOException {
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
return httpURLConnection;
}
/**
* get HttpsURLConnection
* @param strUrl url地址
* @return HttpsURLConnection
* @throws IOException
*/
public static HttpsURLConnection getHttpsURLConnection(String strUrl)
throws IOException {
URL url = new URL(strUrl);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url
.openConnection();
return httpsURLConnection;
}
/**
* 获取不带查询串的url
* @param strUrl
* @return String
*/
public static String getURL(String strUrl) {
if(null != strUrl) {
int indexOf = strUrl.indexOf("?");
if(-1 != indexOf) {
return strUrl.substring(0, indexOf);
}
return strUrl;
}
return strUrl;
}
/**
* 获取查询串
* @param strUrl
* @return String
*/
public static String getQueryString(String strUrl) {
if(null != strUrl) {
int indexOf = strUrl.indexOf("?");
if(-1 != indexOf) {
return strUrl.substring(indexOf+1, strUrl.length());
}
return "";
}
return strUrl;
}
/**
* 查询字符串转换成Map<br/>
* name1=key1&name2=key2&...
* @param queryString
* @return
*/
public static Map queryString2Map(String queryString) {
if(null == queryString || "".equals(queryString)) {
return null;
}
Map m = new HashMap();
String[] strArray = queryString.split("&");
for(int index = 0; index < strArray.length; index++) {
String pair = strArray[index];
HttpClientUtil.putMapByPair(pair, m);
}
return m;
}
/**
* 把键值添加至Map<br/>
* pair:name=value
* @param pair name=value
* @param m
*/
public static void putMapByPair(String pair, Map m) {
if(null == pair || "".equals(pair)) {
return;
}
int indexOf = pair.indexOf("=");
if(-1 != indexOf) {
String k = pair.substring(0, indexOf);
String v = pair.substring(indexOf+1, pair.length());
if(null != k && !"".equals(k)) {
m.put(k, v);
}
} else {
m.put(pair, "");
}
}
/**
* BufferedReader转换成String<br/>
* 注意:流关闭需要自行处理
* @param reader
* @return String
* @throws IOException
*/
public static String bufferedReader2String(BufferedReader reader) throws IOException {
StringBuffer buf = new StringBuffer();
String line = null;
while( (line = reader.readLine()) != null) {
buf.append(line);
buf.append("\r\n");
}
return buf.toString();
}
/**
* 处理输出<br/>
* 注意:流关闭需要自行处理
* @param out
* @param data
* @param len
* @throws IOException
*/
public static void doOutput(OutputStream out, byte[] data, int len)
throws IOException {
int dataLen = data.length;
int off = 0;
while (off < data.length) {
if (len >= dataLen) {
out.write(data, off, dataLen);
off += dataLen;
} else {
out.write(data, off, len);
off += len;
dataLen -= len;
}
// 刷新缓冲区
out.flush();
}
}
/**
* 获取SSLContext
* @param trustPasswd
* @param keyPasswd
* @return
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
*/
public static SSLContext getSSLContext(
FileInputStream trustFileInputStream, String trustPasswd,
FileInputStream keyFileInputStream, String keyPasswd)
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, UnrecoverableKeyException,
KeyManagementException {
// ca
TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);
KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
trustKeyStore.load(trustFileInputStream, HttpClientUtil
.str2CharArray(trustPasswd));
tmf.init(trustKeyStore);
final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);
KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
ks.load(keyFileInputStream, kp);
kmf.init(ks, kp);
SecureRandom rand = new SecureRandom();
SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);
return ctx;
}
/**
* 获取CA证书信息
* @param cafile CA证书文件
* @return Certificate
* @throws CertificateException
* @throws IOException
*/
public static Certificate getCertificate(File cafile)
throws CertificateException, IOException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream(cafile);
Certificate cert = cf.generateCertificate(in);
in.close();
return cert;
}
/**
* 字符串转换成char数组
* @param str
* @return char[]
*/
public static char[] str2CharArray(String str) {
if(null == str) return null;
return str.toCharArray();
}
/**
* 存储ca证书成JKS格式
* @param cert
* @param alias
* @param password
* @param out
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws IOException
*/
public static void storeCACert(Certificate cert, String alias,
String password, OutputStream out) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
ks.setCertificateEntry(alias, cert);
// store keystore
ks.store(out, HttpClientUtil.str2CharArray(password));
}
public static InputStream String2Inputstream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
/**
* InputStream转换成Byte
* 注意:流关闭需要自行处理
* @param in
* @return byte
* @throws Exception
*/
public static byte[] InputStreamTOByte(InputStream in) throws IOException{
int BUFFER_SIZE = 4096;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while((count = in.read(data,0,BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = null;
byte[] outByte = outStream.toByteArray();
outStream.close();
return outByte;
}
/**
* InputStream转换成String
* 注意:流关闭需要自行处理
* @param in
* @param encoding 编码
* @return String
* @throws Exception
*/
public static String InputStreamTOString(InputStream in,String encoding) throws IOException{
return new String(InputStreamTOByte(in),encoding);
}
}
package org.xxpay.common.util;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @Description: IP地址工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class IPUtility {
/**
* getLocalhostIp(获取本机ip地址)
* @throws UnknownHostException
* @Exception 异常对象
* @since CodingExample Ver(编码范例查看) 1.1
*/
public static String getLocalhostIp() {
String ip = "";
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
return null;
}
return ip;
}
public static List<String> getIpAddrs() throws Exception {
List<String> IPs = new ArrayList<String>();
Enumeration<NetworkInterface> allNetInterfaces = null;
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration<?> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address && ip.getHostAddress().indexOf(".") != -1) {
IPs.add(ip.getHostAddress());
}
}
}
return IPs;
}
/**
* 兼容Linux系统
* @return
*/
public static String getLocalIP() {
String ip = "";
try {
Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address)
continue;
if (!ia.isLoopbackAddress()) {
ip = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
return "";
}
return ip;
}
public static void main(String[] args) throws Exception {
System.out.println(IPUtility.getLocalIP());
}
}
package org.xxpay.common.util;
/**
* @Description: base64编码解码工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MyBase64 {
public final static String encode(byte[] src, int startIndex, int srclen) {
if (src == null) return null;
if (startIndex+srclen>src.length) srclen = src.length-startIndex;
byte src2[] = new byte[srclen];
System.arraycopy(src, startIndex, src2, 0, srclen);
return encode(src2);
}
public final static String encode(byte[] src, int srclen) {
if (src == null) return null;
if (srclen>src.length) srclen = src.length;
byte data[] = new byte[srclen+2];
System.arraycopy(src, 0, data, 0, srclen);
byte dest[] = new byte[(data.length/3)*4];
// 3-byte to 4-byte conversion
for (int sidx = 0, didx=0; sidx < srclen; sidx += 3, didx += 4) {
dest[didx] = (byte) ((data[sidx] >>> 2) & 077);
dest[didx+1] = (byte) ((data[sidx+1] >>> 4) & 017 | (data[sidx] << 4) & 077);
dest[didx+2] = (byte) ((data[sidx+2] >>> 6) & 003 | (data[sidx+1] << 2) & 077);
dest[didx+3] = (byte) (data[sidx+2] & 077);
}
// 0-63 to ascii printable conversion
for (int idx = 0; idx <dest.length; idx++) {
if (dest[idx] < 26) dest[idx] = (byte)(dest[idx] + 'A');
else if (dest[idx] < 52) dest[idx] = (byte)(dest[idx] + 'a' - 26);
else if (dest[idx] < 62) dest[idx] = (byte)(dest[idx] + '0' - 52);
else if (dest[idx] < 63) dest[idx] = (byte)'+';
else dest[idx] = (byte)'/';
}
// add padding
for (int idx = dest.length-1; idx > (srclen*4)/3; idx--) {
dest[idx] = (byte)'=';
}
return new String(dest);
}
public final static String encode(byte[] d) {
return encode(d, d.length);
}
/** 每64字符后,换行 */
public static String encode_64(byte[] bin) throws Exception {
String b64 = MyBase64.encode(bin);
StringBuffer sb = new StringBuffer();
for(int offset=0; offset < b64.length(); offset+=64) {
int idx_begin = offset;
int idx_end = Math.min(offset+64, b64.length());
String s = b64.substring(idx_begin, idx_end);
sb.append(s).append('\n');
//if (withDebug) debug(idx_begin+"..."+idx_end);
}
b64 = sb.toString();
return b64;
}
public final static byte[] decode(String str) {
if (str == null) return new byte[0];
str = str.trim(); //TODO 去掉结尾空格,但还不彻底,可考虑进一步改善。。。
if (str.length()==0) return new byte[0];
return decode(str.getBytes());
}
private final static byte[] decode(byte[] data) {
int tail = data.length;
while (data[tail-1] == '=') tail--; //去掉结尾的等号
byte dest[] = new byte[tail - data.length/4];
for(int i = 0; i <data.length; i++) {// ascii printable to 0-63 conversion
data[i] = decode_pre_byte(data[i]); //TODO ??是否有用?
}
// 4-byte to 3-byte conversion
int sidx, didx;
for (sidx = 0, didx=0; didx < dest.length-2; sidx += 4, didx += 3) {
dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 3) );
dest[didx+1] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) );
dest[didx+2] = (byte) ( ((data[sidx+2] << 6) & 255) | ( data[sidx+3] & 077) );
}
if (didx < dest.length) {
dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 3) );
}
if (++didx < dest.length) {
dest[didx] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) );
}
return dest;
}
private final static byte decode_pre_byte(byte b0) { //重构。。。
byte b = 0;
if (b0 >= '0' && b0 <= '9') b = (byte)(b0 - ('0' - 52));
else if (b0 >= 'a' && b0 <= 'z') b = (byte)(b0 - ('a' - 26));
else if (b0 >= 'A' && b0 <= 'Z') b = (byte)(b0 - 'A');
else if (b0 == '=') b = 0;
else if (b0 == '+') b = 62;
else if (b0 == '/') b = 63;
return b;
}
/**
* A simple test.cache that encodes and decodes the first commandline argument.
*/
public final static void main(String args[]) throws Exception {
String s = "xxpay做最好的开源聚合支付系统";
System.out.println(MyBase64.encode(s.getBytes()));
}
}
\ No newline at end of file
package org.xxpay.common.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by admin on 2016/4/27.
*/
public class MyLog extends MyLogFace {
private static final Map<String,MyLog> _pool = new HashMap<String,MyLog>();
//----------
public static synchronized Set<String> getLoggers() {
return _pool.keySet();
}
public static synchronized void clearLoggers() {
_pool.clear();
}
//----------
public static synchronized MyLog getLog(String clz) {
MyLog log = _pool.get(clz);
if (log==null) {
log = new MyLog();
log.setName(clz);
_pool.put(clz, log);
}
return log;
}
//----------
public static MyLog getLog(Class<?> clz){
return getLog(clz.getName());
}
}
package org.xxpay.common.util;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MyLogFace implements MyLogInf {
private org.slf4j.Logger _log = null;
public void setName(String clz) { _log = org.slf4j.LoggerFactory.getLogger(clz); }
public boolean isDebugEnabled() { return _log.isDebugEnabled(); }
public boolean isInfoEnabled() { return _log.isInfoEnabled(); }
public boolean isWarnEnabled() { return _log.isWarnEnabled(); }
public boolean isErrorEnabled() { return _log.isErrorEnabled(); }
public boolean isTraceEnabled() { return _log.isTraceEnabled(); }
public void trace(String message, Object... args) {
if (this.isTraceEnabled()) _log.trace(message, args);
}
public void debug(String message, Object... args) {
if (this.isDebugEnabled()) _log.debug(message, args);
}
public void info(String message, Object... args) {
if (this.isInfoEnabled()) _log.info(message, args);
}
public void warn(String message, Object... args) {
if (this.isWarnEnabled()) _log.warn(message, args);
}
public void error(String message, Object... args) {
if (this.isErrorEnabled()) _log.error(message, args);
}
public void error(Throwable e, String message, Object... args) {
if (this.isErrorEnabled()) _log.error(String.format(message, args), e);
}
//------------------
public void error(Throwable e, String message) {//简化版
if (this.isErrorEnabled()) _log.error(message+e.toString(), e);
}
}
package org.xxpay.common.util;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public abstract interface MyLogInf {
public abstract void debug(String paramString, Object[] paramArrayOfObject);
public abstract void info(String paramString, Object[] paramArrayOfObject);
public abstract void warn(String paramString, Object[] paramArrayOfObject);
public abstract void error(Throwable paramThrowable, String paramString, Object[] paramArrayOfObject);
}
package org.xxpay.common.util;
import java.util.Date;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* @Description: 属性文件工具类,支持缓存及刷新
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MyProperties {
private static HashMap<String, MyProperties> configMap = new HashMap<String, MyProperties>();
private Date loadTime = null;
private ResourceBundle rb = null;
private static final String CONFIG_FILE = "properties";
private static final long CONFIG_CACHE_TIME = 60 * 1000; // 缓存1分钟
private MyProperties(String name) {
this.loadTime = new Date();
this.rb = ResourceBundle.getBundle(name);
}
public static synchronized MyProperties getInstance(String name) {
MyProperties conf = configMap.get(name);
if (null == conf) {
conf = new MyProperties(name);
configMap.put(name, conf);
return conf;
}
if (new Date().getTime() - conf.getLoadTime().getTime() > CONFIG_CACHE_TIME) {
conf = new MyProperties(name);
configMap.put(name, conf);
return conf;
}
return conf;
}
public static synchronized MyProperties getInstance() {
return getInstance("config");
}
public Date getLoadTime() {
return loadTime;
}
public String getValue(String key) {
try {
String v = rb.getString(key);
return v;
}catch (MissingResourceException e) {
return "";
}
}
public boolean getBool(String key) {
String v = getValue(key);
if (v.equalsIgnoreCase("true"))
return true;
return false;
}
public int getInt(String key) {
String v = getValue(key);
return Integer.parseInt(v);
}
public long getLong(String key) {
String v = getValue(key);
return Long.parseLong(v);
}
public static void main(String[] args) throws InterruptedException {
for (int i=0; i<10; i++) {
String v = MyProperties.getInstance("common").getValue("jdbc.jndi.name");
Thread.sleep(1000 * 30);
}
}
}
package org.xxpay.common.util;
import java.util.concurrent.atomic.AtomicLong;
/**
* @Description: 生成全局唯一序列号工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MySeq {
private static AtomicLong pay_seq = new AtomicLong(0L);
private static String pay_seq_prefix = "P";
private static AtomicLong trans_seq = new AtomicLong(0L);
private static String trans_seq_prefix = "T";
private static String node = "00";
static {
try {
//URL url = Thread.currentThread().getContextClassLoader().getResource("config" + File.separator + "system.properties");
//Properties properties = new Properties();
//properties.load(url.openStream());
//node = properties.getProperty(ConfigEnum.SERVER_NAME.getKey());
}catch (Exception e) {
e.printStackTrace();
}
}
public static String getPay() {
return getSeq(pay_seq_prefix, pay_seq);
}
public static String getTrans() {
return getSeq(trans_seq_prefix, trans_seq);
}
private static String getSeq(String prefix, AtomicLong seq) {
prefix += node;
return String.format("%s%s%06d", prefix, DateUtil.getSeqString(), (int) seq.getAndIncrement() % 1000000);
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println("pay=" + getPay());
System.out.println("trans=" + getTrans());
}
}
}
\ No newline at end of file
package org.xxpay.common.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class PayDigestUtil {
private static final MyLog _log = MyLog.getLog(PayDigestUtil.class);
private static String encodingCharset = "UTF-8";
/**
* @param aValue
* @param aKey
* @return
*/
public static String hmacSign(String aValue, String aKey) {
byte k_ipad[] = new byte[64];
byte k_opad[] = new byte[64];
byte keyb[];
byte value[];
try {
keyb = aKey.getBytes(encodingCharset);
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
keyb = aKey.getBytes();
value = aValue.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
for (int i = 0; i < keyb.length; i++) {
k_ipad[i] = (byte) (keyb[i] ^ 0x36);
k_opad[i] = (byte) (keyb[i] ^ 0x5c);
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md.update(k_ipad);
md.update(value);
byte dg[] = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return toHex(dg);
}
public static String toHex(byte input[]) {
if (input == null)
return null;
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++) {
int current = input[i] & 0xff;
if (current < 16)
output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}
/**
*
* @param args
* @param key
* @return
*/
public static String getHmac(String[] args, String key) {
if (args == null || args.length == 0) {
return (null);
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < args.length; i++) {
str.append(args[i]);
}
return (hmacSign(str.toString(), key));
}
/**
* @param aValue
* @return
*/
public static String digest(String aValue) {
aValue = aValue.trim();
byte value[];
try {
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
value = aValue.getBytes();
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
return toHex(md.digest(value));
}
public static String md5(String value, String charset) {
MessageDigest md = null;
try {
byte[] data = value.getBytes(charset);
md = MessageDigest.getInstance("MD5");
byte[] digestData = md.digest(data);
return toHex(digestData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String getSign(Object o, String key) throws IllegalAccessException {
if(o instanceof Map) {
return getSign((Map<String, Object>)o, key);
}
ArrayList<String> list = new ArrayList<String>();
Class cls = o.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
if (f.get(o) != null && f.get(o) != "") {
list.add(f.getName() + "=" + f.get(o) + "&");
}
}
int size = list.size();
String [] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size; i ++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
result += "key=" + key;
_log.debug("Sign Before MD5:" + result);
result = md5(result, encodingCharset).toUpperCase();
_log.debug("Sign Result:" + result);
return result;
}
public static String getSign(Map<String,Object> map, String key){
ArrayList<String> list = new ArrayList<String>();
for(Map.Entry<String,Object> entry:map.entrySet()){
if(!"".equals(entry.getValue())){
list.add(entry.getKey() + "=" + entry.getValue() + "&");
}
}
int size = list.size();
String [] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size; i ++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
result += "key=" + key;
_log.debug("Sign Before MD5:" + result);
result = md5(result, encodingCharset).toUpperCase();
_log.debug("Sign Result:" + result);
return result;
}
/**
*
* @param map
* @param key
* @param notContains 不包含的签名字段
* @return
*/
public static String getSign(Map<String,Object> map, String key, String... notContains){
Map<String,Object> newMap = new HashMap<String,Object>();
for(Map.Entry<String,Object> entry:map.entrySet()){
boolean isContain = false;
for(int i=0; i<notContains.length; i++) {
if(entry.getKey().equals(notContains[i])) {
isContain = true;
break;
}
}
if(!isContain) {
newMap.put(entry.getKey(), entry.getValue());
}
}
return getSign(newMap, key);
}
public static void main(String[] args) {
String key = "8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t";
String dataStr = "AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp这4564868265473632445648682654736324511";
System.out.println(hmacSign(dataStr, key));
System.out.println(md5(dataStr, "UTF-8"));
System.out.println(md5(dataStr, "GBK"));
}
}
package org.xxpay.common.util;
import java.util.ResourceBundle;
/**
* @Description: 属性文件工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class PropertiesFileUtil {
private ResourceBundle rb = null;
public PropertiesFileUtil(String bundleFile) {
rb = ResourceBundle.getBundle(bundleFile);
}
public String getValue(String key) {
return rb.getString(key);
}
public static void main(String[] args) {
}
}
package org.xxpay.common.util;
import com.alibaba.fastjson.JSON;
import org.xxpay.common.constant.PayConstant;
import org.xxpay.common.constant.PayEnum;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @Description: 支付工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class XXPayUtil {
private static final MyLog _log = MyLog.getLog(XXPayUtil.class);
public static Map<String, Object> makeRetMap(String retCode, String retMsg, String resCode, String errCode, String errCodeDesc) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(retCode != null) retMap.put(PayConstant.RETURN_PARAM_RETCODE, retCode);
if(retMsg != null) retMap.put(PayConstant.RETURN_PARAM_RETMSG, retMsg);
if(resCode != null) retMap.put(PayConstant.RESULT_PARAM_RESCODE, resCode);
if(errCode != null) retMap.put(PayConstant.RESULT_PARAM_ERRCODE, errCode);
if(errCodeDesc != null) retMap.put(PayConstant.RESULT_PARAM_ERRCODEDES, errCodeDesc);
return retMap;
}
public static Map<String, Object> makeRetMap(String retCode, String retMsg, String resCode, PayEnum payEnum) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(retCode != null) retMap.put(PayConstant.RETURN_PARAM_RETCODE, retCode);
if(retMsg != null) retMap.put(PayConstant.RETURN_PARAM_RETMSG, retMsg);
if(resCode != null) retMap.put(PayConstant.RESULT_PARAM_RESCODE, resCode);
if(payEnum != null) {
retMap.put(PayConstant.RESULT_PARAM_ERRCODE, payEnum.getCode());
retMap.put(PayConstant.RESULT_PARAM_ERRCODEDES, payEnum.getMessage());
}
return retMap;
}
public static String makeRetData(Map retMap, String resKey) {
if(retMap.get(PayConstant.RETURN_PARAM_RETCODE).equals(PayConstant.RETURN_VALUE_SUCCESS)) {
String sign = PayDigestUtil.getSign(retMap, resKey, "payParams");
retMap.put(PayConstant.RESULT_PARAM_SIGN, sign);
}
_log.info("生成响应数据:{}", retMap);
return JSON.toJSONString(retMap);
}
public static String makeRetFail(Map retMap) {
_log.info("生成响应数据:{}", retMap);
return JSON.toJSONString(retMap);
}
/**
* 验证支付中心签名
* @param params
* @return
*/
public static boolean verifyPaySign(Map<String,Object> params, String key) {
String sign = (String)params.get("sign"); // 签名
params.remove("sign"); // 不参与签名
String checkSign = PayDigestUtil.getSign(params, key);
if (!checkSign.equalsIgnoreCase(sign)) {
return false;
}
return true;
}
/**
* 验证VV平台支付中心签名
* @param params
* @return
*/
public static boolean verifyPaySign(Map<String,Object> params, String key, String... noSigns) {
String sign = (String)params.get("sign"); // 签名
params.remove("sign"); // 不参与签名
if(noSigns != null && noSigns.length > 0) {
for (String noSign : noSigns) {
params.remove(noSign);
}
}
String checkSign = PayDigestUtil.getSign(params, key);
if (!checkSign.equalsIgnoreCase(sign)) {
return false;
}
return true;
}
public static String genUrlParams(Map<String, Object> paraMap) {
if(paraMap == null || paraMap.isEmpty()) return "";
StringBuffer urlParam = new StringBuffer();
Set<String> keySet = paraMap.keySet();
int i = 0;
for(String key:keySet) {
urlParam.append(key).append("=").append(paraMap.get(key));
if(++i == keySet.size()) break;
urlParam.append("&");
}
return urlParam.toString();
}
/**
* 发起HTTP/HTTPS请求(method=POST)
* @param url
* @return
*/
public static String call4Post(String url) {
try {
URL url1 = new URL(url);
if("https".equals(url1.getProtocol())) {
return HttpClient.callHttpsPost(url);
}else if("http".equals(url1.getProtocol())) {
return HttpClient.callHttpPost(url);
}else {
return "";
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment