以下是获取二维码代码:
public String getWxaCodeUnLimit(String scene, String page) {
byte[] byteCode = null;
try {
byteCode = getByteCode(scene, page);
String s = new String(byteCode);
// 报异常信息 重试一次
if (s.contains("errcode")) {
LOGGER.error(s);
byteCode = getByteCode(scene, page);
}
}catch (Exception e){
throw new OpBusinessException(ExceptionCodeEnum.GET_WXACODEUNLIMIT_ERROR.getCode(), ExceptionCodeEnum.GET_WXACODEUNLIMIT_ERROR.getMsg());
}
String encode = Base64.getEncoder().encodeToString(byteCode);
return encode;
}
private byte[] getByteCode(String scene, String page) {
String accessToken = getAccessToken();
LOGGER.info("accessToken:" + accessToken);
StringBuilder stringBuilder = new StringBuilder(seed2);
stringBuilder.append(accessToken);
LOGGER.info("stringBuilder:" + stringBuilder);
Map<String, Object> params = new HashMap<>();
params.put("scene", scene);
params.put("page", page);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(stringBuilder.toString());
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);
StringEntity entity;
InputStream content = null;
byte[] bytes = null;
try {
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
content = response.getEntity().getContent();
bytes = IOUtils.toByteArray(content);
} catch (Exception e) {
LOGGER.error("getWxaCodeUnLimit", e);
} finally {
try {
if (content != null) {
content.close();
}
} catch (IOException ex) {
LOGGER.error("getWxaCodeUnLimit IO 流关闭异常", ex);
}
return bytes;
}
}
获取accesstoken 工具,accessToken只要在有效时间内不重复获取都是有效的,所以用了Redis做了缓存
accesstoken 获取微信开发者文档
public String getAccessToken() {
String cacheKey = GlobalCacheManageEnum.SMALL_PRODURES_ACCESS_TOKEN_CACHE.getCacheKey();
String accessToken = redisService.get(cacheKey);
if (StringUtils.isEmpty(accessToken)) {
StringBuilder stringBuilder = new StringBuilder(seed);
stringBuilder.append(appid).append("&secret=").append(appSecret);
String token = HttpClientUtil.doGet(stringBuilder.toString());
JSONObject jsonObject = JSONObject.parseObject(token);
String errcode = jsonObject.getString("errcode");
if (StringUtils.isNotEmpty(errcode) && !errcode.equals("0")) {
LOGGER.error(jsonObject.getString("errmsg"));
throw new OpBusinessException(ExceptionCodeEnum.SMALL_PRODURES_ACCESS_TOKEN_ERROR.getCode(), ExceptionCodeEnum.SMALL_PRODURES_ACCESS_TOKEN_ERROR.getMsg());
}
accessToken = jsonObject.getString("access_token");
Object expiresIn = jsonObject.get("expires_in");
long expiresTime = Long.valueOf(expiresIn.toString()) ;
redisService.set(cacheKey, accessToken, expiresTime);
}
return accessToken;
}