JAVA微信公众号消息推送
时间: 2025-02-18 18:05:38 浏览: 106
### Java 实现微信公众号消息推送
#### 准备工作
为了通过Java实现向微信公众号发送消息的功能,需准备如下参数:
- `appId` 和 `appSecret`: 应用程序ID和密钥,用于获取访问令牌。
- `openId`: 接收者的唯一标识符,在特定的公众账号中表示唯一的订阅者身份[^2].
- `templateId`: 模板消息ID.
- `url`(可选): 用户点击模板卡片后的跳转链接.
- `data`: JSON格式的数据体, 包含要显示的信息.
#### 获取AccessToken
在调用微信接口前,先要用`appId`和`appSecret`换取`access_token`. 这个token是请求其他API的前提条件。
```java
public String getAccessToken(String appId, String appSecret){
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()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.getString("access_token");
} catch (IOException | JSONException e) {
throw new RuntimeException(e);
}
}
```
#### 发送模板消息
有了`access_token`, 就可以构建并发送带有具体信息的消息给指定用户了。下面是一段用来发送模板消息的例子:
```java
public void sendTemplateMessage(String accessToken, String openId, String templateId, Map<String,Object> dataMap){
// 构建URL
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
// 创建JSON对象作为POST主体
JSONObject jsonParam = new JSONObject();
jsonParam.put("touser", openId);
jsonParam.put("template_id", templateId);
// 如果有额外配置项如url或miniprogram,则在此处加入jsonParam
// 添加自定义数据到msgDataField节点下
JSONObject msgDataField = new JSONObject(dataMap);
jsonParam.put("data", msgDataField);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParam.toString());
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try(Response response = client.newCall(request).execute()){
System.out.println(response.body().string());
}catch(Exception ex){
ex.printStackTrace();
}
}
```
此方法接受四个参数:`accessToken`,`openId`,`templateId`以及一个包含所有需要传递给用户的动态内容的地图(`dataMap`). 它将这些信息打包成JSON字符串并通过HTTP POST提交给微信公众平台服务器.
阅读全文
相关推荐















