erzhongxmu 2023-10-13 17:18:49 +08:00
parent 8950097bb6
commit e19a83fdd9
14 changed files with 0 additions and 1812 deletions

View File

@ -1,31 +0,0 @@
package com.zzjee.sdk;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ClientRequestHandler extends PrepayIdRequestHandler {
public ClientRequestHandler(HttpServletRequest request,
HttpServletResponse response) {
super(request, response);
// TODO Auto-generated constructor stub
}
public String getXmlBody() {
StringBuffer sb = new StringBuffer();
Set es = super.getAllParameters().entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (!"appkey".equals(k)) {
sb.append("<" + k + ">" + v + "<" + k + ">" + "\r\n");
}
}
return sb.toString();
}
}

View File

@ -1,166 +0,0 @@
package com.zzjee.sdk;
import org.jdom2.JDOMException;
import java.io.IOException;
import java.util.*;
public class ClientResponseHandler {
/** 应答原始内容 */
private String content;
/** 应答的参数 */
private SortedMap parameters;
/** 密钥 */
private String key;
/** 字符集 */
private String charset;
public ClientResponseHandler() {
this.content = "";
this.parameters = new TreeMap();
this.key = "";
this.charset = "utf8";
}
public String getContent() {
return content;
}
public void setContent(String content) throws Exception {
this.content = content;
this.doParse();
}
/**
*
* @param parameter
* @return String
*/
public String getParameter(String parameter) {
String s = (String)this.parameters.get(parameter);
return (null == s) ? "" : s;
}
/**
*
* @param parameter
* @param parameterValue
*/
public void setParameter(String parameter, String parameterValue) {
String v = "";
if(null != parameterValue) {
v = parameterValue.trim();
}
this.parameters.put(parameter, v);
}
/**
*
* @return SortedMap
*/
public SortedMap getAllParameters() {
return this.parameters;
}
/**
*
*/
public String getKey() {
return key;
}
/**
*
*/
public void setKey(String key) {
this.key = key;
}
public String getCharset() {
return this.charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
/**
* ,:a-z,
* @return boolean
*/
public boolean isTenpaySign() {
StringBuffer sb = new StringBuffer();
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
//算出摘要
String sign = MD5Util.MD5Encode(sb.toString(), this.charset).toLowerCase();
String tenpaySign = this.getParameter("sign").toLowerCase();
return tenpaySign.equals(sign);
}
/**
*
* @param signParameterArray
* @return boolean
*/
protected boolean isTenpaySign(String signParameterArray[]) {
StringBuffer signPars = new StringBuffer();
for(int index = 0; index < signParameterArray.length; index++) {
String k = signParameterArray[index];
String v = this.getParameter(k);
if(null != v && !"".equals(v)) {
signPars.append(k + "=" + v + "&");
}
}
signPars.append("key=" + this.getKey());
//算出摘要
String sign = MD5Util.MD5Encode(
signPars.toString(), this.charset).toLowerCase();
String tenpaySign = this.getParameter("sign").toLowerCase();
return tenpaySign.equals(sign);
}
/**
* XML
*/
protected void doParse() throws JDOMException, IOException {
String xmlContent = this.getContent();
//解析xml,得到map
Map m = XMLUtil.doXMLParse(xmlContent);
//设置参数
Iterator it = m.keySet().iterator();
while(it.hasNext()) {
String k = (String) it.next();
String v = (String) m.get(k);
this.setParameter(k, v);
}
}
}

View File

@ -1,44 +0,0 @@
package com.zzjee.sdk;
public class ConstantUtil {
public static final String APP_ID="wxbe2c5ee498af5098";
/**
*
*/
public static final String APP_SECRET="3655e7f01063e2a269807b53aa979be1";
/**
*
*/
public static final String APP_KEY="3655e7f01063e2a269807b53aa979be1";
/**
*
*/
public static final String MCH_ID="1487601332";
/**
*
*/
public static final String BODY="test";
/**
*
*/
public static final String PARTNER_key="123466";
/**
* id
*/
public static final String PARTNER_ID="14698sdfs402dsfdew402";
/**
*
*/
public static final String GRANT_TYPE="client_credential";
/**
* idurl
*/
public static final String GATEURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
/**
* url
*/
public static final String NOTIFY_URL="http://www.zhaodui.com.cn/fxj380/rest/tenPayController/app/tenpay/notify";
}

View File

@ -1,278 +0,0 @@
package com.zzjee.sdk;
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.CertificateException;
import java.util.HashMap;
import java.util.Map;
public class HttpClientUtil {
/**
* http
*
*/
public static final String SunX509 = "SunX509";
public static final String JKS = "JKS";
public static final String PKCS12 = "PKCS12";
public static final String TLS = "TLS";
/**
* 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
* 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
* 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, "");
}
}
/**
* BufferedReaderString<br/>
* :
* @param reader
* @return
* @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;
}
// ˢ<>»<EFBFBD><C2BB><EFBFBD><EFBFBD><EFBFBD>
out.flush();
}
}
/**
* SSLContext
* @param trustFileInputStream
* @param trustPasswd
* @param keyFileInputStream
* @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;
}
/**
* char
* @param str
* @return char[]
*/
public static char[] str2CharArray(String str) {
if(null == str) {
return null;
}
return str.toCharArray();
}
public static InputStream String2Inputstream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
/**
* InputStreamByte
* :
* @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;
}
/**
* InputStreamString
* :
* @param in
* @param encoding
* @return String
* @throws Exception
*/
public static String InputStreamTOString(InputStream in, String encoding) throws IOException {
return new String(InputStreamTOByte(in),encoding);
}
}

View File

@ -1,52 +0,0 @@
package com.zzjee.sdk;
import java.security.MessageDigest;
public class MD5Util {
/**
* MD5
* @param b
* @return
*/
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0) {
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
//Dm DM_STRING_CTOR 因为使用StringString构造函数生成新字符串会浪费内存推荐使用原有字符串。
resultString = origin;
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname)) {
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
} else {
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
}
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}

