Java生成带参数的微信小程序二维码

Java生成带参数的微信小程序二维码

微信官方提供了三个生成二维码的方法,这里我们使用第三个 getUnlimited 数量无限制的这个方法。
在这里插入图片描述

第一步:生成 access_token
	/**
     * 获取微信accessToken
     */
    public String getAccessToken() {
        // 先从redis获取
        String redisAccessTokenKey = String.format(Constant.REDIS_ACCESS_TOKEN_KEY, appId);
        String accessToken = RedisUtil.get(redisAccessTokenKey);
        if (StringUtils.isNotBlank(accessToken)) {
            log.info("返回redis中AccessToken: {}", accessToken);
            return accessToken;
        }

        String url = String.format(Constant.ACCESS_TOKEN_URL, appId, appSecret);
        JSONObject jsonObject;
        try {
             jsonObject = restTemplate.getForObject(url, JSONObject.class);
        } catch (Exception e) {
            log.info("调用微信AccessToken异常:{}", e);
            return "";
        }
        log.info("调用微信AccessToken结束,返回:{}", jsonObject.toJSONString());

        if (jsonObject == null || jsonObject.containsKey("errcode")) {
            return "";
        }

        accessToken = jsonObject.getString("access_token");
        // accessToken有效期两个小时 7200秒(预留200秒)
        RedisUtil.set(redisAccessTokenKey, accessToken, 7000);
        return accessToken;
    }

注意:如果是公司业务,获取 access_token 应该统一管理,避免多个业务端各自调用,各自刷新,否则会造成冲突,导致 access_token被覆盖。

第二步:创建二维码,并保存文件至本地
	/**
     * 生成小程序二维码
     * <p>
     * scene        可以传入参数
     * page         扫码进入的小程序页面路径,最大长度 128 字节,不能为空
     * width        二维码的宽度  默认430
     * autoColor    自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
     * lineColor    auto_color 为 false 时生效,使用 rgb 设置颜色
     * isHyaline    是否需要透明底色,为 true 时,生成透明底色的小程序
     */
    private String getWxQRCode(HashMap<String, String> mapParam, String url) {
        String scene = mapParam.get("scene");
        String page = StringUtils.isBlank(mapParam.get("page")) ? "" : mapParam.get("page");
        Integer width = StringUtils.isBlank(mapParam.get("width")) ? 430 : Integer.valueOf(mapParam.get("width"));
        boolean autoColor = StringUtils.isBlank(mapParam.get("autoColor")) ? false : Boolean.valueOf(mapParam.get("autoColor"));
        Integer lineColorR = StringUtils.isBlank(mapParam.get("lineColor_r")) ? 0 : Integer.valueOf(mapParam.get("lineColorR"));
        Integer lineColorG = StringUtils.isBlank(mapParam.get("lineColor_g")) ? 0 : Integer.valueOf(mapParam.get("lineColorG"));
        Integer lineColorB = StringUtils.isBlank(mapParam.get("lineColor_b")) ? 0 : Integer.valueOf(mapParam.get("lineColorB"));
        boolean isHyaline = StringUtils.isBlank(mapParam.get("isHyaline")) ? false : Boolean.valueOf(mapParam.get("isHyaline"));

		// 本例使用 uuid 作为文件名
        String qrcodeName = UUID.randomUUID().toString();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
        	// 构造请求参数
            Map<String, Object> param = new HashMap<>();
            param.put("scene", scene);
            param.put("page", page);
            param.put("width", width);
            param.put("auto_color", autoColor);
            Map<String,Object> lineColor = new HashMap<>();
            lineColor.put("r", lineColorR);
            lineColor.put("g", lineColorG);
            lineColor.put("b", lineColorB);
            param.put("line_color", lineColor);
            param.put("is_hyaline", isHyaline);

			// 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity requestEntity = new HttpEntity(JSONObject.toJSONString(param), headers);
            ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);

            byte[] result = entity.getBody();
            inputStream = new ByteArrayInputStream(result);
            // resourcePath 为文件要保存的路径url  如:D:\
            File file = new File(resourcePath + qrcodeName + ".png");
            if (!file.getParentFile().exists()) {
                file.mkdirs();
            }
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            log.info("生成二维码异常:{}", e);
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return qrcodeName;
    }
如何生成带参数的二维码?

比如我们需要传入参数userId=101,username=Linance
我们可以在调用微信时 scene 参数中传:101&Linance
此时前端处理逻辑:

onLoad:function(options){
  if(options.scene){
    let scene=decodeURIComponent(options.scene);
    //&是我们定义的参数链接方式
    let userId=scene.split("&")[0];
    let username=scene.split('&')[1];
    //其他逻辑处理。。。。。
  }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值