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;
/**
* @ClassName: WeChatController
* @Author zhaohp
* @Date 2019/2/18 14:57
* @Description: 微信相关操作
*/
@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 {
//根据code近一步获取openId和token
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);
//redis存储半个小时
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() {
//使用redis缓存
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) {
//使用redis缓存
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;
}
/**
* 验证微信后台配置的服务器地址有效性
*
* 接收并校验四个请求参数
*
* @param url URL
* @param timestamp 时间戳
* @param ticket ticket
* @param echostr 随机字符串
* @return echostr
*/
@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);
/* 加密/校验流程如下:
*1. 将token、timestamp、nonce三个参数进行字典序排序
* 2. 将三个参数字符串拼接成一个字符串进行sha1加密
* 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 */
logger.info("微信-开始排序");
// 1.排序
String sortString = sort(url, timestamp, ticket, echostr);
logger.info("微信-开始sha1加密");
// 2.sha1加密
String signature = sha1(sortString);
// 工具类的加密方法
// String signature = DigestUtils.sha1Hex(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;
}
/**
* @Author zhaohp
* @Date 2018/12/10 19:50
* @Param [signature, timestamp, ticket, echostr]
* @Return java.lang.String
* @Description: 对所有待签名参数按照字段名的ASCII 码从小到大排序
*/
public String sort(String url, String timestamp, String ticket, String echostr) {
return "jsapi_ticket=" + ticket + "&noncestr=" + echostr + "×tamp=" + timestamp + "&url=" + url;
}
/**
* @Author zhaohp
* @Date 2018/12/10 19:51
* @Param [str]
* @Return java.lang.String
* @Description: 将字符串进行sha1加密
*/
public String sha1(String str) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
// 创建 16进制字符串
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 "";
}
/**
* 解密并且获取用户手机号码
*
* @param encrypdata
* @param ivdata
* @param loginKey
* @return
* @throws Exception
*/
@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;
/**
* @ClassName: WeChatCommonUtil
* @Author zhaohp
* @Date 2018/12/10 18:18
* @Description: 微信工具类
*/
@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;
}
/***
* @Author zhaohp
* @Date 2018/12/14 10:57
* @Param [requestUrl 请求地址, requestMethod 请求方式(GET、POST), outputStr 提交的数据]
* @Return com.alibaba.fastjson.JSONObject
* @Description: JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
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 conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
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;
}
/***
* @Author zhaohp
* @Date 2018/12/14 10:56
* @Param [appid, appsecret] 凭证,密钥
* @Return com.zichan360.domain.weChat.Token
* @Description: 获取接口访问凭证
*/
public static JSONObject getToken(String appid, String appsecret) {
String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
// 发起GET请求获取凭证
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
return jsonObject;
}
/***
* @Author zhaohp
* @Date 2018/12/14 10:56
* @Param [accessToken]
* @Return com.alibaba.fastjson.JSONObject
* @Description: 获取access_token
*/
public static JSONObject getTicket(String accessToken) {
String requestUrl = ticket_url.replace("ACCESS_TOKEN", accessToken);
// 发起GET请求获取凭证
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;
/**
* @ClassName: MyX509TrustManager
* @Author zhaohp
* @Date 2018/12/10 18:18
* @Description: 信任管理器
*/
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
weChat:
#获取token
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: ***********************