Java获取微信小程序二维码(传参)

采用的是wxacode.createQRCode获取二维码,此二维码有调用次数限制(100000次)

微信小程序官方文档地址:createQRCode

1.第一步获取accessToken
  /**
     * @return access_token
     * @throws Exception
     */
    public static String getAccessToken() throws Exception {
    
    
        String apiKey = "你的小程序apiKey";//小程序apiKey
        String secretKey = "你的小程序secretKey";//小程序密钥
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + apiKey + "&secret=" + secretKey;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp")) {
    
    
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        } else {
    
    
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        }
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
    
    
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken = jsonObject.getString("access_token");
        return accesstoken;
    }

2.获取小程序二维码到本地

  /**
     * 生成带参小程序二维码(输出到本地)
     *
     * @param machineNo    机器编号
     * @param accessToken token
     */
    public static Map<String, Object> getMiniqrQrToLocal(String machineNo, String accessToken) {
    
    
        Map<String, Object> retMap = null;
        try {
    
    
            URL url = new URL("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken);
//            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
			// 扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:"bar"}      
            paramJson.put("path", "pages/index/index?machineNo="+machineNo);//传入机器编码
            paramJson.put("width", 430);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            /*ByteArrayOutputStream os = new ByteArrayOutputStream();*/
            OutputStream os = new FileOutputStream(new File("/Desktop/image/wechatImage.jpg"));//本机位置
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
    
    
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return retMap;
    }

3.测试使用

    public static void main(String[] args) throws Exception {
    
    
        String accessToken = accessToken();
        System.out.println("获取的accessToken:" + accessToken);
        //获取二维码
         getMiniqrQrToLocal("123",accessToken);
    }

4.小程序端接收参数

在page/index/index.js页面中的onload函数接收即可
onLoad: function(e) {
    
      
console.log("接收的机器参数为:"+e.machineNo);
}

猜你喜欢

转载自blog.csdn.net/poxiao58/article/details/108156358