準備工作
這裏先給出我的配置信息吧。
步驟一:
先得到微信的AccessToken
public static String getAccessToken() throws Exception {
// 獲取基礎支持的access_token
String resultUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
HttpRequestor http=new HttpRequestor();
String json = http.doGet(resultUrl);
JSONObject jsonObject =JSONObject.fromObject(json);
String access_token = jsonObject.get("access_token").toString();
System.out.println("獲取的access_token:"+access_token);
return access_token;
}
步驟二:
/**
* 發送模板消息
* @param access_token
* @return
*/
public static String sendInfo(String access_token) {
// 發送模板消息
String resultUrl2 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
Map<String,Object> map=new HashMap<String, Object>();
map.put("touser",touser);//需要接收消息的用戶openid
map.put("template_id", template_id);//模板id
Map<String,Object> data=new HashMap<String, Object>();
data.put("name",new DataInfo("小熊","#FF0000"));
data.put("date",new DataInfo("2019年10月17日","#FF0000"));
map.put("data", data);
String s = JSONObject.fromObject(map).toString();
String re=post(resultUrl2,s);//開始發送
System.out.println(re);
return re;
}
DataInfo.java
public class DateInfo {
private String value;
private String color;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public DateInfo(String value, String color) {
super();
this.value = value;
this.color = color;
}
}
上圖