记录Java后端调用微信getWxacodeUnlimit接口生成小程序码。

947 阅读2分钟

微信文档请看这个接口:getWxacodeUnlimit

这里一定要注意:POST 参数需要转成 JSON 字符串,不支持 form 表单提交

我就是没留意这个,折腾了一下午。真的极度无语!!!!

就是说要将body体转成json字符串,这个可以通过jackson去转换,如下:

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(bodyMap);

正式开始:

我们先获取微信的accessToken,因为这个接口需要会话凭据:

public String getAccessToken() {
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                appId, appSecret);
        
        ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl, String.class);
        
        long expiresIn = CommonUtils.parseJson(response.getBody(), "expires_in").asInt();
        
        String accessToken = CommonUtils.parseJson(response.getBody(), "access_token").asText();
        
        if (Objects.isNull(accessToken) || accessToken.trim().isEmpty()) {
            LogUtil.error(WechatService.class, "微信api:::access_token: " + accessToken);
            return null;
        }
        
        // 可以将token缓存起来,这个的时效是两个小时
        redisService.setValue("weixin_access_token", accessToken, expiresIn - 300);
        
        return accessToken;
}

接下来就是发起生成二维码的请求了,我们使用RestTemplate.exchange来发起post请求:

check_path: 默认是true,检查page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在, 但page 有数量上限(60000个)请勿滥用。

如果是开发阶段,或者体验版本,一定要把这个设置为false;否则无法创建,且接口还以200响应,这个很扯淡啊,谁能想到你都200了,还TM是错误的。!!!切记!!!

// 获取小程序码
public byte[] getWxaCodeUnlimit(String page, String scene) {
        // 先获取access_token
        Object accessToken = redisService.getValue("weixin_access_token");
        if (Objects.isNull(accessToken)) accessToken = getAccessToken();
        
        // 请求 URL,注入 access_token
        String url = String.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", accessToken);
    
        // 构造参数体
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("scene", scene);
        bodyMap.put("page", page);
        bodyMap.put("width", 300);
        // 正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
        bodyMap.put("env_version", "trial");
        bodyMap.put("check_path", false);
        // 转成json字符串
        String bodyJson = CommonUtils.toJson(bodyMap);

    
        // 构造请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);  // 设置为 JSON 请求
    
        // 发送 POST 请求获取二维码
        ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(bodyJson, headers), byte[].class);

        return response.getBody();
}

!!!注意!!! getWxaCodeUnlimit这里返回是字节流,前端拿到被编码的base64字符串需要添加头信息才能使用:

cosnt base64Url = `data:image/jpeg;base64,${base64String}`

直接将base64Url放到image的src上就能展示图片了。

完结!觉得有用的记得点个赞!!!