微信公众号发送模版消息 Java实现
微信公眾號發(fā)送模版消息
背景:
當用戶發(fā)布任務的時候,公眾號會自動推送消息通知。例如我們都熟悉的場景:微信支付的時候,公眾號會推送支付成功消息。
申請模版:
模版消息,顧名思義,就是有模版的消息,那么要模版干嘛呢?模版是從哪來呢?
發(fā)送消息需要有固定的格式,我們可以在微信公眾號平臺上配置模版。
微信公眾號平臺–>廣告與服務–>模版消息–>我的模版
「我的模版」列表里的是已經申請的模版,如果里面的模版格式都不符合自己業(yè)務,可以到模版庫里找,然后添加到「我的模版」。也可以按照自己的需求申請新的模版,一般第二個工作日會審核通過。
https://mp.weixin.qq.com/
打開模版詳情,查看模版的格式,下圖左邊紅框是消息最終展示的效果,
右邊紅框是需要傳的參數(shù)。
有了模版之后,模版ID就是我們要放進代碼里的,把模版ID復制出來。
發(fā)送模版消息接口文檔:
消息模版準備好之后,暫時不要寫代碼奧,查看微信開發(fā)文檔,看看發(fā)送模版都需要哪些參數(shù)。
微信開發(fā)文檔–>基礎消息能力–>模版消息接口–「發(fā)送模版消息」
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
微信開發(fā)文檔參數(shù)介紹
發(fā)送模版消息
…
http請求方式: POST 請求地址: https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
…
注:
url和miniprogram都是非必填字段,若都不傳則模板無跳轉;若都傳,會優(yōu)先跳轉至小程序。開發(fā)者可根據(jù)實際需要選擇其中一種跳轉方式即可。當用戶的微信客戶端版本不支持跳小程序時,將會跳轉至url。
…
返回碼說明:
在調用模板消息接口后,會返回JSON數(shù)據(jù)包。
返回JSON數(shù)據(jù)包示例如下
{
“errcode”:0,
“errmsg”:“ok”,
“msgid”:200228332
}
發(fā)送模版所需參數(shù):
模版ID和openId是必須有的,剩下的就是和自己業(yè)務有關了。
上面的內容都搞定之后,就可以開始擼代碼了
發(fā)送模版微信返回Dto
@Data public class TemplateMsgResultDto extends ResultState {/*** 消息id(發(fā)送模板消息)*/private String msgid;}發(fā)送模版微信返回狀態(tài)
@Data public class ResultState implements Serializable {/*** 狀態(tài)碼*/private int errcode;/*** 信息*/private String errmsg;}微信模版消息請求參數(shù)實體類
@Data public class WxTemplateMsg {/*** 接收者openId*/private String touser;/*** 模板ID*/private String template_id;/*** 模板跳轉鏈接*/private String url;/*** 消息data*/private TreeMap<String, TreeMap<String, String>> data;/*** 參數(shù)** @param value 值* @param color 顏色* @return params*/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;} }Java封裝模版信息代碼
public TemplateMsgResultDto noticeTemplate(TemplateMsgVo templateMsgVo) {// 模版IDString templateId="XXX";TreeMap<String, TreeMap<String, String>> params = new TreeMap<>();//根據(jù)具體模板參數(shù)組裝params.put("first", WxTemplateMsg.item("恭喜!您的需求已發(fā)布成功", "#000000"));params.put("keyword1", WxTemplateMsg.item(templateMsgVo.getTaskName(), "#000000"));params.put("keyword2", WxTemplateMsg.item("需求已發(fā)布", "#000000"));params.put("remark", WxTemplateMsg.item("請耐心等待審核", "#000000"));WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();// 模版IDwxTemplateMsg.setTemplate_id(templateId);// openIdwxTemplateMsg.setTouser(templateMsgVo.getOpenId());// 關鍵字賦值wxTemplateMsg.setData(params);String data = JsonUtils.ObjectToString(wxTemplateMsg);return handleSendMsgLog(data);}發(fā)送模版代碼
private TemplateMsgResultDto handleSendMsgLog(String data) {TemplateMsgResultDto resultDto = new TemplateMsgResultDto();try {resultDto = sendTemplateMsg(data);} catch (Exception exception) {log.error("發(fā)送模版失敗", exception);}// TODO 可以記錄一下發(fā)送記錄的日志return resultDto;}public TemplateMsgResultDto sendTemplateMsg(String data) throws Exception {// 獲取tokenString accessToken = getAccessToken();// 發(fā)送消息HttpResult httpResult = HttpUtils.stringPostJson(ConstantsPath.SEND_MESSAGE_TEMPLATE_URL + accessToken, data);return IMJsonUtils.getObject(httpResult.getBody(), TemplateMsgResultDto.class);}/*** 獲取全局token*/public String getAccessToken() {String key = ConstantsRedisKey.ADV_WX_ACCESS_TOKEN;// 從redis緩存中獲取tokenif (redisCacheManager.get(key) != null) {return (String) redisCacheManager.get(key);}// 獲取access_tokenString url = String.format(ConstantsPath.WX_ACCESS_TOKEN_URL, appid, secret);ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);if (result.getStatusCode() == HttpStatus.OK) {JSONObject jsonObject = JSON.parseObject(result.getBody());String accessToken = jsonObject.getString("access_token");// Long expires_in = jsonObject.getLong("expires_in");redisCacheManager.set(key, accessToken, 1800);return accessToken;}return null;}微信地址常量類
public class ConstantsPath {/*** 微信公眾號獲取全局token*/public static final String WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";/*** 微信發(fā)送模版消息*/public static final String SEND_MESSAGE_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";}Json工具類
package com.demo.advertiser.common.utils;import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.cglib.beans.BeanMap;import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;@Slf4j public class JsonUtils {private static ObjectMapper json;static {json = new ObjectMapper();json.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));json.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);}/*** 序列化為JSON字符串*/public static String ObjectToString(Object object) {try {return (json.writeValueAsString(object));} catch (Exception e) {log.error("序列化為JSON字符串出錯",e);}return null;}public static <T> T getObject(String jsonString, Class<T> clazz) {if (StringUtils.isEmpty(jsonString))return null;try {return json.readValue(jsonString, clazz);} catch (Exception e) {log.error("將JSON字符串轉化為Map出錯",e);return null;}}}Http工具類
package com.demo.advertiser.common.utils;import com.google.common.base.Splitter; import com.demo.advertiser.common.utils.component.HttpResult; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;@Component @Slf4j public class HttpUtils {private static String sourcePath;public static HttpResult stringPostJson(String path, String content) throws Exception{return stringPost(path, null, content, "utf-8", "utf-8", "application/json");}public static HttpResult stringPost(String path, Map<String,String> headerMap, String content, String contentencode, String encode, String contentType) throws Exception{StringEntity entity = new StringEntity(content, contentencode);entity.setContentType(contentType);return post(path, headerMap, entity, encode);}private static HttpResult post(String path, Map<String,String> headerMap, HttpEntity entity, String encode){HttpResult httpResult = new HttpResult();CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;try{HttpPost httpPost = new HttpPost(getURI(path));LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();httpClient = HttpClientBuilder.create().setRedirectStrategy(redirectStrategy).build();RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(120000).setConnectionRequestTimeout(120000).setCircularRedirectsAllowed(true).setRedirectsEnabled(true).setMaxRedirects(5).build();httpPost.setConfig(requestConfig);httpPost.setHeader("User-Agent", header);if(headerMap != null && headerMap.size() > 0){for(String name:headerMap.keySet()) {httpPost.addHeader(name, headerMap.get(name));}}httpPost.setEntity(entity);response = httpClient.execute(httpPost);httpResult.setStatus(response.getStatusLine().getStatusCode());if(httpResult.getStatus() == 200){HttpEntity resEntity = response.getEntity();httpResult.setBody(EntityUtils.toString(resEntity, encode));}}catch(Exception ex){log.error("post請求出錯", ex);}finally{try{if(response != null){response.close();}if(httpClient != null){httpClient.close();}}catch(Exception ex) {log.error("post請求關閉資源出錯", ex);}}return httpResult;} } package com.demo.advertiser.common.utils.component;public class HttpResult {private Integer status = 601;private String body = "";public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public String getBody() {return body;}public void setBody(String body) {this.body = body;} }總結
以上是生活随笔為你收集整理的微信公众号发送模版消息 Java实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于netty的微服务架构
- 下一篇: 通过configSource提高web.