微信接口文档地址:模板消息 | 微信开放文档
发送模板消息接口:
http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
获取accessToken的接口:
https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
发送模板消息的参数说明:
结果图:
####################################### 代码部分 ############################################
1.首先创建相关实体类:存放AccessToken的类
public class AccessToken {
/**
* 获取到的凭证
*/
private String access_token;
/**
* 凭证有效时间,单位:秒
*/
private int expires_in;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
}
微信模板类:
/**
* Created by yxz on 2018/7/12.
*
* 微信模板类
*/
public class WeChatTemplate {
/**
* 模板id
*/
private String template_id;
/**
* 接收者 openId
*/
private String touser;
/**
* 模板跳转链接
*/
private String url;
/**
* data的数据
*/
private TreeMap<String, TreeMap<String, String>> data;
/**
* data 里的数据
* @param value :模板参数
* @param color :颜色 可选
* @return
*/
public static TreeMap<String, String> item(String value, String color) {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("value", value);
params.put("color", color);
return params;
}
}
2.提供方法的service类:
/**
* Created by yxz on 2018/7/12.
*
* 微信模板消息
*/
@Component
public class WeChatTemplateService {
@Autowired
RestTemplate restTemplate;
private static Logger logger = LoggerFactory.getLogger(WeChatTemplateService.class);
/**
* 获取access_token的接口地址
*/
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**发送模板消息*/
public static final String SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
/**
* 通过APPID 和 APPSECRET
* 获取assess_token
* @return
*/
public AccessToken getAccessToken(String appid, String appsecret) {
AccessToken accessToken = null;
String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
JSONObject jsonObject = restTemplate.getForObject(requestUrl,JSONObject.class);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setAccess_token(jsonObject.getString("access_token"));
accessToken.setExpires_in(jsonObject.getInt("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return accessToken;
}
/**
* 发送模板消息
* @param accessToken
* @param data
* @return
*/
public void sendTemplateMsg(String accessToken, WeChatTemplate data){
String jsonString =new Gson().toJson(data.toString());
String requestUrl =SEND_TEMPLATE_MESSAGE.replace("ACCESS_TOKEN",accessToken);
JSONObject jsonObject = restTemplate.postForObject(requestUrl,jsonString,JSONObject.class);
logger.error("jsonObject值:"+jsonObject);
if (null != jsonObject) {
int errorCode = jsonObject.getInt("errcode");
if (0 == errorCode) {
logger.info("模板消息发送成功");
} else {
String errorMsg = jsonObject.getString("errmsg");
logger.info("模板消息发送失败,错误是 "+errorCode+",错误信息是"+ errorMsg);
}
}
}
}
3.消费者类:(监听activeMq的消息,调用发送模板的方法,发送)
/** * * @author yxz * @date 2018/7/13 */ @Component public class WxTemplateConsumer { Logger logger = LoggerFactory.getLogger(WxTemplateConsumer.class); @Autowired WeChatTemplateService weChatTemplateService; @Value("${weixin.appid}") public String appId; //spring读取配置文件 @Value("${weixin.appsecret}") public String appsecret; /** * 内网发送模板 * * @param data * @param data */ @JmsListener(destination = "WxMsg", containerFactory = "outConnectionFactory") public void sendWxTemplate(String data) { sendWxMsg(data); } private void sendWxMsg(String data) { AccessToken access = weChatTemplateService.getAccessToken(appId,appsecret); logger.error("accessToken:" + access.getAccess_token(),"data:" + data); JSONObject jsonObject = (JSONObject) JSONObject.parse(data); //获取openid String touser = null; if (jsonObject.containsKey("touser")){ touser= jsonObject.get("touser").toString(); }else { logger.error("touser键为空"); } //获取template_id String templateId= null; if (jsonObject.containsKey("template_id")){ templateId = jsonObject.get("template_id").toString(); }else { logger.error("template_id键为空"); } //获取模板跳转url String url =null; if (jsonObject.containsKey("url")){ url =jsonObject.get("url").toString(); } //获取data String params =null; if (jsonObject.containsKey("data")){ params =jsonObject.get("data").toString(); }else { logger.error("data键为空"); } JSONObject jsonObjectData =null; String firstValue =null; JSONObject jsonObjectValue1 = null; String value2 =null; String keyword1Value =null; String value3 =null; String value4 =null; String keyword2Value =null; String remarkValue =null; String firstColor =null; String keyword1Color =null; String keyword2Color =null; String remarkColor =null; if (params != null){ jsonObjectData = (JSONObject) JSONObject.parse(params); if (jsonObjectData != null){ //获取first值 String value1 = null; if (jsonObjectData.containsKey("first")){ //判断是否有键,否则会报异常 value1=jsonObjectData.get("first").toString(); if (value1 != null){ JSONObject jsonObjectValue = (JSONObject) JSONObject.parse(value1); if (jsonObjectValue.containsKey("value")){ firstValue = jsonObjectValue.get("value").toString(); }else { logger.error("first缺少value键"); } if (jsonObjectValue.containsKey("color")){ firstColor = jsonObjectValue.get("color").toString(); }else { logger.error("first缺少color键"); } } }else { logger.error("first键为空"); } //获取keyword1值 if (jsonObjectData.containsKey("keyword1")){ value2 = jsonObjectData.get("keyword1").toString(); if (value2 != null){ jsonObjectValue1 = (JSONObject) JSONObject.parse(value2); if (jsonObjectValue1.containsKey("value")){ keyword1Value = jsonObjectValue1.get("value").toString(); }else { logger.error("keyword1缺少value键"); } if (jsonObjectValue1.containsKey("color")){ keyword1Color = jsonObjectValue1.get("color").toString(); }else { logger.error("keyword1缺少color键"); } } }else { logger.error("keyword1键为空"); } //获取keyword2值 if (jsonObjectData.containsKey("keyword2")){ value3 = jsonObjectData.get("keyword2").toString(); if (value3 != null){ JSONObject jsonObjectValue2 = (JSONObject) JSONObject.parse(value3); if (jsonObjectValue2.containsKey("value")){ keyword2Value = jsonObjectValue2.get("value").toString(); }else { logger.error("keyword2缺少value键"); } if (jsonObjectValue2.containsKey("color")) { keyword2Color = jsonObjectValue2.get("color").toString(); }else { logger.error("keyword2缺少color键"); } } }else { logger.error("keyword2键为空"); } //获取remark值 if (jsonObjectData.containsKey("remark")){ value4 = jsonObjectData.get("remark").toString(); if (value4 != null){ JSONObject jsonObjectValue3 = (JSONObject) JSONObject.parse(value4); if (jsonObjectValue3.containsKey("value")) { remarkValue = jsonObjectValue3.get("value").toString(); } else { logger.error("remark缺少value键"); } if (jsonObjectValue3.containsKey("color")) { remarkColor = jsonObjectValue3.get("color").toString(); }else { logger.error("remark缺少color键"); } } }else { logger.error("remark键为空"); } } }else { logger.error("参数data为null"); } TreeMap<String ,TreeMap<String ,String>> allData =new TreeMap<>(); allData.put("first",WeChatTemplate.item(firstValue,firstColor)); allData.put("keyword1",WeChatTemplate.item(keyword1Value,keyword1Color)); allData.put("keyword2",WeChatTemplate.item(keyword2Value,keyword2Color)); allData.put("remark",WeChatTemplate.item(remarkValue,remarkColor)); WeChatTemplate template =new WeChatTemplate(); if (touser != null){ template.setTouser(touser); }else{ logger.error("openId为null"); } if (templateId != null){ template.setTemplate_id(templateId); }else{ logger.error("template_id为null"); } template.setUrl(url); template.setData(allData); weChatTemplateService.sendTemplateMsg(access.getAccess_token(),template); } }
关于ActiveMq:下载ActiveMq,解压到本地,启动(bin下的32/64位,activemq.bat),浏览器打开localhost:8161进入界面,输入用户名密码。
点击queues,进入发送消息的页面:
在message body发送消息测试。