首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java进行微信公众号推送模板消息

Java进行微信公众号推送模板消息

作者头像
用户1750537
发布2025-08-29 17:06:18
发布2025-08-29 17:06:18
7400
代码可运行
举报
运行总次数:0
代码可运行

使用Java进行微信公众号推送模板消息,使用微信开放平台的API。

首先,您需要获取微信公众号的access_token,使用以下代码:

代码语言:javascript
代码运行次数:0
运行
复制
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class AccessTokenUtil {
    public static String getAccessToken(String appId, String appSecret) {
        String accessToken = null;
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection)obj.openConnection();
            con.setRequestMethod("GET");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                JSONObject jsonObject = new JSONObject(response.toString());
                accessToken = jsonObject.getString("access_token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return accessToken;
    }
}

然后,您可以使用以下代码向用户发送模板消息:

代码语言:javascript
代码运行次数:0
运行
复制
import net.sf.json.JSONObject;

public class TemplateMessageUtil {
    public static void sendTemplateMessage(String accessToken, String openId, String templateId, String url, JSONObject data) {
        String apiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        try {
            URL obj = new URL(apiUrl);
            HttpURLConnection con = (HttpURLConnection)obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);

            JSONObject jsonBody = new JSONObject();
            jsonBody.put("touser", openId);
            jsonBody.put("template_id", templateId);
            jsonBody.put("url", url);
            jsonBody.put("data", data);

            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(jsonBody.toString());
            out.close();

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                JSONObject jsonObject = new JSONObject(response.toString());
                int errorCode = jsonObject.getInt("errcode");
                if (errorCode == 0) {
                    System.out.println("Template message sent successfully.");
                } else {
                    System.out.println("Failed to send template message. Error code: " + errorCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用时,您需要提供正确的appIdappSecretaccessTokenopenIdtemplateIdurldatadata是一个包含模板消息内容的JSONObject对象。

请注意,以上代码只是一个简单的示例,您可能还需要处理异常等情况。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档