最近在做一个点餐项目需要生成带参数的二维码供顾客扫码点餐,网上有用许多二维码生成器,比如“草料二维码生成器”,但是我还是偏爱用微信小程序官方提供的接口来实现。
首先贴一个文档地址,万事先看文档
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
我用到的是生成码数量较少的场景,你们也可以选较多的,实现方式一样的
请求参数
返回值返回的是图片的二进制字节,将其用io流写进图片文件中即可
//获取access_token
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + deskacode.getAppId() + "&secret=" + secret;
String accessTokenObject = this.restTemplate.getForObject(accessTokenUrl, String.class);
String accessToken = (String) JSON.parseObject(accessTokenObject).get("access_token");
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
String createQRcodeUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
byte[] result = this.restTemplate.postForObject(createQRcodeUrl, "{\"path\": \"pages/similar/similar?deskNo="+deskacode.getDeskNo()+"\"}", byte[].class);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new ByteArrayInputStream(result);
String acodePath = fileProfile+"/acodes/"+deskacode.getAppId()+"/"+deskacode.getDeskNo()+".png";
String saveAcodePath = "/profile/acodes/"+deskacode.getAppId()+"/"+deskacode.getDeskNo()+".png";
File file = new File(acodePath);//windows
//File file = new File("/home/buyfood/acodePath+"/"+deskacode.getDeskNo()+".png"); //linux
if(!file.getParentFile().exists()){//判断文件夹在不在
file.getParentFile().mkdirs();//文件夹不在 创建文件夹
}if(!file.exists()){ //判断文件是否存在 不存在创建一个文件
file.createNewFile();
}
outputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
// log.error("调用小程序生成微信永久小程序码URL接口异常", e);
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}