1. 程式人生 > 其它 >簡單使用Java實現微信公眾號推送模板訊息

簡單使用Java實現微信公眾號推送模板訊息

原文連結: https://blog.csdn.net/qq_41936224/article/details/108076005

以下例子是簡單的使用Java程式碼實現微信公眾號推送模板訊息,不包含跳轉到小程式網頁程式碼

1、pom.xml檔案中新增依賴

<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1.wso2v1</version>
</dependency>
<dependency>
<groupId>org.wso2.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1.wso2v1</version>
</dependency>
<!-- json -->
<dependency>
<groupId>top.jfunc.json</groupId>
<artifactId>json-fastjson</artifactId>
<version>1.8.3</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2、實體類

@Getter
@Setter
public class DataEntity {
//內容
private String value;
//字型顏色
private String color;

public DataEntity(String value ,String color){
this.value = value;
this.color = color;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
3、實現類: 有“XXX”的地方需要修改,其他地方可以不用動。應用ID、金鑰、模板ID等資訊可以登入微信公眾號開放平臺,檢視自己公司對應的資訊

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gzds.entity.DataEntity;

@Component
public class WechatMsg {

public static void main(String[] args) {
WechatMsg wm = new WechatMsg();
wm.SendWeChatMsg(wm.getToken());
}
/**
* 獲取token
*
* @return token
*/
public String getToken() {
// 授予形式
String grant_type = "client_credential";
//應用ID
String appid = "XXXXXXXXXXXXXXXXXXX";
//金鑰
String secret = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
// 介面地址拼接引數
String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid
+ "&secret=" + secret;
String tokenJsonStr = doGetPost(getTokenApi, "GET", null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String token = tokenJson.get("access_token").toString();
System.out.println("獲取到的TOKEN : " + token);
return token;
}
/***
* 傳送訊息
*
* @param token
*/
public void SendWeChatMsg(String token) {
// 介面地址
String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
//openId
String toUser = "XXXXXXXXXXXXXX";
//訊息模板ID
String template_id = "XXXXXXXXXXXXXXXXXXXXXX";
//整體引數map
Map<String, Object> paramMap = new HashMap<String, Object>();
//訊息主題顯示相關map
Map<String, Object> dataMap = new HashMap<String, Object>();
//根據自己的模板定義內容和顏色
dataMap.put("first",new DataEntity("詳細內容XXXXXXX","#173177"));
dataMap.put("keyword1",new DataEntity("私有化部署XXX","#173177"));
dataMap.put("keyword2",new DataEntity("2020-08-18XXX" ,"#173177"));
dataMap.put("remark",new DataEntity("申請成功XXX","#173177"));
paramMap.put("touser", toUser);
paramMap.put("template_id", template_id);
paramMap.put("data", dataMap);
paramMap.put("url",toUrl);
//需要實現跳轉網頁的,可以新增下面一行程式碼實現跳轉
// paramMap.put("url","http://xxxxxx.html");
System.out.println(doGetPost(sendMsgApi,"POST",paramMap));
}
/**
* 呼叫介面 post
* @param apiPath
*/
public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
OutputStreamWriter out = null;
InputStream is = null;
String result = null;
try{
URL url = new URL(apiPath);// 建立連線
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(type) ; // 設定請求方式
connection.setRequestProperty("Accept", "application/json"); // 設定接收資料的格式
connection.setRequestProperty("Content-Type", "application/json"); // 設定傳送資料的格式
connection.connect();
if(type.equals("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8編碼
out.append(JSON.toJSONString(paramMap));
out.flush();
out.close();
}
// 讀取響應
is = connection.getInputStream();
int length = (int) connection.getContentLength();// 獲取長度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
result = new String(data, "UTF-8"); // utf-8編碼
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
4、效果圖

如果有不知道怎麼獲取使用者openId的朋友,可以試一下下圖的方法:在使用者管理介面,按F12,可以從HTML頁面中找到使用者id

 

歡迎大家閱讀,本人見識有限,寫的部落格難免有錯誤或者疏忽的地方,還望各位大佬指點,在此表示感謝

你的點贊是我最大的鼓勵