微信公众平台API链接:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
1、认证的服务号,获取消息模板(能接受模板消息的用户必须是关注公众号的用户)
模板详情
2、定义发送的实体对象
public class WxTemplateContent {
public String touser; //用户OpenID
public String template_id; //模板消息ID
public String url; //URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)。
public String topcolor; //标题颜色
public HashMap<String,WxTemplateData> data;
}
public class WxTemplateData {
public WxTemplateData(String value, String color){
this.value = value;
this.color = color;
}
public String value;
public String color;
}
3、定义发送方法
public static void sendMessage(WxTemplateContent temp){
String jsonString = JSONObject.fromObject(temp).toString();
String token = WeChatGongZhongService.getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
WeChatUtil.httpRequest(url, "POST", jsonString);
}
public static String getAccessToken() {
JSONObject jsonObject = null;
String result = (String) Cache.get("WeiXinUtils.getAccessToken",
String.class);
if (result == null) {
String parameter = "grant_type=client_credential&appid=" + appId
+ "&secret=" + appSecret;
System.out.println(parameter);
jsonObject = WeChatUtil.httpRequest(
"https://api.weixin.qq.com/cgi-bin/token?" + parameter,
"GET", null);
System.out.println(jsonObject);
result = jsonObject.getString("access_token");
}
return result;
}
4、使用案例
/**
* 交易提醒
* @param user
* @param order
*/
public static void sendTradeNotify(t_users user){
WxTemplateContent temp = new WxTemplateContent();
temp.touser=user.open_id;
temp.template_id = TP_TRADE_NOTIFY;
temp.topcolor="#173177";
HashMap<String,WxTemplateData> data = new HashMap<String,WxTemplateData>();
temp.data= data;
data.put("first",new WxTemplateData("您的风控服务订单已经交易成功。","#000000"));
data.put("keyword1",new WxTemplateData(“2018031421020434”,"#173177"));
data.put("keyword2",new
WxTemplateData(DateUtil.dateToString1(2018-03-14),"#173177"));
data.put("keyword3",new WxTemplateData(183****5247,"#173177"));
data.put("keyword4",new WxTemplateData("会员费","#173177"));
data.put("keyword5",new WxTemplateData(99+"元","#173177"));
data.put("remark",new WxTemplateData("如有问题请联系客服"+1010+"。","#000000"));
sendMessage(temp);
}
如果你只是拿到了用户的openid,但该用户没有关注公众号,发送时会抛出下面的错误:
其他信息: 微信Post请求发生错误!错误代码:43004,说明:require subscribe hint: [Q2OfvA0092ge21]