微信支付、回调、订单查询;

微信用户登录、用户信息查询、修改用户信息、同意用户协议;
文件OSS上传、删除接口;
This commit is contained in:
songmingsong
2024-12-05 17:33:25 +08:00
parent 4822174c5e
commit ffc9fcb95c
39 changed files with 2074 additions and 133 deletions

View File

@ -142,8 +142,8 @@ public class ApiResponse<T> implements Serializable {
public static <T> ApiResponse<T> buildResult(BizCodeEnum bizCodeEnum) {
ApiResponse<T> apiResponse = new ApiResponse();
apiResponse.setCode(bizCodeEnum.code);
apiResponse.setMsg(bizCodeEnum.message);
apiResponse.setCode(bizCodeEnum.getCode());
apiResponse.setMsg(bizCodeEnum.getMessage());
return apiResponse;
}

View File

@ -0,0 +1,31 @@
package com.ycwl.basic.utils;
import org.apache.http.StatusLine;
/**
* Http服务工具类
* @author songmingsong
*/
public class HttpServiceUtil {
/**
* 请求OK代码
*/
public static final int REQUEST_OK_CODE=200;
/**
* 无响应内容
*/
public static final String REQUEST_NO_RESULT="No_Result";
/**
* 是否响应成功
* @param status 响应状态
* @return boolean
*/
public static boolean success(StatusLine status) {
return status.getStatusCode() == REQUEST_OK_CODE;
}
}

View File

@ -60,55 +60,4 @@ public class JwtTokenUtil {
throw new CheckTokenException("token is invalid");
}
}
/*********************************************** 测试 ***************************************************/
/**
* 测试 token
*
* @param args
*/
// public static void main(String[] args) throws Exception {
//
// JwtInfo jwtInfo = new JwtInfo("阿豹", "1", "role1", "yangchen", 1, LocalDateTime.now(), new HashMap<>());
//
// long a = Instant.now().toEpochMilli();
//
// JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
// String token = jwtTokenUtil.generateToken(jwtInfo);
//
// log.info("==> generate token: " + (Instant.now().toEpochMilli() - a) + " ms");
//
// System.out.println("=======");
// System.out.println();
//
// System.out.println(token);
//
// System.out.println();
// System.out.println("=======");
//
// long b = Instant.now().toEpochMilli();
//
// JwtInfo jwtInfo1 = jwtTokenUtil.parsingToken(token);
//
// log.info("==> paring token end " + (Instant.now().toEpochMilli() - b) + " ms");
//
// System.out.println();
// System.out.println();
// System.out.println();
// System.out.println(jwtInfo);
// System.out.println("=======");
// System.out.println(jwtInfo1.toString());
//
// }
public static void main(String[] args) throws Exception {
JwtInfo jwtInfo = new JwtInfo();
jwtInfo.setUserId("1");
LocalDateTime expireTime = LocalDateTime.now().plusDays(9999999);
byte[] bytes = RsaKeyUtil.toBytes(PRI_KEY);
String token = JwtAnalysisUtil.generateToken(jwtInfo, bytes, expireTime);
System.out.println(token);
}
}

View File

@ -0,0 +1,85 @@
package com.ycwl.basic.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.ycwl.basic.config.OssConfig;
import com.ycwl.basic.enums.BizCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.InputStream;
@Slf4j
@Component
public class OssUtil {
@Autowired
private OssConfig ossConfig;
public String uploadFile(InputStream inputStream, String filename) {
String uploadFileName = ossConfig.getObjectName() + System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndPoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
try {
PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), uploadFileName, inputStream);
ossClient.putObject(putObjectRequest);
String fileUrl = ossConfig.getUrl() + uploadFileName;
return fileUrl;
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason."
+ " \n Error Message:" + oe.getErrorMessage()
+ " \n Error Code:" + oe.getErrorCode()
+ " \n Request ID:" + oe.getRequestId()
+ " \n Host ID:" + oe.getHostId()
);
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network."
+ "Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return BizCodeEnum.UPLOAD_FAILED.getMessage();
}
public boolean deleteFile(String filename) {
// 填写文件完整路径。文件完整路径中不能包含Bucket名称。
String objectName = filename;
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndPoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
try {
// 删除文件或目录。如果要删除目录,目录必须为空。
ossClient.deleteObject(ossConfig.getBucketName(), objectName);
return true;
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason."
+ " \n Error Message:" + oe.getErrorMessage()
+ " \n Error Code:" + oe.getErrorCode()
+ " \n Request ID:" + oe.getRequestId()
+ " \n Host ID:" + oe.getHostId()
);
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network."
+ "Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return false;
}
}

View File

@ -0,0 +1,98 @@
package com.ycwl.basic.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* SSL工具类
*
* @author songmingsong
*/
@Slf4j
public class SslUtil {
/**
* 获取HtttpClient对象
*
* @return CloseableHttpClient
*/
public static CloseableHttpClient sslHttpClientBuild() {
Registry<ConnectionSocketFactory> socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", trustAllHttpsCertificates()).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
return httpClient;
}
/**
* 信任所有Http证书
*
* @return SSLConnectionSocketFactory
*/
private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
SSLConnectionSocketFactory socketFactory = null;
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new X509TrustManager() {
@Override
// 返回受信任的X509证书数组。
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
// 该方法检查服务器的证书,若不信任该证书同样抛出异常。通过自己实现该方法,可以使之信任我们指定的任何证书。
// 在实现该方法时,也可以简单的不做任何处理,即一个空的函数体,由于不会抛出异常,它就会信任任何证书。
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
if (chain!=null&&chain.length>0) {
chain[0].checkValidity();
}
} catch (Exception e) {
log.error("checkServerTrusted",e);
}
}
@Override
// 该方法检查客户端的证书,若不信任该证书则抛出异常。由于我们不需要对客户端进行认证,
// 因此我们只需要执行默认的信任管理器的这个方法。JSSE中,默认的信任管理器类为TrustManager。
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
if (chain!=null&&chain.length>0) {
chain[0].checkValidity();
}
} catch (Exception e) {
log.error("checkClientTrusted",e);
}
}
};
trustAllCerts[0] = tm;
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, trustAllCerts, null);
socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
// HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
log.error("trustAllHttpsCertificates", e);
}
return socketFactory;
}
}

View File

@ -0,0 +1,49 @@
package com.ycwl.basic.utils;
import com.wechat.pay.java.core.util.PemUtil;
import org.springframework.util.Base64Utils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Random;
/**
* @Author: songmingsong
* @CreateTime: 2024-12-05
* @Description: 微信支付
* @Version: 1.0
*/
public class WXPayUtil {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
public static String getSign(String signatureStr,String privateKey) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, IOException, URISyntaxException {
//replace 根据实际情况,不一定都需要
String replace = privateKey.replace("\\n", "\n");
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKeyFromPath(replace);
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(merchantPrivateKey);
sign.update(signatureStr.getBytes(StandardCharsets.UTF_8));
return Base64Utils.encodeToString(sign.sign());
}
/**
* 获取随机字符串 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);
}
}