通过微信小程序获取二维码的方式有三种, 这里总结一下生成无限制的小程序二维码
调用方式
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
需要注意的是, 如果请求成功的话, 微信给我们返回的是图片二进制的内容, 在请求失败的时候才会返回json格式的内容
上代码
- 定义一个存放接口信息的对象
public class WechatInterface {
/**
* 获取接口调用凭证
*/
public static String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 获取无限制的小程序二维码
*/
public static String UNLIMITED_QR_CODE = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";
}
- 获取ACCESS_TOKEN, 这里我将token存放到了redis中, AccessTokenDto 就是用于接收微信返回的json对象, 具体可以看看微信小程序的文档
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;
}
- 接下来请求微信的接口来获取二维码, 获取到二维码后我是直接将inputStream转成了base64返回给前端来展示图片
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, 完事