Java实现生成微信小程序的无限制二维码
通过微信小程序获取二维码的方式有三种, 这里总结一下生成无限制的小程序二维码
调用方式
上代码
- 定义一个存放接口信息的对象
public String getAccessToken() {
String accessToken = (String) redisService.get("ACCESS_TOKEN");
if (accessToken == null) {
String url = WechatInterface.GET_ACCESS_TOKEN_URL
.replace("APPID", wechatProperties.getAppid())
.replace("APPSECRET", wechatProperties.getAppSecret());
String body = HttpClientUtils.doGet(url);
AccessTokenDto accessTokenDto = gson.fromJson(body, AccessTokenDto.class);
accessToken = accessTokenDto.getAccessToken();
redisService.set("ACCESS_TOKEN", accessToken);
redisService.expire("ACCESS_TOKEN", 120);
}
return accessToken;
}
public String getQrCode(Long orderId) throws ExecutionException, InterruptedException, IOException {
String accessToken = getAccessToken();
String url = WechatInterface.UNLIMITED_QR_CODE
.replace("ACCESS_TOKEN", accessToken);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("page", wechatProperties.getQrCodePath());
paramMap.put("scene", "orderId=" + orderId);
paramMap.put("env_version", wechatProperties.getEnvVersion());
return getBase64FromInputStream(HttpClientUtils.doPost(url, gson.toJson(paramMap)));
}
- 上面的HttpClientUtils用的是java11的HttpClient, 随便做了一点封装, 大家有更好的也可以用自己的
static HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofMillis(5000))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
public static InputStream doPost(String url, String requestBody) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
//指定提交表单的方式编码请求体
.header("Contend-Type", "application/json")
//通过字符串创建请求体,然后作为POST请求的请求参数
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<InputStream> response;
try {
response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
return response.body();
}
- 最后请求接口, 返回base64, 完事
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
基于微信小程序的宠物寄养平台的设计与实现
