项目中遇到一个生成小程序二维码的需求,经过调研采用官方提供的wxacode.getUnlimited 方法来生成,
官方文档地址: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
思路:
- 首先请求接口,获取到二进制内容
- 然后将二进制转为图片,保存到本地/服务器
package org.jsola.hr.common.wechat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 小程序二维码处理类
*/
@Slf4j
@Component
public class QRCodeUtils {
public void getQRCode() {
Map<String, Object> parameters = new HashMap<>();
// 小程序appid
String appid = "xxx";
// 小程序秘钥
String secret = "xxx";
log.info("appid:{},secret:{}", appid, secret);
String accessToken = MessageHandlerUtil.getAccessToken(appid, secret).getAccessToken();
parameters.put("scene", "");
parameters.put("width", 430);
String url= "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
// 请求生成二维码接口,返回图片二进制内容
byte[] bytes = HttpUtils.httpPostByte(url, parameters);
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
BufferedImage bi1 = ImageIO.read(byteArrayInputStream);
//可以是jpg,png,gif格式
File file = new File("C:\\Users\\Administrator\\Desktop\\123.png");
// TODO: 将本地文件上传到服务器,返回图片存储地址
// 不管输出什么格式图片,此处不需改动
ImageIO.write(bi1, "jpg", file);
} catch (IOException e) {
log.error("生成小程序二维码失败:{}", e.getMessage());
}
}
}
请求接口获取二进制流
package org.jsola.hr.common.wechat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
* @Author
* @Description:
* @Date in 16:57
* @Modify By:
*/
@Slf4j
public class HttpUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* 获取二进制流
*
* @param url url
* @param params 参数值
*/
public static byte[] httpPostByte(String url, Map<String, Object> params) {
String jsonParams = "";
try {
jsonParams = objectMapper.writeValueAsString(params);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
kong.unirest.HttpResponse<byte[]> httpResponse = Unirest.post(url)
.body(jsonParams).asBytes();
byte[] body = httpResponse.getBody();
log.info("body:{}", body);
return body;
}
}