View File

@ -1,61 +0,0 @@
package com.zzjee.sdk;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class PrepayIdRequestHandler extends RequestHandler {
public PrepayIdRequestHandler(HttpServletRequest request,
HttpServletResponse response) {
super(request, response);
}
public String createMD5Sign() {
StringBuffer sb = new StringBuffer();
Set es = super.getAllParameters().entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + v + "&");
}
String params=sb.append("key="+ConstantUtil.APP_KEY).substring(0);
String sign = MD5Util.MD5Encode(params, "utf8");
return sign.toUpperCase();
}
// 提交预支付
public String sendPrepay() throws Exception {
String prepayid = "";
Set es=super.getAllParameters().entrySet();
Iterator it=es.iterator();
StringBuffer sb = new StringBuffer("<xml>");
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append("<"+k+">"+v+"</"+k+">");
}
sb.append("</xml>");
String params=sb.substring(0);
System.out.println("请求参数:"+params);
String requestUrl = super.getGateUrl();
System.out.println("请求url"+requestUrl);
TenpayHttpClient httpClient = new TenpayHttpClient();
httpClient.setReqContent(requestUrl);
String resContent = "";
if (httpClient.callHttpPost(requestUrl, params)) {
resContent = httpClient.getResContent();
System.out.println("获取prepayid的返回值"+resContent);
Map<String,String> map=XMLUtil.doXMLParse(resContent);
if(map.containsKey("prepay_id")) {
prepayid=map.get("prepay_id");
}
}
return prepayid;
}
}

View File

