代码优化
This commit is contained in:
@@ -3,7 +3,6 @@ package com.starry.admin.common.oss.service.impl;
|
||||
|
||||
import cn.hutool.core.date.DateTime;
|
||||
import cn.hutool.core.io.FileTypeUtil;
|
||||
import com.starry.common.utils.IdUtils;
|
||||
import com.aliyun.oss.ClientException;
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
@@ -13,6 +12,7 @@ import com.aliyun.oss.model.PutObjectRequest;
|
||||
import com.starry.admin.common.exception.CustomException;
|
||||
import com.starry.admin.common.oss.OssProperties;
|
||||
import com.starry.admin.common.oss.service.IOssFileService;
|
||||
import com.starry.common.utils.IdUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
package com.starry.admin.common.play.wx;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.starry.admin.common.exception.CustomException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import java.io.*;
|
||||
import java.net.ConnectException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyStore;
|
||||
|
||||
@Slf4j
|
||||
public class HttpUtils {
|
||||
|
||||
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
try {
|
||||
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
|
||||
TrustManager[] tm = {new MyX509TrustManager()};
|
||||
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
|
||||
sslContext.init(null, tm, new java.security.SecureRandom());
|
||||
// 从上述SSLContext对象中得到SSLSocketFactory对象
|
||||
SSLSocketFactory ssf = sslContext.getSocketFactory();
|
||||
|
||||
URL url = new URL(requestUrl);
|
||||
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
|
||||
httpUrlConn.setSSLSocketFactory(ssf);
|
||||
httpUrlConn.setDoOutput(true);
|
||||
httpUrlConn.setDoInput(true);
|
||||
httpUrlConn.setUseCaches(false);
|
||||
// 设置请求方式(GET/POST)
|
||||
httpUrlConn.setRequestMethod(requestMethod);
|
||||
if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();
|
||||
// 当有数据需要提交时
|
||||
if (null != outputStr) {
|
||||
OutputStream outputStream = httpUrlConn.getOutputStream();
|
||||
// 注意编码格式,防止中文乱码
|
||||
outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
|
||||
outputStream.close();
|
||||
}
|
||||
// 将返回的输入流转换成字符串
|
||||
InputStream inputStream = httpUrlConn.getInputStream();
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
|
||||
String str;
|
||||
while ((str = bufferedReader.readLine()) != null) {
|
||||
buffer.append(str);
|
||||
}
|
||||
bufferedReader.close();
|
||||
inputStreamReader.close();
|
||||
// 释放资源
|
||||
inputStream.close();
|
||||
httpUrlConn.disconnect();
|
||||
return JSONObject.parseObject(buffer.toString());
|
||||
} catch (ConnectException ce) {
|
||||
log.error("weixin server connection timed out");
|
||||
} catch (Exception e) {
|
||||
log.error("weixin play error", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static String sendPost(String requestUrl, String outputStr) throws IOException {
|
||||
HttpURLConnection conn = getConnection(requestUrl);
|
||||
// 当outputStr不为null时向输出流写数据
|
||||
if (null != outputStr) {
|
||||
OutputStream outputStream = conn.getOutputStream();
|
||||
// 注意编码格式
|
||||
outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
try (InputStream inputStream = conn.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
// 从输入流读取返回内容
|
||||
String str;
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
while ((str = bufferedReader.readLine()) != null) {
|
||||
buffer.append(str);
|
||||
}
|
||||
// 释放资源
|
||||
conn.disconnect();
|
||||
return buffer.toString();
|
||||
} catch (Exception e) {
|
||||
log.error("sendPost error,url = {},outputStr={}", requestUrl, outputStr, e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 需要使用证书请求接口
|
||||
*/
|
||||
public static String requestWithCert(String url, String pay_cert, String mchid, String data) throws Exception {
|
||||
KeyStore keyStore = KeyStore.getInstance("PKCS12");
|
||||
try (FileInputStream is = new FileInputStream(pay_cert)) {
|
||||
// 这里写密码..默认是你的MCHID
|
||||
keyStore.load(is, mchid.toCharArray());
|
||||
}
|
||||
// Trust own CA and all self-signed certs
|
||||
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray())// 这里也是写密码的
|
||||
.build();
|
||||
// Allow TLSv1 protocol only
|
||||
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
|
||||
try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(socketFactory).build()) {
|
||||
HttpPost httpPost = getHttpPost(url, data);
|
||||
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
|
||||
HttpEntity entity = response.getEntity();
|
||||
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
EntityUtils.consume(entity);
|
||||
return jsonStr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpPost getHttpPost(String url, String data) {
|
||||
HttpPost httpPost = new HttpPost(url); // 设置响应头信息
|
||||
httpPost.addHeader("Connection", "keep-alive");
|
||||
httpPost.addHeader("Accept", "*/*");
|
||||
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
|
||||
httpPost.addHeader("Host", "api.mch.weixin.qq.com");
|
||||
httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
|
||||
httpPost.addHeader("Cache-Control", "max-age=0");
|
||||
httpPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
|
||||
httpPost.setEntity(new StringEntity(data, "UTF-8"));
|
||||
return httpPost;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取网络连接
|
||||
*
|
||||
* @param url URL
|
||||
* @return URLConnection
|
||||
*/
|
||||
private static HttpURLConnection getConnection(String url) {
|
||||
try {
|
||||
URL realUrl = new URL(url);
|
||||
// 打开和URL之间的连接
|
||||
URLConnection conn = realUrl.openConnection();
|
||||
// 设置通用的请求属性
|
||||
conn.setRequestProperty("Charset", "UTF-8");
|
||||
conn.setRequestProperty("accept", "*/*");
|
||||
conn.setRequestProperty("connection", "Keep-Alive");
|
||||
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||||
// 发送POST请求必须设置如下两行
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
|
||||
return (HttpURLConnection) conn;
|
||||
} catch (IOException e) {
|
||||
log.error("getConnection error", e);
|
||||
throw new CustomException("getConnection error," + e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.starry.admin.common.play.wx;
|
||||
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
|
||||
/**
|
||||
* 对于https请求,我们需要一个证书信任管理器,这个管理器类需要自己定义,但需要实现X509TrustManager接口
|
||||
* 证书信任管理器(用于https请求)
|
||||
* 这个证书管理器的作用就是让它信任我们指定的证书,上面的代码意味着信任所有证书,不管是否权威机构颁发。
|
||||
*
|
||||
* @author jiangyin
|
||||
*/
|
||||
public class MyX509TrustManager implements X509TrustManager {
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType) {
|
||||
}
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType) {
|
||||
}
|
||||
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.starry.admin.common.play.wx;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
public final class WXPayXmlUtil {
|
||||
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
|
||||
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
|
||||
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
documentBuilderFactory.setXIncludeAware(false);
|
||||
documentBuilderFactory.setExpandEntityReferences(false);
|
||||
|
||||
return documentBuilderFactory.newDocumentBuilder();
|
||||
}
|
||||
|
||||
public static Document newDocument() throws ParserConfigurationException {
|
||||
return newDocumentBuilder().newDocument();
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.starry.admin.common.play.wx;
|
||||
|
||||
/**
|
||||
* 位置支付常量
|
||||
*
|
||||
* @author admin
|
||||
*/
|
||||
public class WeChatConstants {
|
||||
|
||||
public enum SignType {
|
||||
MD5, HMACSHA256
|
||||
}
|
||||
|
||||
public static final String FIELD_SIGN = "sign";
|
||||
|
||||
/**
|
||||
* 支付成功回调地址
|
||||
*/
|
||||
public static String NOTIFY_URL = "https://july.hucs.top/api/wx/pay/jsCallback";
|
||||
|
||||
|
||||
/**
|
||||
* 支付证书路径
|
||||
*/
|
||||
public static String PAY_CERT_LOC = "C:\\CTO\\java\\apache-tomcat-8.0.50\\wxcert\\";
|
||||
|
||||
/**
|
||||
* 微信 trade_type 参数
|
||||
*/
|
||||
public static final String TRADE_TYPE_JSAPI = "JSAPI";// JSAPI支付 例如 : 直接调用微信支付
|
||||
public static final String TRADE_TYPE_NATIVE = "NATIVE";// Native支付 例如 : 扫码支付
|
||||
|
||||
/**
|
||||
* 统一下单
|
||||
*/
|
||||
public static String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
|
||||
/**
|
||||
* 订单支付状态查询
|
||||
*/
|
||||
public static String ORDERQUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
|
||||
/**
|
||||
* 退款
|
||||
*/
|
||||
public static String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
|
||||
/**
|
||||
* 提现
|
||||
*/
|
||||
public static String TRANSFERS_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
|
||||
|
||||
}
|
||||
@@ -1,368 +0,0 @@
|
||||
package com.starry.admin.common.play.wx;
|
||||
|
||||
import com.starry.common.utils.IdUtils;
|
||||
import cn.hutool.crypto.digest.MD5;
|
||||
import com.github.wxpay.sdk.WXPayUtil;
|
||||
import com.starry.admin.common.exception.CustomException;
|
||||
import com.starry.common.utils.StringUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 微信支付辅助类
|
||||
*
|
||||
* @author admin
|
||||
*/
|
||||
@Slf4j
|
||||
public class WxCustomPayUtils {
|
||||
|
||||
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
private static final Random RANDOM = new SecureRandom();
|
||||
|
||||
|
||||
/**
|
||||
* 获取微信支付请求参数(map格式)
|
||||
*
|
||||
* @param openId 微信公众号ID
|
||||
* @param appid 用户ID
|
||||
* @param mchId 商户ID
|
||||
* @param orderId 订单ID
|
||||
* @param nonceStr 订单ID
|
||||
* @param spBillCreateIp 终端设备ID
|
||||
* @param body 商品描述
|
||||
* @param totalFee 商品金额
|
||||
* @param attach 附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用(传入租户ID)
|
||||
*/
|
||||
public static Map<String, String> getPayRequestParameters(String openId, String appid, String mchId, String orderId, String nonceStr, String spBillCreateIp, String body, String attach, long totalFee) {
|
||||
Map<String, String> playRequestParameters = new HashMap<>(16);
|
||||
playRequestParameters.put("openId", openId);
|
||||
playRequestParameters.put("appid", appid);
|
||||
playRequestParameters.put("mch_id", mchId);
|
||||
playRequestParameters.put("nonce_str", nonceStr);
|
||||
playRequestParameters.put("body", body);
|
||||
playRequestParameters.put("attach", attach);
|
||||
playRequestParameters.put("out_trade_no", orderId);
|
||||
playRequestParameters.put("total_fee", String.valueOf(totalFee));
|
||||
playRequestParameters.put("spbill_create_ip", spBillCreateIp);
|
||||
playRequestParameters.put("notify_url", WeChatConstants.NOTIFY_URL);
|
||||
playRequestParameters.put("trade_type", "JSAPI");
|
||||
return playRequestParameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param playRequestParameters 微信支付请求参数
|
||||
* @param orderId 订单ID
|
||||
* @param sign 签名信息
|
||||
*/
|
||||
public static String unifiedOrderJsApi(Map<String, String> playRequestParameters, String orderId, String sign) throws Exception {
|
||||
playRequestParameters.put("sign", sign);
|
||||
// 将所有参数(map)转xml格式
|
||||
String xml = WXPayUtil.mapToXml(playRequestParameters);
|
||||
String newXml = new String(xml.getBytes(StandardCharsets.UTF_8));
|
||||
log.error("xml:{}", newXml);
|
||||
// 发送post请求"统一下单接口"返回预支付id:prepay_id
|
||||
String xmlStr = HttpUtils.sendPost(WeChatConstants.UNIFIEDORDER_URL, newXml);
|
||||
log.info("xmlStr:{}", xmlStr);
|
||||
if (StringUtils.isBlank(xmlStr)) {
|
||||
throw new CustomException("微信支付返回信息为空");
|
||||
}
|
||||
Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
|
||||
// 如果预支付返回状态码为不为SUCCESS,说明预支付接口调用失败(通讯业务失败),抛出异常,业务进行处理
|
||||
if (!map.get("return_code").equals("SUCCESS")) {
|
||||
throw new CustomException(map.get("return_msg"));
|
||||
}
|
||||
// 如果预支付返回状态码为不为SUCCESS,说明预支付接口调用失败(交易业务失败),抛出异常,业务进行处理
|
||||
if (!map.get("result_code ").equals("SUCCESS")) {
|
||||
throw new CustomException(map.get("err_code_des"));
|
||||
}
|
||||
return map.get("prepay_id");
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单支付状态查询
|
||||
*
|
||||
* @param wechat_appid
|
||||
* @param wechat_mchid
|
||||
* @param wechat_seckey
|
||||
* @param out_trade_no
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Map<String, String> orderQuery(String wechat_appid, String wechat_mchid, String wechat_seckey, String out_trade_no) throws Exception {
|
||||
// 拼接 参数
|
||||
Map<String, String> paraMap = new HashMap<String, String>();
|
||||
paraMap.put("appid", wechat_appid);
|
||||
paraMap.put("mch_id", wechat_mchid);
|
||||
paraMap.put("nonce_str", IdUtils.getUuid());
|
||||
paraMap.put("out_trade_no", out_trade_no);// 订单号
|
||||
String sign = WXPayUtil.generateSignature(paraMap, wechat_seckey);
|
||||
paraMap.put("sign", sign);
|
||||
String xml = WXPayUtil.mapToXml(paraMap);// 将所有参数(map)转xml格式
|
||||
String xmlStr = HttpUtils.sendPost(WeChatConstants.ORDERQUERY_URL, xml);// 发送post请求"统一下单接口"返回预支付id:prepay_id
|
||||
return WXPayUtil.xmlToMap(xmlStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* XML格式字符串转换为Map
|
||||
*
|
||||
* @param strXML XML字符串
|
||||
* @return XML数据转换后的Map
|
||||
*/
|
||||
public static Map<String, String> xmlToMap(String strXML) throws Exception {
|
||||
Map<String, String> data = new HashMap<>();
|
||||
DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
|
||||
// InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
|
||||
InputStream stream = new ByteArrayInputStream(strXML.getBytes("GBK"));
|
||||
Document doc = documentBuilder.parse(stream);
|
||||
doc.getDocumentElement().normalize();
|
||||
NodeList nodeList = doc.getDocumentElement().getChildNodes();
|
||||
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
|
||||
Node node = nodeList.item(idx);
|
||||
if (node.getNodeType() == Node.ELEMENT_NODE) {
|
||||
Element element = (Element) node;
|
||||
data.put(element.getNodeName(), element.getTextContent());
|
||||
}
|
||||
}
|
||||
try {
|
||||
stream.close();
|
||||
} catch (Exception ignored) {
|
||||
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将Map转换为XML格式的字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @return XML格式的字符串
|
||||
* @throws Exception 系统异常
|
||||
*/
|
||||
public static String mapToXml(Map<String, String> data) throws Exception {
|
||||
Document document = WXPayXmlUtil.newDocument();
|
||||
Element root = document.createElement("xml");
|
||||
document.appendChild(root);
|
||||
for (String key : data.keySet()) {
|
||||
String value = data.get(key);
|
||||
if (value == null) {
|
||||
value = "";
|
||||
}
|
||||
value = value.trim();
|
||||
Element filed = document.createElement(key);
|
||||
filed.appendChild(document.createTextNode(value));
|
||||
root.appendChild(filed);
|
||||
}
|
||||
TransformerFactory tf = TransformerFactory.newInstance();
|
||||
Transformer transformer = tf.newTransformer();
|
||||
DOMSource source = new DOMSource(document);
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
|
||||
// transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
StringWriter writer = new StringWriter();
|
||||
StreamResult result = new StreamResult(writer);
|
||||
transformer.transform(source, result);
|
||||
String output = writer.getBuffer().toString();
|
||||
try {
|
||||
writer.close();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成带有 sign 的 XML 格式字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @return 含有sign字段的XML
|
||||
*/
|
||||
public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
|
||||
return generateSignedXml(data, key, WeChatConstants.SignType.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带有 sign 的 XML 格式字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @param signType 签名类型
|
||||
* @return 含有sign字段的XML
|
||||
*/
|
||||
public static String generateSignedXml(final Map<String, String> data, String key, WeChatConstants.SignType signType) throws Exception {
|
||||
String sign = generateSignature(data, key, signType);
|
||||
data.put(WeChatConstants.FIELD_SIGN, sign);
|
||||
return mapToXml(data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断签名是否正确
|
||||
*
|
||||
* @param xmlStr XML格式数据
|
||||
* @param key API密钥
|
||||
* @return 签名是否正确
|
||||
* @throws Exception 系统异常
|
||||
*/
|
||||
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
|
||||
Map<String, String> data = xmlToMap(xmlStr);
|
||||
if (!data.containsKey(WeChatConstants.FIELD_SIGN)) {
|
||||
return false;
|
||||
}
|
||||
String sign = data.get(WeChatConstants.FIELD_SIGN);
|
||||
return generateSignature(data, key).equals(sign);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @return 签名是否正确
|
||||
* @throws Exception 系统异常
|
||||
*/
|
||||
public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
|
||||
return isSignatureValid(data, key, WeChatConstants.SignType.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断签名是否正确,必须包含sign字段,否则返回false。
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param key API密钥
|
||||
* @param signType 签名方式
|
||||
* @return 签名是否正确
|
||||
* @throws Exception 系统异常
|
||||
*/
|
||||
public static boolean isSignatureValid(Map<String, String> data, String key, WeChatConstants.SignType signType) throws Exception {
|
||||
if (!data.containsKey(WeChatConstants.FIELD_SIGN)) {
|
||||
return false;
|
||||
}
|
||||
String sign = data.get(WeChatConstants.FIELD_SIGN);
|
||||
return generateSignature(data, key, signType).equals(sign);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名
|
||||
*
|
||||
* @param data 待签名数据
|
||||
* @param key API密钥
|
||||
* @return 签名
|
||||
*/
|
||||
public static String generateSignature(final Map<String, String> data, String key) throws Exception {
|
||||
return generateSignature(data, key, WeChatConstants.SignType.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
|
||||
*
|
||||
* @param data 待签名数据
|
||||
* @param key API密钥
|
||||
* @param signType 签名方式
|
||||
* @return 签名
|
||||
*/
|
||||
public static String generateSignature(final Map<String, String> data, String key, WeChatConstants.SignType signType) throws Exception {
|
||||
Set<String> keySet = data.keySet();
|
||||
String[] keyArray = keySet.toArray(new String[0]);
|
||||
Arrays.sort(keyArray);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String k : keyArray) {
|
||||
if (k.equals(WeChatConstants.FIELD_SIGN)) {
|
||||
continue;
|
||||
}
|
||||
// 参数值为空,则不参与签名
|
||||
if (!data.get(k).trim().isEmpty()) {
|
||||
sb.append(k).append("=").append(data.get(k).trim()).append("&");
|
||||
}
|
||||
}
|
||||
sb.append("key=").append(key);
|
||||
if (WeChatConstants.SignType.MD5.equals(signType)) {
|
||||
return MD5.create().digestHex(sb.toString()).toUpperCase();
|
||||
} else if (WeChatConstants.SignType.HMACSHA256.equals(signType)) {
|
||||
return HmacSHA256(sb.toString(), key);
|
||||
} else {
|
||||
throw new Exception(String.format("Invalid sign_type: %s", signType));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取随机字符串 Nonce Str
|
||||
*
|
||||
* @return String 随机字符串
|
||||
*/
|
||||
public static String generateNonceStr() {
|
||||
char[] nonceChars = new char[32];
|
||||
for (int index = 0; index < nonceChars.length; ++index) {
|
||||
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
|
||||
}
|
||||
return new String(nonceChars);
|
||||
}
|
||||
|
||||
|
||||
// /**
|
||||
// * 生成 MD5
|
||||
// *
|
||||
// * @param data 待处理数据
|
||||
// * @return MD5结果
|
||||
// */
|
||||
// public static String MD5(String data) throws Exception {
|
||||
// MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
// byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
|
||||
// StringBuilder sb = new StringBuilder();
|
||||
// for (byte item : array) {
|
||||
// sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
|
||||
// }
|
||||
// return sb.toString().toUpperCase();
|
||||
// }
|
||||
|
||||
/**
|
||||
* 生成 HmacSHA256
|
||||
*
|
||||
* @param data 待处理数据
|
||||
* @param key 密钥
|
||||
* @return 加密结果
|
||||
* @throws NoSuchAlgorithmException,InvalidKeyException 系统异常
|
||||
*/
|
||||
public static String HmacSHA256(String data, String key) throws NoSuchAlgorithmException, InvalidKeyException {
|
||||
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
||||
sha256_HMAC.init(secret_key);
|
||||
byte[] array = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte item : array) {
|
||||
sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
|
||||
}
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间戳,单位秒
|
||||
*/
|
||||
public static long getCurrentTimestamp() {
|
||||
return System.currentTimeMillis() / 1000;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.starry.admin.common.play.wx;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "wx.play")
|
||||
@PropertySource(value = {"classpath:play.properties"})
|
||||
public class WxPlayProperties implements InitializingBean {
|
||||
|
||||
/**
|
||||
* 设置微信公众号或者小程序等的appid
|
||||
*/
|
||||
private String appId;
|
||||
/**
|
||||
* 微信支付商户号
|
||||
*/
|
||||
private String mchId;
|
||||
|
||||
/**
|
||||
* 证书相对路径
|
||||
*/
|
||||
private String privateKeyPath;
|
||||
|
||||
/**
|
||||
* 证书相对路径
|
||||
*/
|
||||
private String privateCertPath;
|
||||
|
||||
/**
|
||||
* 下单回调地址
|
||||
*/
|
||||
private String returnUrl;
|
||||
|
||||
/**
|
||||
* 退款回调地址
|
||||
*/
|
||||
private String refundUrl;
|
||||
|
||||
|
||||
/**
|
||||
* apiV3key
|
||||
*/
|
||||
private String apiV3key;
|
||||
|
||||
|
||||
public static String APP_ID = "";
|
||||
public static String MCH_ID = "";
|
||||
public static String PRIVATE_KEY_PATH = "";
|
||||
public static String PRIVATE_CERT_PATH = "";
|
||||
public static String RETURN_URL = "";
|
||||
public static String REFUND_URL = "";
|
||||
public static String API_V3KEY = "";
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
APP_ID = getAppId();
|
||||
MCH_ID = getMchId();
|
||||
PRIVATE_KEY_PATH = getPrivateKeyPath();
|
||||
PRIVATE_CERT_PATH = getPrivateCertPath();
|
||||
RETURN_URL = getReturnUrl();
|
||||
REFUND_URL = getRefundUrl();
|
||||
API_V3KEY = getApiV3key();
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@ import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
|
||||
import com.starry.admin.modules.clerk.service.impl.PlayClerkUserInfoServiceImpl;
|
||||
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
|
||||
import com.starry.admin.modules.custom.service.impl.PlayCustomUserInfoServiceImpl;
|
||||
import com.starry.admin.modules.platform.entity.SysTenantEntity;
|
||||
import com.starry.admin.modules.platform.service.ISysTenantService;
|
||||
import com.starry.admin.modules.system.entity.SysTenantEntity;
|
||||
import com.starry.admin.modules.system.service.ISysTenantService;
|
||||
import com.starry.admin.modules.system.service.SysUserService;
|
||||
import com.starry.admin.modules.weichat.service.WxTokenService;
|
||||
import com.starry.admin.utils.SecurityUtils;
|
||||
|
||||
@@ -8,11 +8,10 @@ import com.starry.admin.modules.clerk.service.IPlayClerkWagesDetailsInfoService;
|
||||
import com.starry.admin.modules.clerk.service.IPlayClerkWagesInfoService;
|
||||
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
|
||||
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
|
||||
import com.starry.admin.modules.platform.entity.SysTenantEntity;
|
||||
import com.starry.admin.modules.platform.service.ISysTenantService;
|
||||
import com.starry.admin.modules.system.entity.SysTenantEntity;
|
||||
import com.starry.admin.modules.system.service.ISysTenantService;
|
||||
import com.starry.admin.utils.SecurityUtils;
|
||||
import com.starry.common.utils.IdUtils;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@@ -6,8 +6,8 @@ import com.starry.admin.modules.clerk.service.IPlayClerkRankingInfoService;
|
||||
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
|
||||
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
|
||||
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
|
||||
import com.starry.admin.modules.platform.entity.SysTenantEntity;
|
||||
import com.starry.admin.modules.platform.service.ISysTenantService;
|
||||
import com.starry.admin.modules.system.entity.SysTenantEntity;
|
||||
import com.starry.admin.modules.system.service.ISysTenantService;
|
||||
import com.starry.admin.utils.SecurityUtils;
|
||||
import com.starry.common.utils.IdUtils;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
Reference in New Issue
Block a user