后端 获取小程序码并返回图片

前言:开发需求需要小程序码,调用微信小程序码的API可获得微信小程序码,本文主要讲图片的返回方式。

微信小程序API文档:获取小程序码
API文档可以详细知道获取小程序码的方式,这里不再赘述。
注意:access_token是和请求地址一起的,而不是json参数。

因为小程序使用canvas进行画图,图片需要使用网络地址的形式去获取,下面的代码则可以直接返回小程序码,在浏览器打开即小程序码(网络地址的形式)。不需要去存储小程序码,在线生成去使用。

上代码:

    /**
     * 获取小程序码
     * @return
     */
    @RequestMapping
    public Object getUnlimited(String scene,HttpServletResponse response) throws WxErrorException, IOException {

		//获取accessToken
        String accessToken = wxMaService.getAccessToken();

        String json = "{\"scene\":\""+scene+"\"}";

        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;

        byte[] bytes = HttpClientUtils.doPost(url, json);

        InputStream inputStream = new ByteArrayInputStream(bytes);

        BufferedImage bufferedImage = ImageIO.read(inputStream);
        if (bufferedImage != null){
            String format = "jpg";
            return ImageIO.write(bufferedImage, format, response.getOutputStream());
        }

        return null;
    }

请求结果:
后端 获取小程序码并返回图片_第1张图片

你可能感兴趣的:(后端 获取小程序码并返回图片)