java 获取小程序码,适用于需要的码数量极多的业务场景

java 获取小程序码,适用于需要的码数量极多的业务场景

2019年12月9日 panlobal编写 第1版

注:必须是发布的小程序才可以!
请求地址
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
请求参数:
1 access_token string 是 接口调用凭证
2 scene string 是 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&’()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)
page string 主页 否 必须是已经发布的小程序存在的页面(否则报错),例如 pages/index/index, 根路径前不要填加 /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
3 width number 430 否 二维码的宽度,单位 px,最小 280px,最大 1280px

错误码
45009 调用分钟频率受限(目前5000次/分钟,会调整),如需大量小程序码,建议预生成。
41030 所传page页面不存在,或者小程序没有发布
40001 access_token过期了

第一步 获取 access_token

https://developers.weixin.qq.com/miniprogram/dev/api/getAccessToken.html

//获取微信小程序的access_token
private String getAccessToken(){

    //微信接口url
    String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?" +
            "grant_type=client_credential" +
            "&appid=" + APPID +
            "&secret=" + SECRET;
    RestTemplate restTemplate = new RestTemplate();

    ResponseEntity<String> responseEntity = restTemplate.getForEntity(accessTokenUrl,String.class);
    String accessToken = null;
    if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK){
        String strBody = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(strBody);
        accessToken = jsonObject.getString("access_token");
        log.info("accessToken:{}",accessToken);
    }
    return accessToken;

}

代码注解:APPID 在代码中定义你自己的appid,SECRET 也是一样。

第二步 发送post请求, 并保存图片

url: https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

//发送post请求,并保存图片
private String saveImage(){

    String accessToken = getAccessToken();
    log.info("getQrCodeByCooperationId,accessToken:{}",accessToken);

    //图片文件名称
    String fileName = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()) +
            UUID.randomUUID().toString().substring(8)+".png";
    RestTemplate rest = new RestTemplate();
    InputStream inputStream = null;
    OutputStream outputStream = null;
   
    try {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
        Map<String,Object> param = new HashMap<>();
        
        param.put("path", "pages/index/index");
        param.put("width", 430);    
        param.put("auto_color", true);
        log.info("调用生成微信URL接口传参:" + param);

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        HttpEntity requestEntity = new HttpEntity(param, headers);
        ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
        log.info("调用小程序生成微信永久二维码URL接口返回结果:" + entity.getBody());

        byte[] result = entity.getBody();
        inputStream = new ByteArrayInputStream(result);
        File file = new File(fileName);
        outputStream = new FileOutputStream(file);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = inputStream.read(buf, 0, 1024)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.flush();

    } catch (Exception e) {
        log.error("调用小程序生成微信永久二维码URL接口异常",e);
    } finally {
        if(inputStream != null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    return fileName;

}

因项目需要,后续会将获取的小程序二维码,通过spring cloud Feign接口调用的方式 上传到另一个微服务:文件服务器,并获取该图片的链接;若有同样功能需求的朋友,可以翻看后续文章。

猜你喜欢

转载自www.cnblogs.com/tanzi-888/p/12015043.html