Java调用微信客服消息接口

package com.yhxc.utils.wechat;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: 赵贺飞
 * @Date: 2018/3/28 16:05
 * 调用微信公众平台主动发消息接口
 */
public class wechat {

    public static void main(String[] args) throws IOException {

        //元泓星辰
        String appId = APPID;
        String appSecret = appSecret;
        String token = getAccess_token(appId, appSecret).getString("access_token");
        System.err.println("Tocken:" + token);

        //发送消息
        /*JSONObject text = new JSONObject();
        text.element("content", "内容");
        JSONObject json = new JSONObject();
        json.element("touser", "oNLtTw6H2Rx5Qg-SWaEjsbKfPkGY");
        json.element("text", text);
        json.element("msgtype", "text");*/
       // customSend(json, token);

        //发送图片
        /*JSONObject media_id = new JSONObject();
        String filePath = "E:\\SougouImages\\SogouWP\\Net\\WallPaper\\405376.jpg";
        media_id.element("media_id", upload(filePath, token, "image"));
        JSONObject json1 = new JSONObject();
        json1.element("touser", "oNLtTw6H2Rx5Qg-SWaEjsbKfPkGY");
        json1.element("image", media_id);
        json1.element("msgtype", "image");
        customSend(json1, token);*/
    }

    /**
     * 获取code
     */
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=redirect_uri&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect

    /**
     * 获取code后,根据code获取openid
     */
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=secret&code=$code&grant_type=authorization_code


