public void createQRCode(String id, HttpServletResponse response) throws Exception {
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId
+ "&secret=" + appSecret;
String responseString = restTemplate.getForObject(url, String.class);
String accessToken = (responseString != null ? responseString.split(":") : new String[0])[1].split("\"")[1];
String jumpPath = "pages/index/index";
String qrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
Map<String, Object> params = new HashMap<>();
params.put("page", jumpPath);
params.put("scene", id);
params.put("width", 430);
params.put("is_hyaline", true);
params.put("auto_color", false);
params.put("line_color", new HashMap<String, Object>(){{put("r",0);put("g",0);put("b",0);}});
restTemplate.postForEntity(qrcodeUrl, params, String.class);
byte[] bytes = restTemplate.postForObject(qrcodeUrl, params, byte[].class);
response.setContentType("image/png");
OutputStream outputStream = response.getOutputStream();
assert bytes != null;
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
参数名 | 参数值 | 解释 |
---|
page | pages/index/index | 小程序的首页跳转地址,注意:前面不能加"/" |
scene | id | 自定义场景码(就是和前端约定好的自定义参数,在小程序中不做任何处理,扫码以后会传给前端。比如我的是传的某商品的主键,扫码以后小程序端获取到id,会根据主键去查询商品展示) |