package com.zichan360.controller;
import com.alibaba.fastjson.JSONObject;
import com.zichan360.common.result.Result;
import com.zichan360.common.result.ResultUtil;
import com.zichan360.common.utils.MD5Util;
import com.zichan360.common.utils.weChatUtils.WeChatCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/weChat")
@Api(description = "微信相关操作")
@Slf4j
public class WeChatController {
@Value("${weChat.APP_ID}")
private String APP_ID;
@Value("${weChat.APP_SECRET}")
private String APP_SECRET;
@Value("${weChat.USER_CODE_GET_TOKEN_URL}")
private String USER_CODE_GET_TOKEN_URL;
@Value("${weChat.ACCESS_TOKEN}")
private String ACCESS_TOKEN;
@Autowired
StringRedisTemplate redisTemplate;
@ApiOperation("保存OpenId")
@GetMapping("/saveOpenId")
public Result saveOpenId(@RequestParam("code") @ApiParam(value = "code", required = true) String code) throws Exception {
String url = USER_CODE_GET_TOKEN_URL.replace("APPID", APP_ID).replace("SECRET", APP_SECRET).replace("JSCODE", code);
JSONObject jsonObject = WeChatCommonUtil.httpsRequest(url, "GET", null);
if (jsonObject.containsKey("openid")) {
String openid = jsonObject.getString("openid");
String sessionKey = jsonObject.getString("session_key");
String token = MD5Util.md5(openid, sessionKey);
redisTemplate.opsForValue().set("WeChatAppletAiExperience:weChat:session_key:" + token, openid + "," + sessionKey, 30, TimeUnit.MINUTES);
return ResultUtil.success(token);
}
return ResultUtil.error(jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
}
@ApiIgnore
@ApiOperation("获取接口调用凭证")
@GetMapping("/getToken")
public JSONObject getToken() {
if (redisTemplate.hasKey("weixin:access_token")) {
JSONObject jsonObject = new JSONObject();
String accessToken = redisTemplate.opsForValue().get("weixin:access_token");
Long expiresIn = redisTemplate.getExpire("weixin:access_token", TimeUnit.SECONDS);
jsonObject.put("access_token", accessToken);
jsonObject.put("expires_in", expiresIn);
return jsonObject;
}
JSONObject jsonObject = WeChatCommonUtil.getToken(APP_ID, APP_SECRET);
System.out.println(jsonObject.toJSONString());
redisTemplate.opsForValue().set("weixin:access_token", jsonObject.getString("access_token"), jsonObject.getLong("expires_in"), TimeUnit.SECONDS);
return jsonObject;
}
@GetMapping("/getTicket")
public JSONObject getTicket(@RequestParam(value = "accessToken", required = false) String accessToken) {
if (redisTemplate.hasKey("weixin:jsapi_ticket")) {
JSONObject jsonObject = new JSONObject();
String ticket = redisTemplate.opsForValue().get("weixin:jsapi_ticket");
Long expiresIn = redisTemplate.getExpire("weixin:jsapi_ticket", TimeUnit.SECONDS);
jsonObject.put("ticket", ticket);
jsonObject.put("expires_in", Math.toIntExact(expiresIn));
jsonObject.put("errcode", 0);
jsonObject.put("errmsg", "OK");
return jsonObject;
}
if (StringUtils.isNotBlank(accessToken)) {
redisTemplate.opsForValue().set("weixin:access_token", accessToken, 7200L, TimeUnit.SECONDS);
return CommonUtil.getTicket(accessToken);
}
accessToken = getToken().getString("access_token");
JSONObject jsonObject = WeChatCommonUtil.getTicket(accessToken);
redisTemplate.opsForValue().set("weixin:jsapi_ticket", jsonObject.getString("ticket"), jsonObject.getLong("expires_in"), TimeUnit.SECONDS);
return jsonObject;
}
@GetMapping("/getSignature")
public Map<String, String> checkName(@RequestParam(name = "url") String url,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "ticket", required = false) String ticket,
@RequestParam(name = "echostr", required = false) String echostr) {
if (StringUtils.isBlank(timestamp)) {
timestamp = String.valueOf(System.currentTimeMillis() / 1000);
}
if (StringUtils.isBlank(echostr)) {
echostr = RandomStringUtils.randomAlphanumeric(10);
}
if (StringUtils.isBlank(ticket)) {
JSONObject jsonObject = getTicket("");
ticket = jsonObject.getString("ticket");
}
logger.info("微信-开始校验签名");
logger.info("收到来自微信的 echostr 字符串:{}", echostr);
logger.info("微信-开始排序");
String sortString = sort(url, timestamp, ticket, echostr);
logger.info("微信-开始sha1加密");
String signature = sha1(sortString);
Map map = new HashMap<>();
map.put("appId", APP_ID);
map.put("url", url);
map.put("timestamp", timestamp);
map.put("ticket", ticket);
map.put("echostr", echostr);
map.put("str", sortString);
map.put("signature", signature );
return map;
}
public String sort(String url, String timestamp, String ticket, String echostr) {
return "jsapi_ticket=" + ticket + "&noncestr=" + echostr + "×tamp=" + timestamp + "&url=" + url;
}
public String sha1(String str) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
@ApiOperation("解密并且获取用户手机号码")
@GetMapping("/deciphering")
public String deciphering(@ApiParam(value = "encrypdata", required = true) @RequestParam("encrypdata") String encrypdata,
@ApiParam(value = "ivdata", required = true) @RequestParam("ivdata") String ivdata,
@CookieValue("loginKey")String loginKey) {
byte[] encrypData = Base64.decode(encrypdata);
byte[] ivData = Base64.decode(ivdata);
String sessionkey = redisTemplate.opsForValue().get("WeChatAppletAiExperience:weChat:session_key:" + loginKey);
sessionkey = sessionkey.substring(sessionkey.indexOf(",") + 1);
byte[] sessionKey = Base64.decode(sessionkey);
String str = "";
try {
str = decrypt(sessionKey, ivData, encrypData);
} catch (Exception e) {
e.printStackTrace();
}
log.info(str);
return str;
}
public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(encData), "UTF-8");
}
}
package com.zichan360.common.utils.weChatUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
@Slf4j
public class WeChatCommonUtil {
public static String token_url;
@Value("${weChat.ACCESS_TOKEN}")
public void token_url(String url) {
WeChatCommonUtil.token_url = url;
}
public static String ticket_url;
@Value("${weChat.ACCESS_TICKET}")
public void ticket_url(String url) {
WeChatCommonUtil.token_url = url;
}
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
}
public static JSONObject getToken(String appid, String appsecret) {
String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
return jsonObject;
}
public static JSONObject getTicket(String accessToken) {
String requestUrl = ticket_url.replace("ACCESS_TOKEN", accessToken);
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
return jsonObject;
}
}
package com.zichan360.common.utils.weChatUtils;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
weChat:
USER_CODE_GET_TOKEN_URL: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
ACCESS_TOKEN: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
ACCESS_TICKET: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
APP_ID: ************
APP_SECRET: ***********************