Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Wechat official account to send template message by Java

2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces Java how to achieve Wechat official account to send template messages, the article is very detailed, has a certain reference value, interested friends must read it!

Wechat official account sends template message background: as shown in the following figure, when a user posts a demand, the official account customizes to push the message. For example, when WeChat Pay, the official account will push the payment success message.

Premise: send template messages, as the name implies, the premise is that there is a template, so where to configure the template?

Wechat official account platform-> Advertising and Services-> template message-> my template

Template message is already applied for the template, if the template does not meet their own business, you can find it in the template library, and then add to the "my template". You can also apply for a new template according to your own needs, which will be examined and approved on the second working day.

You can view the format of the template in the template details. The red box on the left side of the image below shows the final effect of the message.

The red box on the right is the parameter to be passed.

With the template, the template ID is what we want to put into the code and copy it out.

After the message template is ready, don't write the code for a while. Check the Wechat development documentation to see what parameters are needed to send the template.

Wechat Development document-> basic message capability-> template message Interface-"send template message"

View Wechat development documentation

Send template message

Http request method: POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

Note: url and miniprogram are both optional fields. If both fields are left empty, the template will not jump. If both fields are passed, it will be redirected to Mini Program first. Developers can choose one of the jump methods according to their actual needs. When the client version of Wechat does not support jumping Mini Program, it will be redirected to url.

Return code description

After invoking the template message interface, a JSON packet is returned.

Example of returning JSON packets under normal conditions:

{

"errcode": 0

"errmsg": "ok"

"msgid": 200228332

}

Send the parameters required for the template:

Templates ID and openId are necessary, and the rest is related to your own business.

Once all the above is done, you can start playing with the code.

Send template Wechat and return Dto.

@ Datapublic class TemplateMsgResultDto extends ResultState {/ * message id (send template message) * / private String msgid;}

Send template Wechat to return status

@ Datapublic class ResultState implements Serializable {/ * status * / private int errcode; / * Information * / private String errmsg;}

Wechat template message request parameter entity class

@ Datapublic class WxTemplateMsg {/ * * recipient openId * / private String touser; / * template ID * / private String template_id; / * template Redirect Link * / private String url / / "miniprogram": {not added / / "appid": "xiaochengxuappid12345", / / "pagepath": "index?foo=bar" / /}, / * data data * / private TreeMap data / * * Parameter * * @ param value value * @ param color color can be left empty * @ return params * / public static TreeMap item (String value, String color) {TreeMap params = new TreeMap (); params.put ("value", value); params.put ("color", color); return params;}}

Java Encapsulation template Information Code

Public TemplateMsgResultDto noticeTemplate (TemplateMsgVo templateMsgVo) {/ / template ID String templateId= "XXX"; TreeMap params = new TreeMap (); / / assemble params.put according to specific template parameters ("first", WxTemplateMsg.item ("Congratulations! Your requirements have been released successfully "," # 000000 "); params.put (" keyword1 ", WxTemplateMsg.item (templateMsgVo.getTaskName ()," # 000000 ")); params.put (" keyword2 ", WxTemplateMsg.item (" requirements released "," # 000000 ")); params.put (" remark ", WxTemplateMsg.item (" Please wait patiently for approval "," # 000000 "); WxTemplateMsg wxTemplateMsg = new WxTemplateMsg () / / template ID wxTemplateMsg.setTemplate_id (templateId); / / openId wxTemplateMsg.setTouser (templateMsgVo.getOpenId ()); / / keyword assignment wxTemplateMsg.setData (params); String data = JsonUtils.ObjectToString (wxTemplateMsg); return handleSendMsgLog (data);}

Send template code

Private TemplateMsgResultDto handleSendMsgLog (String data) {TemplateMsgResultDto resultDto = new TemplateMsgResultDto (); try {resultDto = sendTemplateMsg (data);} catch (Exception exception) {log.error ("failed to send template", exception);} / / TODO can record the log return resultDto of sending record } public TemplateMsgResultDto sendTemplateMsg (String data) throws Exception {/ / get token String accessToken = getAccessToken (); / / send message HttpResult httpResult = HttpUtils.stringPostJson (ConstantsPath.SEND_MESSAGE_TEMPLATE_URL + accessToken, data); return IMJsonUtils.getObject (httpResult.getBody (), TemplateMsgResultDto.class) } / * get global token * / public String getAccessToken () {String key = ConstantsRedisKey.ADV_WX_ACCESS_TOKEN; / / get token if from redis cache (redisCacheManager.get (key)! = null) {return (String) redisCacheManager.get (key) } / / get access_token String url = String.format (ConstantsPath.WX_ACCESS_TOKEN_URL, appid, secret); ResponseEntity 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;}

Wechat address constant class

Get the global 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";" on the public class ConstantsPath {Universe * * official account of Wechat / * * Wechat sends template message * / public static final String SEND_MESSAGE_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";}"

Json utility class

@ Slf4jpublic 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) } / * serialized to JSON string * / public static String ObjectToString (Object object) {try {return (json.writeValueAsString (object));} catch (Exception e) {log.error ("error serializing into JSON string", e);} return null } public static T getObject (String jsonString, Class clazz) {if (StringUtils.isEmpty (jsonString)) return null; try {return json.readValue (jsonString, clazz);} catch (Exception e) {log.error ("error converting JSON string to Map", e); return null;}

Http utility class

@ Component@Slf4jpublic 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 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 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 request error", ex) } finally {try {if (response! = null) {response.close ();} if (httpClient! = null) {httpClient.close () }} catch (Exception ex) {log.error ("error in post request to shut down resources", ex);}} return httpResult;}} above is all the content of this article "how does Java implement Wechat official account to send template messages". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report