-
1.先获取access_token
-
2.组装小程序需要的参数
-
3.请求微信返回图片的二进制流
-
4.保存到服务器
1.获取access_token 保存到redis服务器
/**
* 获取小程序的ACCESS_TOKEN
*/
public static String getAccessToken(RedisService redisService) {
//从redis中获取小程序的token
String access_token = redisService.get("access_token_samll");
if (StringUtil.isNullOrEmpty(access_token)) {
//获取小程序的access_token
String jsonParam = HttpUtil.get(WxSPConfig.ACCESS_TOKEN_SMALL_PROGRAM.replace("APPID", WxSPConfig.APP_ID_SMALL_PROGRAM).replace("APPSECRET", WxSPConfig.SECRET_SMALL_PROGRAM));
Map<String, Object> json2Map = FastJsonUtil.json2Map(jsonParam);
access_token= String.valueOf(json2Map.get("access_token"));
Long expires_in = Long.valueOf(String.valueOf(json2Map.get("expires_in")));
redisService.set("access_token_samll", access_token,expires_in);
return access_token;
} else {
return access_token;
}
}
2.组装小程序必要的参数
private static final Logger logger = LoggerFactory.getLogger(GenerateQRCodeController.class);
@Autowired
private CompanyService companyService;
@Autowired
private RedisService redisService;
@Value("${wx_pay.images}")
private String images;
@Value("${media.image.url}")
private String url;
@ApiOperation(value = "生成QRCode", notes = "给指定的商家生成小程序二维码")
@GetMapping("/code/{sn}")
public ResponseBean generate(@PathVariable String sn) throws IOException {
CompanyEntity companyEntity = companyService.findBySn(sn);
if (companyEntity == null) {
return ResponseUtil.failure("当前商户不存在");
}
if (!StringUtil.isNullOrEmpty(companyEntity.getQrCode())) {
return ResponseUtil.failure("当前商户已存在小程序二维码");
}
String accessToken = AccessTokenUtil.getAccessToken(redisService);
Map<String, Object> map = new HashMap<String, Object>();
map.put("scene", companyEntity.getSn());
map.put("page", "pages/index/index");
map.put("width", 1280);//二维码宽度
String json = FastJsonUtil.toJson(map);
logger.info("map={}", json);
//如果正常返回是图片的二进制内容
byte[] bytes = HttpUtil.doPostJsonResponseImage(WxSPConfig.WX_ACODE_UNLIMIT.replace("ACCESS_TOKEN", accessToken).toString().replace("\"", ""), json);
String path = images + companyEntity.getSn() + ".png";
logger.info("小程序二维码保存路径={}",path);
File file = new File(images);
if (!file.exists()) {
file.mkdirs();
}
//设置到公司下面
companyEntity.setQrCode(url+"qrcode/"+companyEntity.getSn()+".png");
companyService.save(companyEntity);
//保存到服务器
InputStream is = new ByteArrayInputStream(bytes);
OutputStream out = new FileOutputStream(new File(path));
copyFile(is, out);
out.close();
is.close();
return ResponseUtil.success();
}
private static void copyFile(InputStream is, OutputStream os) throws IOException {
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
os.flush();
}
4.保存到服务器
默认奇妙的在替换请求微信二维码的接口时,出现了两个双引号导致我 调了很长时间的bug
在替换access_token的时候