RestTemplate+获取微信小程序二维码

获取微信小程序二维码

获取AccessToken

   public String getAccessToken(String appid, String secret) {
        Proxy proxy = null;
        if (proxyEnabled) {
            SocketAddress address = new InetSocketAddress(proxyHost, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, address);
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        Map<String, Object> params = new HashMap<>();
        HttpHeaders headers = new HttpHeaders();
        logger.info("url:" + url);
        logger.info("参数" + params.toString());
        ResponseEntity<String> responseEntity = httpUtil.getRequest(url, params, headers, proxy);
        logger.info("返回参数" + responseEntity.toString());
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new ApiException("获取【{0}】token异常HttpStatus:{1}", responseEntity.getStatusCode());
        }
        return responseEntity.getBody();
    }

获取微信小程序二维码

RestTemplate restTemplate = new RestTemplate();
        Proxy proxy = null;
        if (proxyEnabled) {
            SocketAddress address = new InetSocketAddress(proxyHost, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, address);
        }
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        Map<String, Object> params = new HashMap<>();
        params.put("scene", scene);
        params.put("page", page);
        params.put("width", 430);
        HttpHeaders headers = new HttpHeaders();
        logger.info("url:" + url);
        logger.info("参数:" + params.toString());
        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, params, byte[].class);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            byte[] body = responseEntity.getBody();
            InputStream inputStream = new ByteArrayInputStream(body);
            // 将获取流转为base64格式
            String result = "";
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            result = new String(Base64.getEncoder().encode(data));
            logger.info("base64:" + result);
            inputStream.close();
            swapStream.close();
            return result;
        }
        throw new ApiException("生成二维码失败");
    }

开发过程中遇到的坑:

  • 小程序返回的是buffer。
  • 开始用string去接收再把string转成byte[]数组,发现拿到的数据转成base64解析不了。
  • 用byte[]数组接收拿到的数据转成base64可以转换成图片。
    拿到的base64字符串找一个base64转图片的在线工具试一下即可。

版权声明:本文为weixin_43966689原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。