@ -1,179 +0,0 @@
package com.zzjee.sdk;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
*
* createSign
*
*/
public class RequestHandler {
/** 网关url地址 */
private String gateUrl;
/** 密钥 */
private String key;
/** 请求的参数 */
private SortedMap parameters;
protected HttpServletRequest request;
protected HttpServletResponse response;
/**
*
* @param request
* @param response
*/
public RequestHandler(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
this.gateUrl = "https://gw.tenpay.com/gateway/pay.htm";
this.key = "";
this.parameters = new TreeMap();
}
/**
*
*/
public void init() {
//nothing to do
}
/**
*,
*/
public String getGateUrl() {
return gateUrl;
}
/**
*,
*/
public void setGateUrl(String gateUrl) {
this.gateUrl = gateUrl;
}
/**
*
*/
public String getKey() {
return key;
}
/**
*
*/
public void setKey(String key) {
this.key = key;
}
/**
*
* @param parameter
* @return String
*/
public String getParameter(String parameter) {
String s = (String)this.parameters.get(parameter);
return (null == s) ? "" : s;
}
/**
*
* @param parameter
* @param parameterValue
*/
public void setParameter(String parameter, Object parameterValue) {
String v = "";
if(null != parameterValue) {
if(parameterValue instanceof String) {
v = ((String) parameterValue).trim();
}
}
this.parameters.put(parameter, v);
}
/**
*
* @return SortedMap
*/
public SortedMap getAllParameters() {
return this.parameters;
}
/**
* URL
* @return String
* @throws UnsupportedEncodingException
*/
public String getRequestURL() throws UnsupportedEncodingException {
this.createSign();
StringBuffer sb = new StringBuffer();
String enc = TenpayUtil.getCharacterEncoding(this.request, this.response);
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"spbill_create_ip".equals(k)) {
sb.append(k + "=" + URLEncoder.encode(v, enc) + "&");
} else {
sb.append(k + "=" + v.replace("\\.", "%2E") + "&");
}
}
//去掉最后一个&
String reqPars = sb.substring(0, sb.lastIndexOf("&"));
return this.getGateUrl() + "?" + reqPars;
}
public void doSend() throws UnsupportedEncodingException, IOException {
this.response.sendRedirect(this.getRequestURL());
}
/**
* md5,:a-z,
*/
protected void createSign() {
StringBuffer sb = new StringBuffer();
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
String enc = TenpayUtil.getCharacterEncoding(this.request, this.response);
String sign = MD5Util.MD5Encode(sb.toString(), enc).toUpperCase();
this.setParameter("sign", sign);
}
protected HttpServletRequest getHttpServletRequest() {
return this.request;
}
protected HttpServletResponse getHttpServletResponse() {
return this.response;
}
}

View File

@ -1,180 +0,0 @@
package com.zzjee.sdk;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
*
* isTenpaySign
*
*/
public class ResponseHandler {
/** 密钥 */
private String key;
/** 应答的参数 */
private SortedMap parameters;
private HttpServletRequest request;
private HttpServletResponse response;
private String uriEncoding;
/**
*
*
* @param request
* @param response
*/
public ResponseHandler(HttpServletRequest request,
HttpServletResponse response) {
this.request = request;
this.response = response;
this.key = "";
this.parameters = new TreeMap();
this.uriEncoding = "";
Map m = this.request.getParameterMap();
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String k = (String) it.next();
String v = ((String[]) m.get(k))[0];
this.setParameter(k, v);
}
}
/**
*
*/
public String getKey() {
return key;
}
/**
*
*/
public void setKey(String key) {
this.key = key;
}
/**
*
* @param parameter
* @return String
*/
public String getParameter(String parameter) {
String s = (String)this.parameters.get(parameter);
return (null == s) ? "" : s;
}
/**
*
* @param parameter
* @param parameterValue
*/
public void setParameter(String parameter, String parameterValue) {
String v = "";
if(null != parameterValue) {
v = parameterValue.trim();
}
this.parameters.put(parameter, v);
}
/**
*
* @return SortedMap
*/
public SortedMap getAllParameters() {
return this.parameters;
}
/**
* ,:a-z,
* @return boolean
*/
public boolean isTenpaySign() {
StringBuffer sb = new StringBuffer();
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
//算出摘要
String enc = TenpayUtil.getCharacterEncoding(this.request, this.response);
String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();
String tenpaySign = this.getParameter("sign").toLowerCase();
return tenpaySign.equals(sign);
}
/**
*
* @param msg: Success or fail
* @throws IOException
*/
public void sendToCFT(String msg) throws IOException {
String strHtml = msg;
PrintWriter out = this.getHttpServletResponse().getWriter();
out.println(strHtml);
out.flush();
out.close();
}
/**
* uri
* @return String
*/
public String getUriEncoding() {
return uriEncoding;
}
/**
* uri
* @param uriEncoding
* @throws UnsupportedEncodingException
*/
public void setUriEncoding(String uriEncoding)
throws UnsupportedEncodingException {
if (!"".equals(uriEncoding.trim())) {
this.uriEncoding = uriEncoding;
// 编码转换
String enc = TenpayUtil.getCharacterEncoding(request, response);
Iterator it = this.parameters.keySet().iterator();
while (it.hasNext()) {
String k = (String) it.next();
String v = this.getParameter(k);
v = new String(v.getBytes(uriEncoding.trim()), enc);
this.setParameter(k, v);
}
}
}
protected HttpServletRequest getHttpServletRequest() {
return this.request;
}
protected HttpServletResponse getHttpServletResponse() {
return this.response;
}
}

