Java实现微信小程序生成小程序二维码,并携带参数。

业务需求:生成小程序的二维码,并携带指定参数;

生成小程序二维码官方链接

官方提供两个接口,我选择了 wxacode.getUnlimited,生成数量不受限制 ;

 1.首先需要获取微信的access_token

 /**
     * 获取微信accesstoken
     *
     * @param wxappid
     * @param wxappkey
     * @return
     */
    public static String getWxAcesstoken(String wxappid, String wxappkey) throws CustomizeException {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxappid + "&secret=" + wxappkey;

        try {
            String jsonstr = HttpUtil.get(tokenUrl);
            JSONObject jsonObject = JSON.parseObject(jsonstr);
            if (jsonObject.containsKey("access_token")) {
                String accesstoken = jsonObject.getString("access_token");
                return accesstoken;
            } else {
                log.error("未获取到token");
                throw new CustomizeException("未获取到token");
            }

        } catch (Exception e) {
            log.error("未获取到token");
            throw new CustomizeException(e.getMessage());
        }
    }

2.重写了一个发送http请求的方法

返回的格式是ByteArrayInputStream,它是一个访问数组的字节输入流

 public static ByteArrayInputStream sendPost(String URL, String json) {
        InputStream inputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                // 创建一个Buffer字符串
                byte[] buffer = new byte[1024];
                // 每次读取的字符串长度,如果为-1,代表全部读取完毕
                int len = 0;
                // 使用一个输入流从buffer里把数据读取出来
                while ((len = inputStream.read(buffer)) != -1) {
                    // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                    outStream.write(buffer, 0, len);
                }
                // 关闭输入流
                inputStream.close();
                // 把outStream里的数据写入内存
                byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayInputStream;
    }

 3.第三步就是生成小程序二维码的逻辑

  /**
     * 获取小程序菊花码
     *parm:machineNo    二维码想携带的参数
     **/
    public String getWXCode(String machineNo) throws CustomizeException {
         private String appId ="asdasdasd";   //自己小程序的appid
         private String secret ="454654645564";   //自己小程序的密钥
        String aiyunUrl = "";
        try {
            //这里调用的是上面的获取access_token方法
            String access_token = getWxAcesstoken(appId, secret);

            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            String scene = machineNo;  /携带参数放在scene 内
            Map<String, String> param = new HashMap<>();
            param.put("scene", scene);
            //这里的page如果没有的话可以不写,默认是跳主页,如果写了没有的页面的话,会返回错误信息
//            param.put("page", "pages/index/index");
            String json = JSON.toJSONString(param);
            ByteArrayInputStream inputStream = sendPost(url, json);
            //这里判断的是返回的图片还是错误信息,一般错误信息不会大于200
            if (inputStream.available() <= 200) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int i;
                byte[] buffer = new byte[200];
                while ((i = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, i);
                }
                String str = new String(byteArrayOutputStream.toByteArray());
                //错误信息的格式在官方文档里有
                JSONObject jsonObject = JSONObject.parseObject(str);
                if ("41030".equals(jsonObject.getString("errcode"))) {
                    log.error("所传page页面不存在,或者小程序没有发布");
                    throw new CustomizeException("所传page页面不存在,或者小程序没有发布");
                } else if ("45009".equals(jsonObject.getString("errcode"))) {
                    log.error("调用分钟频率受限");
                    throw new CustomizeException("调用分钟频率受限");
                }
                byteArrayOutputStream.close();
            }
            //上传阿里云,也可以不上传
            String aiyunUrl= ossClientUtil.UploadImgAndReturnImgUrlInputStream(inputStream, fileName, path);
            //输出到本地的代码
              FileOutputStream fileOutputStream = new FileOutputStream("D:/123.png");
            int i;
            byte[] buffer = new byte[200];
            while ((i = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, i);
            }
            fileOutputStream.flush();
            fileOutputStream.close();

            inputStream.close();
            log.error("二维码生成成功");
        } catch (Exception e) {
            log.error("获取二维码异常");
            throw new CustomizeException(e.getMessage());
        }
        return aiyunUrl;
    }

4.用到的自定义的一个异常

public class CustomizeException extends Exception {
   
    public CustomizeException(String message) {
        super(message);
    }
}

至此二维码生成成功! 

  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
微信小程序可以使用微信提供的API生成参数二维码,具体步骤如下: 1. 在小程序管理后台中,进入“开发”->“开发设置”->“接口设置”,勾选“生成参数二维码”并保存。 2. 在小程序中调用wx.request()方法向微信服务器发送生成二维码的请求,请求URL为:https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode,请求方法为POST。 3. 在请求参数中,需要传入access_token(调用凭证)、path(小程序页面路径,可以参数)、width(二维码宽度,单位为像素,默认为430px),例如: ``` wx.request({ url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode', method: 'POST', header: { 'content-type': 'application/json' }, data: { access_token: 'ACCESS_TOKEN', path: 'pages/index/index?param1=xxx&param2=xxx', width: 430 }, success: function (res) { console.log(res.data) } }) ``` 4. 微信服务器会返回二进制数据,可以使用wx.arrayBufferToBase64()方法将其转换为base64字符串,再使用wx.createImage()方法生成图片。例如: ``` wx.request({ url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode', method: 'POST', header: { 'content-type': 'application/json' }, data: { access_token: 'ACCESS_TOKEN', path: 'pages/index/index?param1=xxx&param2=xxx', width: 430 }, responseType: 'arraybuffer', success: function (res) { var base64 = wx.arrayBufferToBase64(res.data) wx.createImage({ src: 'data:image/jpeg;base64,' + base64, success: function (res) { console.log(res) } }) } }) ``` 以上就是生成参数二维码的步骤,需要注意的是,调用接口时需要传入正确的access_token,而且access_token有时效性,需要定期更新。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值