手记

获取微信小程序二维码

1,首先获取access_token

    @Override
    public String getAudioMinAppToken() {
        String accessToken;
        try {
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxxxxx&secret=xxxxxxxx";
            String data = HttpClientUtil.doGet(requestUrl);
            JSONObject json = JSONObject.parseObject(data);
            accessToken = String.valueOf(json.get("access_token"));
        } catch (Exception e) {
            logger.error("生成access_token异常", e);
            throw new CommonException(CommonErrorCode.UNKNOWN_ERROR, "获取access_token失败");
        }
        return accessToken;
    }

2,获取小程序二维码

    @Override
    public Map<String, String> createWxQRCode(String scene, String page, Integer width, Boolean autoColor, Object lineColor, Boolean isHyaline) {
        Map<String, String> map = new HashMap<>(16);
        String token;
        try {
            String tokenKey = RedisKeyCenter.getAudioMinAppToken();
            if (redisService.get(tokenKey) != null && redisService.isKeyExist(tokenKey)) {
                token = redisService.get(tokenKey);
            } else {
                token = getAudioMinAppToken();
                redisService.set(tokenKey, token, 60 * 60 * 2, TimeUnit.SECONDS);
            }
            if (scene == null) {
                scene = "n=1234";
            }
            if (page == null) {
                page = "pages/index";
            }
            if (isHyaline == null) {
                isHyaline = false;
            }
            Map<String, Object> params = new HashMap<>(16);
            params.put("scene", scene);
            params.put("page", page);
            params.put("width", width);
            params.put("auto_color", autoColor);
            params.put("line_color", lineColor);
            params.put("is_hyaline", isHyaline);

            String url = ApplicationConstant.MINAPP_GET_QR_CODE_URL.replace("ACCESS_TOKEN",token);
            logger.info("request rul is :" ,url);
            InputStream inputStream = HttpClientUtil.jsonPostToStream(url,params);
            String result = StreamUtils.getBase64FromInputStream(inputStream);
            String pic = "data:image/jpeg;base64," + result;
            map.put("pic", pic);
        } catch (Exception e) {
            logger.error("生成小程序二维码出错", e);
            throw new CommonException(CommonErrorCode.UNKNOWN_ERROR, "生成小程序二维码出错");
        }
        return map;
    }
1人推荐
随时随地看视频
慕课网APP