View File

@ -1,231 +0,0 @@
package com.zzjee.sdk;
import com.zzjee.conf.entity.WxConfigEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.JDOMException;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import static com.xiaoleilu.hutool.date.DateTime.now;
@Api(value="tenPayController",description="微信支付",tags="tenPayController")
@Controller
@RequestMapping("/tenPayController")
public class TenpayController {
@Autowired
private SystemService systemService;
@Autowired
private Validator validator;
// @Autowired
// private PayRecordService payRecordService;
// @Autowired
// private AppCustomerService appCustomerService;
private String out_trade_no = "";
/**
* prepayId
* @param request
* @param response
* @return
* @throws Exception
*/
// @Auth
@ApiOperation(value = "wxauthv3")
@RequestMapping(value = "/authv3",method = RequestMethod.GET)
@ResponseBody
public ResponseMessage<?> authV3(@RequestParam(value="CODE", required=false) String CODE, @RequestParam(value="appCode", required=false) String appCode) {
// 验证
if (StringUtils.isEmpty(CODE)) {
return Result.error("JSCODE不能为空!");
}
// // 验证
// if (StringUtils.isEmpty(username)) {
// return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
// }
// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
// Assert.notNull(JSCODE, "JSCODE can not be empty");
// Assert.notNull(password, "password can not be empty");
// String miniappid=ResourceUtil.getConfigByName("mini.appid") ;
// String minisecret=ResourceUtil.getConfigByName("mini.secret");
if(StringUtil.isEmpty(appCode)){
appCode = "fxjpay";
}
WxConfigEntity wxConfigEntity = systemService.findUniqueByProperty(WxConfigEntity.class,"appCode",appCode);
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxConfigEntity.getAppId() +
"&secret=" + wxConfigEntity.getAppSecret() +
"&code=" +
CODE+"&grant_type=authorization_code";
String result= com.xiaoleilu.hutool.http.HttpUtil.get(url);
JSONObject resultJson = JSONObject.fromObject(result);
String openid = String.valueOf(resultJson.get("openid"));
return Result.success(openid,(long)0);
}
@RequestMapping(value = "/app/tenpay/prepay", method = RequestMethod.GET)
@ApiOperation(value="生成预支付订单",produces="application/json",httpMethod="GET")
public @ResponseBody Map<String, Object> getOrder(@RequestParam(value="jzProName", required=false) String jzProName,
@RequestParam(value="jzProject", required=false) String jzProject,
@RequestParam(value="jzRemark", required=false) String jzRemark,
@RequestParam(value="jzName", required=false) String jzName,
@RequestParam(value="code", required=false) String code,
@RequestParam(value="total_fees", required=true) String total_fees,
@RequestParam(value="appCode", required=false) String appCode,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
if(StringUtil.isEmpty(appCode)){
appCode = "fxjpay";
}
WxConfigEntity wxConfigEntity = systemService.findUniqueByProperty(WxConfigEntity.class,"appCode",appCode);
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxConfigEntity.getAppId() +
"&secret=" + wxConfigEntity.getAppSecret() +
"&code=" +
code+"&grant_type=authorization_code";
String result= com.xiaoleilu.hutool.http.HttpUtil.get(url);
JSONObject resultJson = JSONObject.fromObject(result);
String openid = String.valueOf(resultJson.get("openid"));
Map<String, Object> map = new HashMap<String, Object>();
// 获取生成预支付订单的请求类
PrepayIdRequestHandler prepayReqHandler = new PrepayIdRequestHandler(request, response);
// String totalFee = request.getParameter("total_fee");
int total_fee=(int) (Float.valueOf(total_fees)*100);
System.out.println("total:"+total_fee);
System.out.println("total_fee:" + total_fee);
prepayReqHandler.setParameter("appid", wxConfigEntity.getAppId());
prepayReqHandler.setParameter("body", ConstantUtil.BODY);
prepayReqHandler.setParameter("mch_id", wxConfigEntity.getMchId());
String nonce_str = WXUtil.getNonceStr();
prepayReqHandler.setParameter("nonce_str", nonce_str);
prepayReqHandler.setParameter("notify_url", wxConfigEntity.getNotifyUrl());
out_trade_no = String.valueOf(UUID.next());
prepayReqHandler.setParameter("out_trade_no", out_trade_no);
prepayReqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());
String timestamp = WXUtil.getTimeStamp();
prepayReqHandler.setParameter("time_start", timestamp);
System.out.println(String.valueOf(total_fee));
prepayReqHandler.setParameter("total_fee", String.valueOf(total_fee));
prepayReqHandler.setParameter("openid",openid);
prepayReqHandler.setParameter("trade_type", "JSAPI");
// prepayReqHandler.setParameter("trade_type", "JSAPI");
/**
* signAPP_KEY,
*/
prepayReqHandler.setParameter("sign", prepayReqHandler.createMD5Sign());
prepayReqHandler.setGateUrl(ConstantUtil.GATEURL);
String prepayid = prepayReqHandler.sendPrepay();
// 若获取prepayid成功将相关信息返回客户端
if (prepayid != null && !prepayid.equals("")) {
String signs = "appId=" + wxConfigEntity.getAppId() + "&nonceStr=" + nonce_str + "&package=prepay_id="
+ prepayid + "&signType=MD5" + "&timeStamp=" + timestamp + "&key="
+ wxConfigEntity.getAppKey();
map.put("code", 0);
map.put("info", "success");
map.put("prepayid", prepayid);
/**
*
*/
map.put("sign", MD5Util.MD5Encode(signs, "utf8").toUpperCase());
map.put("appid", wxConfigEntity.getAppId());
map.put("timestamp", timestamp); //等于请求prepayId时的time_start
map.put("noncestr", nonce_str); //与请求prepayId时值一致
map.put("package", "prepay_id="+prepayid); //固定常量
map.put("partnerid", ConstantUtil.PARTNER_ID);
} else {
map.put("code", 1);
map.put("info", "获取prepayid失败");
}
return map;
}
/**
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/app/tenpay/notify")
@ApiOperation(value="接收微信支付成功通知",produces="application/json",httpMethod="POST")
public void getnotify(HttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println("微信支付回调");
PrintWriter writer = response.getWriter();
InputStream inStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
String result = new String(outSteam.toByteArray(), "utf-8");
System.out.println("微信支付通知结果:" + result);
Map<String, String> map = null;
try {
/**
*
*/
map = XMLUtil.doXMLParse(result);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("=========:"+result);
// 若支付成功,则告知微信服务器收到通知
if (map.get("return_code").equals("SUCCESS")) {
if (map.get("result_code").equals("SUCCESS")) {
System.out.println("充值成功!");
System.out.println("订单号:"+Long.valueOf(map.get("out_trade_no")));
String notifyStr = XMLUtil.setXML("SUCCESS", "");
writer.write(notifyStr);
writer.flush();
// }
}
}
}
}

