获取微信小程序分享码
获取小程序码微信提供了三个接口,详情见 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html
我在项目中使用的是wxacode.getUnlimited这个接口,因为它没有数量限制,选择接口的时候可以根据项目的需求去选择合适的接口。
首先先了解wxacode.getUnlimited接口

通过接口说明文档可以看到有两个必备参数,access_token和scene,其中access_token是接接口调用凭证,需要通过auth.getAccessToken接口获得,scene这个参数是根据根据项目的业务(即用户扫码进入小程序后的业务)逻辑去设置的,我在项目中设置的是分享人的id(也可以设置分享人的openid),其他参数的我在项目中没有传,就不多做说明了。
通过上面的说明可以知道我们第一步需要获取接口调用凭证
//获取接口调用凭证access_token
String response = HttpUtil.sendGet(wxConfig.getGetAccessTokenUrl(), "grant_type=client_credential&appid=" + wxConfig.getAppletsAppId() + "&secret=" + wxConfig.getAppletsSecret());
Gson gson = new Gson();
Map map = gson.fromJson(response, new TypeToken<Map<String, String>>() {}.getType());
String accessToken= (String) map.get("access_token");
获取到accessToken之后就可以调用wxacode.getUnlimited接口生成小程序码了。
说明
我在项目中是将小程序码保存至本地,然后在上传到阿里云的对象存储
try {
//注:access_token 每天有调用上限,这里处理是放入redis缓存,设置有效期一小时
//获取小程序码调用API
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
Map<String, String> param = new HashMap();
param.put("scene", accountId + "");//参数
System.out.println("accountId:" + accountId);
MultiValueMap<String, String> headers = new LinkedMultiValueMap();
HttpEntity requestEntity = new HttpEntity(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
byte[] result = entity.getBody();
inputStream = new ByteArrayInputStream(result);
//文件上传路径
File file = new File(accountId + ".jpg");
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();
outputStream.close();
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
MultipartFile multipartFile = new CommonsMultipartFile(item);
OssUtil ossUtil = OssUtil.getInstance();
imagePath = ossUtil.uploadImageCore("images/QRCode/", multipartFile, ossUtil);
ossUtil.destroy();
file.delete();