import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
public class WeChatTemplateMessageSender {
// 发送模板消息
public static void sendTemplateMessage(String accessToken, String templateId, String toUserOpenId, JSONObject data) {
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
JSONObject json = new JSONObject();
json.put("touser", toUserOpenId);
json.put("template_id", templateId);
json.put("url", "https://www.example.com"); // 跳转链接(非必须)
json.put("data", data);
try {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = con.getOutputStream()) {
byte[] input = json.toJSONString().getBytes("utf-8");
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String accessToken = "YOUR_ACCESS_TOKEN";
String templateId = "YOUR_TEMPLATE_ID";
String toUserOpenId = "USER_OPEN_ID";
JSONObject data = new JSONObject();
data.put("first", new JSONObject().put("value", "您的快递已发货"));
data.put("keyword1", new JSONObject().put("value", "快递单号"));
data.put("keyword2", new JSONObject().put("value", "123456789"));
data.put("keyword3", new JSONObject().put("value", "2023-01-01 12:00:00"));
data.put("remark", new JSONObject().put("value", "如有疑问,请联系客服。"));
sendTemplateMessage(accessToken, templateId, toUserOpenId, data);
}
}
- 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.