View File

@ -1,297 +0,0 @@
package com.zzjee.sdk;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
public class TenpayHttpClient {
/** 请求内容无论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 TenpayHttpClient() {
this.reqContent = "";
this.resContent = "";
this.method = "POST";
this.errInfo = "";
this.timeOut = 30;//30秒
this.responseCode = 0;
this.charset = "utf8";
this.inputStream = null;
}
/**
*
* @param reqContent
*/
public void setReqContent(String reqContent) {
this.reqContent = reqContent;
}
/**
*
* @return String
* @throws IOException
*/
public String getResContent() {
try {
this.doResponse();
} catch (IOException e) {
this.errInfo = e.getMessage();
//return "";
}
return this.resContent;
}
/**
* postget
* @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;
}
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);
}
public boolean callHttpPost(String url, String postdata) {
boolean flag = false;
byte[] postData;
try {
postData = postdata.getBytes(this.charset);
this.httpPostMethod(url, postData);
flag = true;
} catch (IOException e1) {
e1.printStackTrace();
}
return flag;
}
/**
* 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);
//不使用缓存
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);
// 关闭流
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();
}
}

View File

@ -1,131 +0,0 @@
package com.zzjee.sdk;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TenpayUtil {
/**
*
* @param obj
* @return String ,null,.
*/
public static String toString(Object obj) {
if(obj == null) {
return "";
}
return obj.toString();
}
/**
* int.
*
* @param obj
* .
* @return int ,0
*/
public static int toInt(Object obj) {
int a = 0;
try {
if (obj != null) {
a = Integer.parseInt(obj.toString());
}
} catch (Exception e) {
}
return a;
}
/**
* yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* yyyyMMdd
* @param date
* @return String
*/
public static String formatDate(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String strDate = formatter.format(date);
return strDate;
}
/**
* .
*
* @param length
* int length11
* @return int
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
*
* @param request
* @param response
* @return String
*/
public static String getCharacterEncoding(HttpServletRequest request,
HttpServletResponse response) {
if(null == request || null == response) {
return "gbk";
}
String enc = request.getCharacterEncoding();
if(null == enc || "".equals(enc)) {
enc = response.getCharacterEncoding();
}
if(null == enc || "".equals(enc)) {
enc = "gbk";
}
return enc;
}
/**
* unix1970-01-01 00:00:00
* @param date
* @return long
*/
public static long getUnixTime(Date date) {
if( null == date ) {
return 0;
}
return date.getTime()/1000;
}
/**
*
* @param date
* @param formatType
* @return String
*/
public static String date2String(Date date, String formatType) {
SimpleDateFormat sdf = new SimpleDateFormat(formatType);
return sdf.format(date);
}
}

