最新代码

This commit is contained in:
admin
2024-05-06 10:20:46 +08:00
parent a0cd0312a5
commit 2919029b81
126 changed files with 5276 additions and 1137 deletions

View File

@@ -11,6 +11,8 @@ import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
@@ -32,7 +34,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.setFieldValByName("createdTime", new Date(), metaObject);
// this.setFieldValByName("createdTime", getDate(), metaObject);
this.setFieldValByName("deleted", false, metaObject);
this.setFieldValByName("version", 1L, metaObject);
Object createUser = this.getFieldValByName("createdBy", metaObject);
@@ -46,13 +48,20 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.setFieldValByName("updatedTime", new Date(), metaObject);
// this.setFieldValByName("updatedTime", getDate(), metaObject);
Object createUser = this.getFieldValByName("updatedBy", metaObject);
if (createUser == null) {
this.setFieldValByName("createdBy", getOperatorId(), metaObject);
}
}
public Date getDate() {
LocalDateTime localDateTime = LocalDateTime.now();
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
// return Date.from(localDateTime.toInstant(ZoneOffset.ofHours(8)));
}
public String getOperatorId() {
if (request.getServletPath().startsWith("/wx/")) {
String tenantKey = request.getHeader("tenantkey");

View File

@@ -22,7 +22,7 @@ public class OssProperties implements InitializingBean {
public String bucketName;
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
ENDPOINT = getEndpoint();
KEY_ID = getAccessKeyId();
KEY_SECRET = getAccessKeySecret();

View File

@@ -0,0 +1,38 @@
package com.starry.admin.common.play.wx;
public class CommonText {
public static final String DATA_NOT_EXIST = "数据不存在";
/**
* 微信公众号
*/
public static final String WECHAT_CONFIG_DOES_NOT_EXIST = "未配置公司微信公众号的相关信息";
public static final String WECHAT_PAY_CONFIG_DOES_NOT_EXIST = "未配置公司微信支付的相关信息";
public static final String OPENID_DOES_NOT_EXIST = "请上传微信用户openid";
public static final String WECHAT_TRADE_TYPE_DOES_NOT_EXIST = "请上传微信支付交易类型";
public static final String OPENID_ALREADY_BIND = "该微信号已被其他账号绑定!";
public static final String ADMIN_OPENID_DOES_NOT_EXIST = "请上传管理员openid";
public static final String OPENID_DOES_NOT_FIND = "未获取到对应微信用户openid";
public static final String WECHAT_CODE_DOES_NOT_EXIST = "请上传微信用户code";
public static final String WECHAT_USER_TOKEN_DOES_ERR = "获取微信用户token失败";
public static final String UNIFIEDORDER_ERR = "统一下单失败";
public static final String UNIFIEDORDER_ERR_PREPAY_ID_NOT_FIND = "统一下单失败,未生成PREPAY_ID";
/**
* 微信小程序
*/
public static final String MINI_OPENID_DOES_NOT_EXIST = "请上传小程序用户openid";
public static final String WECHAT_MINI_CONFIG_DOES_NOT_EXIST = "未配置公司微信小程序的相关信息";
public static final String WECHAT_MINI_PARAM_NOT_EXIST = "缺少所需小程序参数!";
public static final String WECHAT_MINI_IV_NOT_EXIST = "请上传iv参数";
public static final String WECHAT_MINI_SESSION_KEY_DOES_NOT_EXIST = "请上传session_key参数";
public static final String WECHAT_MINI_ENCRYPTED_DATA_DOES_NOT_EXIST = "请上传encrypted_data参数";
public static final String WECHAT_MINI_ENCRYPTED_DATA_PARSE_ERR = "encrypted_data解析失败";
public static final String WECHAT_MINI_ENCRYPTED_DATA_NOT_HAVE_PHONE_NUM = "encrypted_data中未解析出电话号码";
/**
* 支付相关
*/
public static final String ORDER_PAY_TYPE_NOT_EXIST = "请上传支付方式!";
}

View File

@@ -0,0 +1,199 @@
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;
}
// /**
// * 向指定 URL 发送POST方法的请求
// *
// * @param url 发送请求的 URL
// * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
// * @return 所代表远程资源的响应结果
// */
// public static String sendPost(String url, String param) {
// URLConnection conn = getConnection(url);
// StringBuilder result = new StringBuilder();
// try (PrintWriter out = new PrintWriter(conn.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
// out.print(param);
// out.flush();
// String line;
// while ((line = in.readLine()) != null) {
// result.append(line);
// }
// } catch (Exception e) {
// log.error("sendPost error", e);
// }
// return result.toString();
// }
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 errorurl = {},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());
}
}
}

View File

@@ -0,0 +1,28 @@
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;
}
}

View File

@@ -0,0 +1,27 @@
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();
}
}

View File

