biubiuchen2019-09-19 16:03:28
微信小程序碼的獲取
最近在做一個小程序,期間發現一個有趣兒的功能,生成小程序碼,官方api地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html,現將實現過程貼出來:
1:獲取token
//授權(必填) String grant_type = "client_credential"; //URL String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?"; String params = "appid=" + Const.MINAPPID + "&secret=" + Const.MINSECRET + "&grant_type=" + grant_type; //發送請求 JSONObject data = NetUtil.get(requestUrl + params); return data.getString("access_token");
2:將獲取到的圖片buffer轉為base64
public static String imgBase64(String token, String path, Integer width, String scene, Integer type) { RestTemplate rest = new RestTemplate(); InputStream inputStream = null; OutputStream outputStream = null; try { String url = null; if (1 == type) { //獲取小程序二維碼,適用于需要的碼數量較少的業務場景 url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + token; } if (2 == type) { //獲取小程序碼,適用于需要的碼數量較少的業務場景 url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token; } if (3 == type) { //獲取小程序碼,適用于需要的碼數量極多的業務場景。 url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token; } Map<String, Object> param = new HashMap<>(); param.put("path", path); param.put("width", width); param.put("auto_color", false); param.put("scene", scene); Map<String, Object> line_color = new HashMap<>(); line_color.put("r", 0); line_color.put("g", 0); line_color.put("b", 0); param.put("line_color", line_color); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); org.springframework.http.HttpEntity requestEntity = new HttpEntity(param, headers); ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]); byte[] result1 = entity.getBody(); //切記加上"data:image/png;base64,不然會報錯" return "data:image/png;base64," + Base64.encodeBase64String(result1); } catch (Exception e) { log.error("調用小程序生成微信永久小程序碼URL接口異常", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
3:將獲取到的base64轉為 MultipartFile
public static MultipartFile base64ToMultipart(String base64) { try { String[] baseStrs = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStrs[1]); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStrs[0]); } catch (IOException e) { e.printStackTrace(); return null; } }
4:將圖片傳到服務器,并返回帶有https的圖片路徑
5:結果
{
"success": true,
"message": "操作成功!",
"code": 0,
"result": "https://**/1568880379942.png",
"timestamp": 1568880230848
}
評論

zhangrenfei LV92小時前
咖啡+綠茶 LV45小時前
有時候簡簡單單就好了 LV2前天
茫茫人海中的小牛 LV7前天
doudouInsist LV210月11日
淘代碼 LV210月11日
z1234560b LV510月11日
1509533069610月9日
暫無貢獻等級
wave小于 LV410月9日
wwwbl123 LV110月9日