View File

@ -1,24 +0,0 @@
package com.zzjee.sdk;
import java.util.Date;
public class UUID {
private static Date date = new Date();
private static StringBuilder buf = new StringBuilder();
private static int seq = 0;
private static final int ROTATION = 99999;
public static synchronized long next() {
if (seq > ROTATION) {
seq = 0;
}
buf.delete(0, buf.length());
date.setTime(System.currentTimeMillis());
String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, seq++);
return Long.parseLong(str);
}
private UUID(){
}
}

View File

@ -1,21 +0,0 @@
package com.zzjee.sdk;
import java.util.Random;
public class WXUtil {
/**
*
* @return
*/
public static String getNonceStr() {
Random random = new Random();
return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "utf8");
}
/**
*
* @return
*/
public static String getTimeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
}

View File

@ -1,117 +0,0 @@
package com.zzjee.sdk;
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.*;
import java.util.Map.Entry;
public class XMLUtil {
/**
* xml,xml
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws org.jdom2.JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
builder.setExpandEntities(false);
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 = XMLUtil.getChildrenText(children);
}
m.put(k, v);
}
//关闭流
in.close();
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(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
/**
* xml
* @param strxml
* @return
* @throws IOException
* @throws JDOMException
*/
public static String getXMLEncoding(String strxml) throws JDOMException, IOException {
InputStream in = HttpClientUtil.String2Inputstream(strxml);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
in.close();
return (String)doc.getProperty("encoding");
}
/**
*
* @param return_code
* @param return_msg
* @return
*/
public static String setXML(String return_code, String return_msg) {
return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
}
public static String createXML(Map<String,Object> map){
// Set<Entry<String,Object>> set=map.entrySet();
//set.iterator();
return null;
}
}