java生成小程序二维码
官方文档地址
步骤一,获取access_token
private String getBaseToken(String grantType, String appId, String secret) {
String baseTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?";
String url = baseTokenUrl + "grant_type=" + grantType + "&appid=" + appId + "&secret=" + secret;
WxAccessTokenDto result;
result = restTemplate.getForObject(url, WxAccessTokenDto.class);
if (Objects.nonNull(result) && result.getErrcode() == 0) {
return result.getAccess_token();
}
return null;
}
步骤二、生成小程序二维码
- 返回的格式是buffer,如果需要返回前端展示需要做处理
- 下面采用byte[] 接收,转成base64返回前端展示
public String getQrImage(WxQrImageRequest request) {
String appId = "";
String secret = "";
String accessToken = "";
String result = null;
accessToken = getBaseToken("client_credential", appId, secret);
String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
Map<String, Object> params = new HashMap<>();
params.put("path", request.getPath());
params.put("width", request.getWidth());
params.put("auto_color", request.isAuto_color());
params.put("line_color", request.getLine_color());
params.put("is_hyaline", request.is_hyaline());
ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, params, byte[].class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
InputStream inputStream = null;
ByteArrayOutputStream swapStream = null;
try {
byte[] body = responseEntity.getBody();
inputStream = new ByteArrayInputStream(body);
byte[] data;
swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rc;
while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
result = new String(Base64.getEncoder().encode(data));
result = "data:image/jpeg;base64," + result;
return result;
} catch (Exception e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (swapStream != null) {
swapStream.close();
}
} catch (Exception e) {
}
}
}
return null;
}
|