package com.smtaiserver.smtaiserver.weixinLogin;
|
|
import cn.hutool.core.util.ArrayUtil;
|
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.http.HttpUtil;
|
import com.fasterxml.jackson.core.type.TypeReference;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.smtaiserver.smtaiserver.core.SMTAIServerApp;
|
import com.smtservlet.util.Json;
|
|
import java.util.Map;
|
|
/**
|
* description: WeChatUtils 微信获取用户工具类<br>
|
*
|
* @date: 2021/8/19 0019 上午 10:05 <br>
|
* @author: William <br>
|
* version: 1.0 <br>
|
*/
|
public class WeChatUtils {
|
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
/**
|
* 获取微信accessToken路径
|
*/
|
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
|
|
public WeChatUtils() throws Exception {
|
}
|
|
|
/**
|
* description: getAccessToken 根据code获取accessToken<br>
|
* version: 1.0 <br>
|
*
|
* @param code 微信用户授权code
|
* @return java.util.Map<java.lang.String, java.lang.String>
|
* @date: 2021/8/19 0019 上午 10:10 <br>
|
* @author: William <br>
|
*/
|
public static Map<String, String> getAccessToken(String code) throws Exception {
|
Json weixinAppidSecret = (Json) SMTAIServerApp.getApp().getGlobalConfig("weixin_appid_secret");
|
String appid = weixinAppidSecret.safeGetStr("appid", null);
|
String secret = weixinAppidSecret.safeGetStr("secret", null);
|
return getAccessToken(code, appid, secret);
|
}
|
|
/**
|
* description: getAccessToken 根据code获取微信用户信息,返回map如果正确map包含access_token ,如果错误则包含:errcode<br>
|
* version: 1.0 <br>
|
*
|
* @param code 微信授权code
|
* @param appId 微信appId
|
* @param appSecret 微信appSecret
|
* @return java.util.Map<java.lang.String, java.lang.String>
|
* @date: 2021/8/19 0019 上午 10:11 <br>
|
* @author: William <br>
|
*/
|
public static Map<String, String> getAccessToken(String code, String appId, String appSecret) throws Exception {
|
//判断所有字段不能为空
|
if (isAnyBlank(code, appId, appSecret)) {
|
throw new IllegalArgumentException("参数错误");
|
}
|
String requestUrl = GET_ACCESS_TOKEN_URL
|
.replace("APPID", appId)
|
.replace("SECRET", appSecret)
|
.replace("CODE", code);
|
String result = HttpUtil.get(requestUrl);
|
return parseMap(result);
|
}
|
|
/**
|
* description: isAnyBlank 判断是否存在空字符串,Hutool未编写<br>
|
* version: 1.0 <br>
|
*
|
* @param strs 字符串
|
* @return java.lang.Boolean
|
* @date: 2021/8/19 0019 上午 10:25 <br>
|
* @author: William <br>
|
*/
|
public static Boolean isAnyBlank(CharSequence... strs) {
|
//如果为空直接返回true
|
if (ArrayUtil.isEmpty(strs)) {
|
return true;
|
}
|
for (CharSequence str : strs) {
|
if (StrUtil.isBlank(str)) {
|
return true;
|
}
|
}
|
return false;
|
}
|
|
public static Map<String, String> parseMap(String json) {
|
try {
|
return OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, String>>() {
|
});
|
} catch (Exception e) {
|
throw new RuntimeException("JSON 解析失败", e);
|
}
|
}
|
|
}
|