有时候我们可能需要在其他的网页上展示我们自己的小程序中某些页面的小程序码,这种时候,我们需要用到小程序的生成小程序码的相关接口。
// 获取小程序服务实例
WxMaService wxMaService = WxMaConfiguration.getWxMaService();
// 获取小程序二维码生成实例
WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
// 设置小程序二维码线条颜色为黑色
WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
// 生成二维码图片字节流(此处也可以生成File类型,如果想将图片文件保存到服务器就生成File类型,此处生成byte[]类型,方便直接返回文件流到前端)
byte[] qrCodeBytes = null;
qrCodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(String.valueOf(id), null, 430, false, lineColor, false);
@RestController
@RequestMapping("/qrCode")
public class QrCodeController {
private static final Logger logger = LoggerFactory.getLogger(QrCodeController.class);
@GetMapping("/getMiniappQrCode/{id}")
public void getMiniappQrCode(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws Exception{
// 获取小程序服务实例
WxMaService wxMaService = WxMaConfiguration.getWxMaService();
// 获取小程序二维码生成实例
WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
// 设置小程序二维码线条颜色为黑色
WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
// 生成二维码图片字节流
byte[] qrCodeBytes = null;
try{
qrCodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(String.valueOf(id), null, 430, false, lineColor, false);
} catch(Exception e){
logger.error("生成小程序码出错", e);
}
// 设置contentType
response.setContentType("image/png");
// 写入response的输出流中
OutputStream stream = response.getOutputStream();
stream.write(qrCodeBytes);
stream.flush();
stream.close();
}
}