Java生成带参数的微信小程序二维码,getwxacode、getwxacodeunlimit

官方提供生成小程序码的三种方式,官方不推荐使用第三种:createwxaqrcode;

官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

第一种方式:POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN

·生成小程序码,可接受 path 参数较长,生成个数受限,数量限制10万个

第二张方式:POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

·生成小程序码,可接受页面参数较短,生成个数不限,5000次/分钟

以上两种方式参数access_token、path为必填

一、生成二维码可分为两步:

第一步:获取ACCESS_TOKEN

    // 网页授权接口
    public final static String GetAccessTokenUrl = 
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";

    public static Map<String, String> getAccessToken(String appid, String appsecret) {
        String requestUrl = GetAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret);
        HttpClient client = null;
        Map<String, String> result = new HashMap<String, String>();
        String accessToken = null;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            accessToken = String.valueOf(OpenidJSONO.get("access_token"));
            result.put("accessToken", accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return result;
    }

第二步:调用生成小程序码接口带上accessToken

    @RequestMapping("/qrCode")
    @ResponseBody
    public Object cenerateTheQrCode(HttpServletRequest request){
        //调用上面方法,获取accessToken,建议对accessToken进行缓存,
        //appid:小程序appid,appsecret:小程序密钥
        String token = SignUtil.getAccessToken(appid,appsecret).get("accessToken");
        Map<String, Object> params = new HashMap<>();
        //参数,一个可以直接放入参数例如:1 多个例如:id=1&name=2&...
        params.put("scene", "需要的参数");
        params.put("path", "pages/index/index"); //扫码后进入小程序的页面位置
        params.put("width", Number类型)//不是必须,需要的宽度,默认430x430,最小280最大1280
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 接口
        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);//必须是json模式的 post
        StringEntity  entity = null;
        try {
            entity = new StringEntity(body);
            entity.setContentType("image/png");//也可以是image/jpg
            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            String name = name+".png";//文件名加后缀,跟上面对应
            String path = "D:\\";//图片保存路径
            SignUtil.saveToImgByInputStream(inputStream,path,name);  //保存图片
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
}

下面是保存图片的方法:

/**
     * 将二进制转换成文件保存
     * @param instreams 二进制流
     * @param imgPath 图片的保存路径
     * @param imgName 图片的名称
     * @return
     *      1:保存正常
     *      0:保存失败
     */
    public static int saveToImgByInputStream(InputStream instreams, String imgPath, String imgName){
        int stateInt = 1;
        if(instreams != null){
            try {
                File file = new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
                File filePath = new File(imgPath);
                if (filePath.exists()) {
                    if (filePath.isDirectory()) {
                        System.out.println("dir exists");
                    } else {
                        System.out.println("the same name file exists, can not create dir");
                    }
                } else {
                    System.out.println("dir not exists, create it ...");
                    filePath.mkdir();
                }
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;//1 成功,0 失败
    }

这样就可以在你保存的文件夹下看到小程序码了。

这里用的是 getwxacodeunlimit 接口,想要使用getwxacode的话只需要替换即可,其他方式不变;

二、后面就是扫码后在小程序获取二维码带的参数

onLoad:function(options){
  if(options.scene){
    decodeURIComponent(options.scene)//一个参数可以直接这样获取

    //1.多个参数处理方式
    let scene=decodeURIComponent(options.scene);
    //&是我们定义的参数链接方式
    let userId=options.scene.split("&")[0];
    let recommendId=options.scene.split('&')[1];

    //2.多个参数处理方式
    if (options.scene) {
        console.log("has scene"); 
        var scene = decodeURIComponent(options.scene); 
        console.log("scene is ", scene); 
        var arrPara = scene.split("&"); 
        var arr = []; 
        for (var i in arrPara) { 
            arr = arrPara[i].split("="); 
        wx.setStorageSync(arr[0],arr[1]);
        console.log("setStorageSync:",arr[0],"=",arr[1]); 
        } 
    } else { 
        console.log("no scene"); 
    }
    //第二中处理方式转载
    ---------------------
    作者:brightming 
    来源:CSDN 
    原文:https://blog.csdn.net/brightming/article/details/81953571 
    版权声明:本文为博主原创文章,转载请附上博文链接!
  }
}

另外:开发测试的时候,使用开发者工具选择编译模式

需要注意的是开发者工具测试时可以不用解码可直接获取

//配置的启动页面下的js文件
onLoad: function (options) {
    console.log('解码:',decodeURIComponent(options.scene))
    console.log('直接获取:',options.scene)
},

发布的小程序扫描小程序码获取参数须解码;

希望对大家有帮助;

生成动态参数微信小程序二维码,可以使用微信提供的接口 `wxacode.getUnlimited`,该接口可以生成不限次数、永久有效的小程序,并且可以携动态参数。以下是一些基本步骤: 1.在微信公众平台或开放平台创建一个小程序,并获取小程序的 appid 和 secret。 2.使用 appid 和 secret 获取 access_token,可以通过调用微信接口实现。 3.使用 access_token 和其他参数调用生成小程序接口,例如以下 URL: https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN 其中 ACCESS_TOKEN 是第二步获取的 access_token。 4.在调用生成小程序接口时,需要传递一些参数,例如 `scene`、`page`、`width`、`auto_color` 等,具体参数的含义可以参考微信开发文档。 `scene` 参数是动态参数,可以根据业务需求生成。例如,可以将用户的 ID、订单号、活动 ID 等作为 `scene` 参数生成小程序时,微信会将 `scene` 参数的值写入到小程序的 `onLoad` 函数中,开发者可以在 `onLoad` 函数中获取该参数并进行相应的处理。 5.将接口返回的二进制数据保存成图片,可以使用 Python 的 requests 库实现。 下面是一个示例代: ```python import requests def generate_wxa_code_with_scene(appid, secret, scene, page, width=430): access_token = get_access_token(appid, secret) url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}' data = { 'scene': scene, 'page': page, 'width': width, 'auto_color': False } response = requests.post(url, json=data) if response.status_code == 200: with open('wxa_code.jpg', 'wb') as f: f.write(response.content) ``` 其中,`get_access_token` 函数用于获取 access_token,可以参考微信开发文档实现。`generate_wxa_code_with_scene` 函数用于调用生成小程序接口,并将结果保存成图片。调用该函数时,需要传递 `appid`、`secret`、`scene`、`page`、`width` 等参数,其中 `scene` 参数是动态参数,可以根据业务需求生成
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值