java微信生成带参数的二维码

99ANYc3cd6
预计阅读时长 27 分钟
位置: 首页 参数 正文

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

在Java中生成带参数的微信二维码,可以通过调用微信提供的二维码生成接口来实现,以下是详细的实现步骤:

java微信生成带参数的二维码
(图片来源网络,侵删)

准备工作

你需要有一个已认证的微信公众号,并获取到以下信息:

  • AppID
  • AppSecret

获取access_token

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class WeChatUtil {
    private static final String APPID = "你的AppID";
    private static final String APPSECRET = "你的AppSecret";
    public static String getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" 
                   + APPID + "&secret=" + APPSECRET;
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        JSONObject jsonObject = new JSONObject(response.toString());
        return jsonObject.getString("access_token");
    }
}

生成带参数的二维码

微信提供了两种类型的二维码:

  1. 临时二维码(expire_seconds参数指定有效期)
  2. 永久二维码(scene_id参数指定场景值)

1 生成临时二维码

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class WeChatQRCode {
    public static String createTemporaryQRCode(int expireSeconds, String sceneStr) throws IOException {
        String accessToken = WeChatUtil.getAccessToken();
        JSONObject json = new JSONObject();
        JSONObject actionInfo = new JSONObject();
        JSONObject scene = new JSONObject();
        scene.put("scene_str", sceneStr); // 使用字符串场景值
        actionInfo.put("scene", scene);
        actionInfo.put("action_name", "QR_STR_SCENE");
        json.put("expire_seconds", expireSeconds);
        json.put("action_info", actionInfo);
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.getOutputStream().write(json.toString().getBytes());
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        JSONObject responseJson = new JSONObject(response.toString());
        return responseJson.getString("ticket");
    }
}

2 生成永久二维码

public static String createPermanentQRCode(int sceneId) throws IOException {
    String accessToken = WeChatUtil.getAccessToken();
    JSONObject json = new JSONObject();
    JSONObject actionInfo = new JSONObject();
    JSONObject scene = new JSONObject();
    scene.put("scene_id", sceneId); // 使用整数场景值
    actionInfo.put("scene", scene);
    actionInfo.put("action_name", "QR_SCENE");
    json.put("action_info", actionInfo);
    String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.getOutputStream().write(json.toString().getBytes());
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    reader.close();
    JSONObject responseJson = new JSONObject(response.toString());
    return responseJson.getString("ticket");
}

使用ticket获取二维码图片

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class QRCodeImage {
    public static void getQRCodeImage(String ticket, String savePath) throws IOException {
        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(savePath);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        outputStream.close();
    }
}

完整示例

public class Main {
    public static void main(String[] args) {
        try {
            // 生成临时二维码,有效期30分钟,场景值为"test123"
            String temporaryTicket = WeChatQRCode.createTemporaryQRCode(1800, "test123");
            QRCodeImage.getQRCodeImage(temporaryTicket, "temporary_qrcode.png");
            System.out.println("临时二维码已生成: temporary_qrcode.png");
            // 生成永久二维码,场景值为12345
            String permanentTicket = WeChatQRCode.createPermanentQRCode(12345);
            QRCodeImage.getQRCodeImage(permanentTicket, "permanent_qrcode.png");
            System.out.println("永久二维码已生成: permanent_qrcode.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项

  1. 二维码的scene_str或scene_id是自定义参数,用于区分不同的二维码场景
  2. 临时二维码有效期最长为30天(2592000秒)
  3. 永久二维码的scene_id目前只支持1-100000的整数
  4. 生成的ticket需要URL编码后才能用于获取二维码图片
  5. 微信接口调用频率有限制,需要注意不要频繁调用

使用第三方库简化

如果你不想自己实现HTTP请求部分,可以使用如Apache HttpClient或OkHttp等第三方库来简化代码:

// 使用OkHttp的示例
public static String getAccessToken() throws IOException {
    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" 
               + APPID + "&secret=" + APPSECRET;
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        String responseBody = response.body().string();
        JSONObject jsonObject = new JSONObject(responseBody);
        return jsonObject.getString("access_token");
    }
}

就是在Java中生成带参数的微信二维码的完整实现方法。

java微信生成带参数的二维码
(图片来源网络,侵删)
java微信生成带参数的二维码
(图片来源网络,侵删)
-- 展开阅读全文 --
头像
三星智能电视 芒果tv
« 上一篇 今天
飞思卡尔智能车大赛具体哪年哪月举办?
下一篇 » 今天

相关文章

取消
微信二维码
支付宝二维码

最近发表

标签列表

目录[+]