小程序获取token的两种方式
注意:使用RestTemplate需要注入
@Qualifier:根据名称注入
@Configuration
public class RestConfig {
@Bean
public RestTemplate restTemplateSimple() {
return new RestTemplate();
}
}
public static String encoding = "UTF-8";
@Autowired
private WeChatConfig weChatConfig;
private static WeChatConfig weChatConfigStatic;
@Qualifier("restTemplateSimple")
@Autowired
private RestTemplate restTemplateSimple;
private static RestTemplate restTemplateStatic;
@PostConstruct
private void init() {
weChatConfigStatic = this.weChatConfig;
restTemplateStatic = this.restTemplateSimple;
}
private static final OkHttpClient client = new OkHttpClient();
方式一:
public static String getAccessToken() {
HttpUrl.Builder urlBuilder = HttpUrl.parse(WeChatConstant.WEI_XIN_API_URL).newBuilder();
urlBuilder.addQueryParameter("grant_type", weChatConfigStatic.getClientCredential());
urlBuilder.addQueryParameter("appid", weChatConfigStatic.getAppId());
urlBuilder.addQueryParameter("secret", weChatConfigStatic.getSecretKey());
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
JSONObject jsonObject = JSONObject.parseObject(responseBody);
return jsonObject.getString("access_token");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
方式二:
public static String getAccessToken2() {
ResponseEntity<String> responseEntity = restTemplateStatic.getForEntity(WeChatConstant.ACCESS_TOKEN_URL, String.class, weChatConfigStatic.getAppId(), weChatConfigStatic.getSecretKey());
log.info("获取wxToken结果集 {}", responseEntity);
Map map = JSONObject.parseObject(responseEntity.getBody(), Map.class);
if (!StringUtils.isEmpty(map.get("errcode"))) {
throw new DefaultException("获取token参数有误");
}
if (!StringUtils.isEmpty(map.get("access_token"))) {
return map.get("access_token").toString();
} else {
throw new DefaultException("获取token失败!");
}
}
grant_type:client_credential
常量
public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
public static final String WEI_XIN_API_URL = "https://api.weixin.qq.com/cgi-bin/token";