生成小程序的官方文檔地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
功能代碼塊:
@RequestMapping("createWxTinyCode")
public ResponseEntity<String> createWxTinyCode(@BCurrentUser EnterpriseUserinfo enterpriseUserinfo, Integer type,
Integer width, String page, String typeUrl, Integer storeId) {
log.info("創建小程序二維碼,type:{},width:{},page:{},typeUrl:{},storeId:{}", type, width, page, typeUrl, storeId);
Assert.notNull(page, "地址不能爲空");
try {
String accessToken = cacheService.get(CacheKeyConstants.WEIXIN_AUTHORIZED_ACCESS_TOKEN + ModuleConstants.WEIXIN_TINY_APPID);
log.info("accessToken:{}", accessToken);
JSONObject paramJson = new JSONObject();
paramJson.put("width", width);
String urlStr = "";
if (type == null) {
type = 1;
}
// 生成小程序碼
if (1 == type) {
// 接口B:適用於需要的碼數量極多的業務場景
// api地址:https://developers.weixin.qq.com/miniprogram/dev/api/qrcode.html
JSONObject json = new JSONObject();
json.put("typeUrl", typeUrl);
json.put("storeId", storeId);
String param = storeId + "";
if (typeUrl != null) {
param += "#" + typeUrl;
}
log.info("小程序請求參數:{}", param);
urlStr = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
paramJson.put("scene", param);
paramJson.put("page", page);
paramJson.put("auto_color", false);
JSONObject line_color = new JSONObject();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
paramJson.put("line_color", line_color);
} else {
// 生成小程序二維碼
paramJson.put("path", page);
urlStr = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
}URL url = new URL(urlStr + accessToken);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// 發送POST請求必須設置如下兩行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 發送請求參數
printWriter.write(paramJson.toString());
// flush輸出流的緩衝
printWriter.flush();
printWriter.close();String picUrl = DOWNLOAD_TEMP_FOLDER + "/smallCode_" + System.currentTimeMillis() + ".png";
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
OutputStream os = new FileOutputStream(new File(picUrl));
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
os.flush();
}
os.close();
InputStream in = null;
byte[] data = null;
// 讀取圖片字節數組
try {
in = new FileInputStream(picUrl);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String res = new String(Base64.encodeBase64(data));log.info("base64 res:{}", res);
new File(picUrl).delete();
return ReqResultUtil.genSuccessResultResponse(res);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
注意點:sence 參數 { 最大32個可見字符,只支持數字,大小寫英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~
,其它字符請自行編碼爲合法字符(因不支持%
,中文無法使用 urlencode
處理,請使用其他編碼方式)}