package com.finance.common.utils;
|
|
import com.alibaba.fastjson2.JSONObject;
|
import com.finance.common.config.WxConfig;
|
import com.finance.common.core.redis.RedisCache;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.client.RestTemplate;
|
|
import java.text.MessageFormat;
|
|
/**
|
* @author liheng
|
* @ClassName WxAppletTools
|
* @Description
|
* @date 2020-12-04 13:55
|
*/
|
@Slf4j
|
@Component
|
public class WxAppletTools {
|
@Autowired
|
private RedisCache redisCache;
|
@Autowired
|
private RestTemplate restTemplate;
|
@Autowired
|
private WxConfig wxConfig;
|
private final static String ACCESSTOKEN_CACHE_KEY = "accessToken";
|
/**
|
* 请求参数
|
* 属性 类型 默认值 必填 说明
|
* appid string 是 小程序 appId
|
* secret string 是 小程序 appSecret
|
* js_code string 是 登录时获取的 code
|
* grant_type string 是 授权类型,此处只需填写 authorization_cod
|
* <p>
|
* 返回值:
|
* <p>
|
* 属性 类型 说明
|
* openid string 用户唯一标识
|
* session_key string 会话密钥
|
* unionid string 用户在开放平台的唯一标识符,若当前小程序已绑定到微信开放平台帐号下会返回,详见 UnionID 机制说明。
|
* errcode number 错误码
|
* errmsg string 错误信息
|
*/
|
private static final String JSCODE_2_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
|
|
|
/**
|
* 请求参数
|
* 属性 类型 默认值 必填 说明
|
* grant_type string 是 填写 client_credential
|
* appid string 是 小程序唯一凭证,即 AppID,可在「微信公众平台 - 设置 - 开发设置」页中获得。(需要已经成为开发者,且帐号没有异常状态)
|
* secret string 是 小程序唯一凭证密钥,即 AppSecret,获取方式同 appid
|
* 返回值
|
* Object
|
* 返回的 JSON 数据包
|
* <p>
|
* 属性 类型 说明
|
* access_token string 获取到的凭证
|
* expires_in number 凭证有效时间,单位:秒。目前是7200秒之内的值。
|
* errcode number 错误码
|
* errmsg string 错误信息
|
*/
|
private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
|
|
/**
|
* @return
|
*/
|
public String getAccessToken() {
|
String requestUrl = MessageFormat.format(ACCESS_TOKEN_URL, wxConfig.getAppId(), wxConfig.getSecret());
|
String respBody = restTemplate.getForEntity(requestUrl, String.class).getBody();
|
JSONObject jsonObject = JSONObject.parseObject(respBody);
|
return jsonObject.getString("access_token");
|
}
|
}
|