微信小程序官方接口生成带参数二维码

最近在做一个点餐项目需要生成带参数的二维码供顾客扫码点餐,网上有用许多二维码生成器,比如“草料二维码生成器”,但是我还是偏爱用微信小程序官方提供的接口来实现。

首先贴一个文档地址,万事先看文档
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html

我用到的是生成码数量较少的场景,你们也可以选较多的,实现方式一样的在这里插入图片描述
请求参数
在这里插入图片描述
返回值返回的是图片的二进制字节,将其用io流写进图片文件中即可
在这里插入图片描述

		//获取access_token
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + deskacode.getAppId() + "&secret=" + secret;
        String accessTokenObject = this.restTemplate.getForObject(accessTokenUrl, String.class);
        String accessToken = (String) JSON.parseObject(accessTokenObject).get("access_token");

		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        String createQRcodeUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
        byte[] result = this.restTemplate.postForObject(createQRcodeUrl, "{\"path\": \"pages/similar/similar?deskNo="+deskacode.getDeskNo()+"\"}", byte[].class);
        InputStream inputStream = null;
        OutputStream outputStream = null;

try {
            inputStream = new ByteArrayInputStream(result);
            String acodePath = fileProfile+"/acodes/"+deskacode.getAppId()+"/"+deskacode.getDeskNo()+".png";
            String saveAcodePath = "/profile/acodes/"+deskacode.getAppId()+"/"+deskacode.getDeskNo()+".png";
            File file = new File(acodePath);//windows
            //File file = new File("/home/buyfood/acodePath+"/"+deskacode.getDeskNo()+".png"); //linux
            if(!file.getParentFile().exists()){//判断文件夹在不在
                file.getParentFile().mkdirs();//文件夹不在 创建文件夹
            }if(!file.exists()){  //判断文件是否存在 不存在创建一个文件
                file.createNewFile();
            }
            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);
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值