    /**
     * 发送图片
     * @param filePath
     * @param accessToken
     * @param type
     * @return
     * @throws IOException
     */
    public static String upload(String filePath, String accessToken, String type) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }
        //String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ accessToken +"&type="+ type;
        URL urlobj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlobj.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        //设置头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");

        //设置边界
        String BOUNFARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNFARY);

        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(BOUNFARY);
        sb.append("\r\n");
        sb.append("Content-Disposition:from-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/actet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");
        //获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        //输出表头
        out.write(head);

        //文件正文部分
        //把文件以流的方式 推入到url
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        //结尾部分
        byte[] foot = ("\r\n--" + BOUNFARY + "--\r\n").getBytes("utf-8");
        out.write(foot);
        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        if (result == null) {
            result = buffer.toString();
        }
        if (result != null) {
            reader.close();
        }
        JSONObject jsonObject = JSONObject.fromObject(result);
        System.out.println(jsonObject);
        String typeName = "media_id";
        if (!"image".equals(type) && !"voice".equals(type) && !"video".equals(type)) {
            typeName = type + "_media_id";
        }
        String mediaid = jsonObject.getString(typeName);
        return mediaid;
    }


    /**
     * post请求,发送消息
     */
    public static void customSend(JSONObject json, String accessToken) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(json.toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("客服消息result:" + result);
        } catch (Exception e) {
            System.out.println("向客服发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 获取token
     *
     * @return
     */
    public static JSONObject getAccess_token(String appId, String appSecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String accessToken = null;
        JSONObject jsonObj = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            accessToken = new String(jsonBytes, "UTF-8");
            System.err.println(accessToken);
            jsonObj = JSONObject.fromObject(accessToken);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }
}

 

<think>我们正在处理用户关于Java调用微信二维码识别接口的请求。用户希望获得示例代码或教程。但请注意:用户提到的“识别二维码接口”可能有歧义。通常有两种理解:1.识别(解析)二维码图片内容:即给定一个二维码图片,解析出其中的信息。2.生成二维码:生成微信小程序码或二维码,用于扫码跳转。根据引用内容,用户提供的引用[1][2][3]都是关于生成二维码(特别是微信小程序码)的,而不是识别二维码。引用[1][2]描述了微信小程序生成小程序码和二维码的接口开发,引用[3]展示了一个用Java生成带参二维码的示例(使用的是QRCodeUtil,但并非微信官方接口,而是普通的二维码生成)。因此,我们需要澄清用户的需求:如果用户想要生成微信小程序码或二维码,那么我们可以提供调用微信接口生成二维码/小程序码的示例。如果用户想要识别(解析)二维码,那么我们需要提供解析二维码图片的Java库使用示例。然而,用户的问题明确写着“识别二维码接口”,所以可能是解析二维码。但观察用户提供的引用,全部都是生成二维码的内容,而且用户上一次的问题可能也是关于生成的(因为引用内容都是生成),所以也可能用户误用了“识别”一词,实际想生成。由于用户的问题描述是“识别二维码接口”,但引用都是生成,我们需要谨慎处理。考虑到用户要求“java调用微信识别二维码接口”,而微信官方并没有提供公开的识别二维码的接口(识别二维码通常在客户端进行,微信客户端可以识别二维码,但服务器端微信没有提供识别二维码的API)。因此,如果用户想要在服务器端识别(解析)二维码图片,需要使用第三方库。所以,我们有两种情况:情况一:用户实际想生成微信小程序码或二维码(根据引用内容,这是更可能的,因为引用都是生成)情况二:用户确实想识别二维码(解析),那么我们需要提供使用Java第三方库(如ZXing)解析二维码的示例。由于用户的问题没有明确,且引用都是生成,我们优先考虑生成,但也要提供识别的可能性。我们这样回答:首先,澄清问题:微信官方没有提供服务器端识别二维码的API,但提供了生成小程序码和二维码的接口。如果用户需要生成,我们可以提供生成接口调用示例;如果用户需要识别,我们可以提供使用ZXing库解析二维码的示例。然后,分别给出两种情况的示例。但是,用户的问题中引用了生成二维码的内容,所以很可能用户需要的是生成。不过为了全面,我们同时提供两种可能性的解决方案。步骤:1.解释微信官方接口情况。2.如果用户需要生成二维码(小程序码),给出调用微信接口生成小程序码的Java示例。3.如果用户需要识别二维码(解析),给出使用ZXing库的Java示例。注意:用户要求的是调用微信接口,但微信没有识别接口,所以识别部分我们无法调用微信接口,只能使用第三方库。因此,我们这样组织回答:首先,明确微信官方接口:-微信提供了生成小程序码和二维码的接口(用于生成,引用[1][2]提到的),但没有提供服务器端识别二维码的接口。然后,根据用户需求提供不同的方案。由于用户问题中同时出现了“识别”和引用中的“生成”,我们怀疑用户可能混淆了这两个概念。所以先简要说明:生成二维码:创建一张包含特定信息的二维码图片。识别二维码:从一张二维码图片中读取信息。接下来,我们分别提供:一、生成微信小程序码/二维码的Java示例(调用微信官方接口)二、识别二维码(解析)的Java示例(使用ZXing库)这样,无论用户实际需要什么,我们都能覆盖。现在,我们开始写回答。</think>### Java调用微信二维码接口解决方案 根据您的需求,我将分为两部分解答:微信二维码生成接口调用微信官方提供)和二维码识别(使用第三方库实现)。 --- ### 一、微信二维码生成接口调用Java示例) 微信官方提供三种二维码生成接口,适用于小程序场景: #### 1. 创建小程序码(推荐) ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class WxQrCodeGenerator { // 微信接口地址 private static final String API_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN"; public static void createMiniProgramQr(String accessToken, String path, File outputFile) { try { // 构建JSON请求体 String jsonInput = "{\"path\":\"" + path + "\", \"width\": 430}"; // 创建HTTP连接 URL url = new URL(API_URL.replace("ACCESS_TOKEN", accessToken)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); // 发送请求 try (OutputStream os = conn.getOutputStream()) { os.write(jsonInput.getBytes()); } // 获取返回图片流 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { try (InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(outputFile)) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } } System.out.println("小程序码生成成功"); } else { System.err.println("错误代码:" + conn.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String accessToken = "你的ACCESS_TOKEN"; // 通过微信API获取 createMiniProgramQr(accessToken, "pages/index/index?id=123", new File("qrcode.png")); } } ``` #### 接口说明: 1. **ACCESS_TOKEN**:通过微信`/cgi-bin/token`接口获取 2. **path**:小程序页面路径(如`pages/index/index?param=value`) 3. **返回结果**:直接输出PNG图片二进制流 4. 官方文档:[获取小程序码](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getQRCode.html) --- ### 二、二维码识别(使用ZXing库) 微信未提供官方二维码识别接口,推荐使用开源库ZXing: #### 1. 添加Maven依赖 ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.1</version> </dependency> ``` #### 2. 二维码识别示例代码 ```java import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; public class QrCodeDecoder { public static String decodeQrCode(File qrCodeFile) throws Exception { BufferedImage image = ImageIO.read(qrCodeFile); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); // 识别设置 HashMap<DecodeHintType, Object> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 执行识别 Result result = new MultiFormatReader().decode(bitmap, hints); return result.getText(); } public static void main(String[] args) { try { String content = decodeQrCode(new File("qrcode.png")); System.out.println("识别结果: " + content); } catch (Exception e) { System.err.println("识别失败: " + e.getMessage()); } } } ``` --- ### 关键注意事项: 1. **ACCESS_TOKEN获取**: ```java // 示例获取代码(需替换APP_ID和APP_SECRET) String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=APP_SECRET"; ``` 2. **微信接口限制**: - 小程序码接口单日调用上限100,000次 - 二维码内容长度限制128字节 3. **错误处理**:微信接口返回JSON错误示例: ```json {"errcode":40013,"errmsg":"invalid appid"} ``` > 提示:微信官方未提供服务器端二维码识别接口,如需识别功能需使用ZXing等第三方库实现[^1][^2][^3]。 --- ### 相关问题 1. 如何获取微信接口调用所需的ACCESS_TOKEN? 2. 微信小程序码和普通二维码有何区别? 3. 如何提高ZXing识别模糊二维码的成功率? 4. 微信二维码接口调用次数超限如何处理? 5. 带参数的小程序码如何关联用户数据? --- [^1]: 微信小程序生成二维码扫码进入小程序java接口开发 [^2]: 微信小程序 获取小程序码和二维码java接口开发 [^3]: 微信小程序 带参二维码 纯Java实现
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值