@@ -0,0 +1,45 @@
package com.starry.admin.common.play.wx;
public class WeChatConstants {
public enum SignType {
MD5, HMACSHA256
}
public static final String FIELD_SIGN = "sign";
/**
* 支付成功回调地址
*/
public static String NOTIFY_URL = "http://8.142.116.233:8001/pay/wxpay/callback";
/**
* 支付证书路径
*/
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";
}

View File

@@ -0,0 +1,69 @@
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();
}
}

View File

@@ -0,0 +1,354 @@
package com.starry.admin.common.play.wx;
import cn.hutool.core.util.IdUtil;
import com.github.wxpay.sdk.WXPayUtil;
import com.starry.admin.common.exception.CustomException;
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.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
@Slf4j
public class WxPlayUtils {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
/**
* @param openId 微信公众号ID
* @param appid 用户ID
* @param mchId 商户ID
* @param orderId 订单ID
* @param spBillCreateIp 终端设备ID
* @param body 商品描述
* @param totalFee 商品金额
* @param attach 附加数据在查询API和支付通知中原样返回可作为自定义参数使用传入租户ID
* @return
* @throws Exception
*/
public static String unifiedOrderJSAPI(String openId, String appid, String mchId, String orderId, String spBillCreateIp, String body, String attach, int totalFee) throws Exception {
Map<String, String> playRequestParameters = new HashMap<>();
playRequestParameters.put("appid", appid);
playRequestParameters.put("mch_id", mchId);
playRequestParameters.put("nonce_str", IdUtil.fastSimpleUUID());
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", WxPlayProperties.RETURN_URL);
playRequestParameters.put("trade_type", "JSAPI");
playRequestParameters.put("openId", openId);
String nonce_str = IdUtil.fastSimpleUUID();
//生成签名, 统一下单
log.debug("paraMap------------{}", playRequestParameters);
String sign = WXPayUtil.generateSignature(playRequestParameters, orderId);
log.debug("sign:{}", sign);
playRequestParameters.put("sign", sign);
String xml = WXPayUtil.mapToXml(playRequestParameters);//将所有参数(map)转xml格式
String new_xml = new String(xml.getBytes(StandardCharsets.UTF_8));
log.debug("xml:{}", new_xml);
//发送post请求"统一下单接口"返回预支付id:prepay_id
String xmlStr = HttpUtils.sendPost(WeChatConstants.UNIFIEDORDER_URL, generateSignedXml(playRequestParameters, orderId));
// String xmlStr = HttpUtils.sendPost(WeChatConstants.UNIFIEDORDER_URL, generateSignedXml(playRequestParameters, orderId));
log.debug("xmlStr:{}", xmlStr);
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", IdUtil.fastSimpleUUID());
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(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;
}
}

View File

@@ -23,6 +23,9 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import javax.annotation.Resource;
import java.util.Set;
@@ -58,7 +61,7 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/login", "/captcha/get-captcha", "/wx/**").permitAll()
// 跨域请求会先进行一次options请求
.antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest()// 除上面外的所有请求全部需要鉴权认证
.authenticated();
.authenticated().and().cors().configurationSource(this.corsConfigurationSource());
// 禁用缓存
httpSecurity.headers().cacheControl();
// 添加Logout filter
@@ -69,6 +72,18 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
httpSecurity.exceptionHandling().accessDeniedHandler(customAccessDeniedHandler).authenticationEntryPoint(customAuthenticationEntryPoint);
}
private CorsConfigurationSource corsConfigurationSource(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedHeader("*"); // 这个得加上一些复杂的请求方式会带有header不加上跨域会失效。
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addExposedHeader("*");
corsConfiguration.addAllowedOriginPattern("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);
return source;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());

View File

@@ -5,7 +5,9 @@ import cn.hutool.core.util.StrUtil;
import com.starry.admin.common.component.JwtToken;
import com.starry.admin.common.domain.LoginUser;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.clear.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clear.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;
@@ -23,11 +25,11 @@ import org.springframework.web.servlet.HandlerExceptionResolver;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author admin
@@ -61,29 +63,62 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) throws ServletException, IOException {
// 微信公众号的请求
if (httpServletRequest.getServletPath().startsWith("/wx/")) {
String clerkToken = httpServletRequest.getHeader(Constants.CLERK_USER_LOGIN_TOKEN);
String customToken = httpServletRequest.getHeader(Constants.CUSTOM_USER_LOGIN_TOKEN);
String tenantKey = httpServletRequest.getHeader("tenantkey");
String tenantId = getTenantId(clerkToken, customToken, tenantKey);
if (!checkTenantId(tenantId)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
SecurityUtils.setTenantId(tenantId);
} else {
// 管理端的请求
LoginUser jwtUser = jwtToken.getNewLoginUser(httpServletRequest);
if (null != jwtUser && null == SecurityContextHolder.getContext().getAuthentication()) {
jwtToken.verifyToken(jwtUser);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
protected void doFilterInternal(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) {
log.info("url = {}", httpServletRequest.getRequestURI());
try {
// 微信公众号的请求必须存在tenantkey否则抛出异常
if (httpServletRequest.getServletPath().startsWith("/wx/")) {
String tenantKey = httpServletRequest.getHeader("tenantkey");
if (StrUtil.isBlank(tenantKey)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("tenantkey不能为空"));
return;
}
Map<String, String> notLoginUrls = new HashMap<>();
notLoginUrls.put("/wx/common/area/tree", "1");
notLoginUrls.put("/wx/common/file/upload", "1");
notLoginUrls.put("/wx/common/audio/upload", "1");
notLoginUrls.put("/wx/oauth2/getConfigAddress", "1");
notLoginUrls.put("/clerk/level/queryAll", "1");
notLoginUrls.put("/wx/clerk/class/queryAll", "1");
notLoginUrls.put("/wx/clerk/user/queryByPage", "1");
notLoginUrls.put("/wx/clerk/user/queryGiftById", "1");
notLoginUrls.put("/wx/clerk/user/queryPriceById", "1");
notLoginUrls.put("/wx/clerk/user/queryTrendsById", "1");
notLoginUrls.put("/wx/clerk/user/queryEvaluateById", "1");
if (notLoginUrls.containsKey(httpServletRequest.getServletPath())) {
String tenantId = getTenantId(null, null, tenantKey);
if (!checkTenantId(tenantId)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
SecurityUtils.setTenantId(tenantId);
} else {
String clerkToken = httpServletRequest.getHeader(Constants.CLERK_USER_LOGIN_TOKEN);
String customToken = httpServletRequest.getHeader(Constants.CUSTOM_USER_LOGIN_TOKEN);
String tenantId = getTenantId(clerkToken, customToken, tenantKey);
if (!checkTenantId(tenantId)) {
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户信息异常"));
return;
}
SecurityUtils.setTenantId(tenantId);
}
} else {
// 管理端的请求
LoginUser jwtUser = jwtToken.getNewLoginUser(httpServletRequest);
if (null != jwtUser && null == SecurityContextHolder.getContext().getAuthentication()) {
jwtToken.verifyToken(jwtUser);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
} catch (Exception e) {
log.error("系统异常", e);
resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("租户及授权验证失败"));
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
@@ -98,27 +133,34 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
*/
public String getTenantId(String clerkToken, String customToken, String tenantKey) {
String tenantId = "";
//如果用户陪玩或客户已登录从token中获取租户ID
if (StrUtil.isNotBlank(clerkToken) || StrUtil.isNotBlank(customToken)) {
String userId;
try {
userId = tokenService.getWxUserIdByToken(StrUtil.isNotBlank(clerkToken) ? clerkToken : customToken);
} catch (Exception e) {
return "";
}
if (clerkToken != null) {
try {
//如果用户陪玩或客户已登录从token中获取租户ID
if (StrUtil.isNotBlank(clerkToken) || StrUtil.isNotBlank(customToken)) {
String userId = tokenService.getWxUserIdByToken(StrUtil.isNotBlank(clerkToken) ? clerkToken : customToken);
String redisKey = "TENANT_INFO:" + userId;
SecurityUtils.setTenantId(redisCache.getCacheObject(redisKey));
tenantId = clerkUserInfoService.selectById(userId).getTenantId();
if (clerkToken != null) {
PlayClerkUserInfoEntity entity = clerkUserInfoService.selectById(userId);
if (entity == null) {
log.error("当前登录陪玩不存在,clerkToken={}tenantKey={}", clerkToken, tenantKey);
}
tenantId = entity != null ? entity.getTenantId() : "";
} else {
PlayCustomUserInfoEntity entity = customUserInfoService.selectById(userId);
if (entity == null) {
log.error("当前登录顾客不存在,customToken={}tenantKey={}", customToken, tenantKey);
}
tenantId = entity != null ? entity.getTenantId() : "";
}
} else {
tenantId = customUserInfoService.selectById(userId).getTenantId();
}
} else {
// 如果用户未登录从tenantKey中获取租户ID然后验证租户ID是否存在以及租户是否过期等
SysTenantEntity entity = sysTenantService.selectByTenantKey(tenantKey);
if (entity != null) {
tenantId = entity.getTenantId();
// 如果用户未登录从tenantKey中获取租户ID然后验证租户ID是否存在以及租户是否过期等
SysTenantEntity entity = sysTenantService.selectByTenantKey(tenantKey);
if (entity != null) {
tenantId = entity.getTenantId();
}
}
} catch (Exception e) {
log.error("获取tenantKey异常clerkToken={},customToken={},tenantKey = {}", clerkToken, customToken, tenantKey, e);
}
return tenantId;
}