WeChat public account development "II" Send template message to realize real-time notification of message business

Original statement: This article comes from another blog of mine [ send template message to realize real-time notification of message business ] original work, not taken from other places, please contact the blogger for reprint

The previous article explained how to obtain the basic details of the user's WeChat and realize automatic login after WeChat binding. Please click here to review: http://banshanxianren.iteye.com/blog/2369250

This article mainly introduces the use of the WeChat ID obtained in the previous article to send template messages to bound users. For example, our common consumption notifications, order notifications and other services can be implemented with this function. Theoretical knowledge will not be repeatedly emphasized. Practice is the only criterion for testing the truth. Just look at the examples, and I believe everyone will be able to understand it at a glance. Let's take a look at the steps to prepare:

1. Configure the template

Log in to the test official account/official official account (service account after certification), test official account: template message interface -> add template in new test template, official official account: add template in function -> template message, the template can be found in Choose from the template library. If you don’t have the template you need, you can apply to add it. You can apply for three items per month. After the template is added successfully, there is a template ID (used for interface calls).

For details, please refer to the official documentation: https://mp.weixin.qq.com/wiki  in message management->send message-template message interface

2. Code application display

Encapsulate send template interface

import java.util.Map;
/**
 * Template base class
 * @author lh
 *
 */
public class WxTemplate {
	private String template_id;//Template ID
	private String touser;//target customer
	private String url;//The user clicks the jump page of the template information
	private String topcolor;//font color
	private Map<String,TemplateData> data;//Data in the template
	
	public String getTemplate_id() {
		return template_id;
	}
	public void setTemplate_id(String template_id) {
		this.template_id = template_id;
	}
	public String getTouser() {
		return touser;
	}
	public void setTouser(String touser) {
		this.touser = touser;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getTopcolor() {
		return topcolor;
	}
	public void setTopcolor(String topcolor) {
		this.topcolor = topcolor;
	}
	public Map<String,TemplateData> getData() {
		return data;
	}
	public void setData(Map<String,TemplateData> data) {
		this.data = data;
	}
}

A template contains multiple pieces of data, template data class encapsulation

/**
 * Template data
 * @author lh
 *
 */
public class TemplateData {
	private String value;//Template display value
	private String color;//Template display 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;
	}
}

Looking at the document, the interface for sending template information is: https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN, the template data in the previous stage is all ready, and now ACCESS_TOKEN is missing, whatever is missing What to get, check the documentation to see that the ACCESS_TOKEN interface is: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET, now encapsulate a request interface to get ACCESS_TOKEN:

public class WeixinUtil {
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
	// Get the interface address of access_token (GET), limited to 200 (times/day)
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	/**
	 * Get access_token
	 * @param appid credentials
	 * @param appsecret key
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// if the request was successful
		if (null != jsonObject) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (JSONException e) {
				accessToken = null;
				// Failed to get token
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}

Note: ACCESS_TOKEN has a limit on the number of requests, and it will automatically expire 7200 seconds after it is obtained, so it is necessary to properly store ACCESS_TOKEN. This instance is placed in memory. And how to ensure that the saved ACCESS_TOKEN is valid? The general solution is to regularly request to obtain the latest ACCESS_TOKEN and update the data in memory. You can use thread timing request, quartz, or Spring's task scheduling function. The following shows the more common thread methods:

/**
 * Thread for regularly obtaining WeChat access_token
 */
public class TokenThread implements Runnable {
	private static Logger log = LoggerFactory.getLogger(TokenThread.class);
	// Unique credentials for third-party users
	public static String appid = "xxx";
	// Third-party user unique credential key
	public static String appsecret = "xxxx";
	public static AccessToken accessToken = null;//Save ACCESS_TOKEN to memory

	public void run() {
		while (true) {
			try {
				accessToken = WeixinUtil.getAccessToken(appid, appsecret);
				if(null != accessToken) {
					log.info("Get access_token successfully, valid for {} seconds token:{}", accessToken.getExpiresIn(), accessToken.getToken());
					// sleep for 7000 seconds
					Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
				}else{
					// If access_token is null, get it after 60 seconds
					Thread.sleep(60 * 1000);
				}
			} catch (InterruptedException e) {
				try{
					Thread.sleep(60 * 1000);
				} catch (InterruptedException e1) {
					log.error("{}", e1);
				}
				log.error("{}", e);
			}
		}
	}
}

Now that ACCESS_TOKEN has been obtained, everything is ready, just need to call, the sending template is given below

/**Order template, template ID: ai3WcdUjq-x4v0Reir442UCIzl3AsyCgpAy0e5q2mkY (automatically generated after adding the template in the background of the official account)**/
{{first.DATA}}
Order number: {{keyword1.DATA}}
Order Type: {{keyword2.DATA}}
Product name: {{keyword3.DATA}}
{{remark.DATA}}

The specific call example:

/**
 * Send template message call instance
 * @param websiteAndProject Request address and project name: http://192.168.2.113/seafood
 * @param receiverWeixinId The recipient's WeChat ID, how to get it, see the previous article
 * @return
 */
WxTemplate template = new WxTemplate();
template.setUrl(""+TimedTask.websiteAndProject+"/weixinTwo/gotoOrderConfirm?orderId="+map.get("orderId"));
template.setTouser("receiverWeixinId"));
template.setTopcolor("#000000");
template.setTemplate_id("ai3WcdUjq-x4v0Reir442UCIzl3AsyCgpAy0e5q2mkY");
Map<String,TemplateData> m = new HashMap<String,TemplateData>();
TemplateData first = new TemplateData();
first.setColor("#000000");
first.setValue("Hello, you have a pending order.");
m.put("first", first);
TemplateData keyword1 = new TemplateData();
keyword1.setColor("#328392");
keyword1.setValue("OD0001");
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setColor("#328392");
keyword2.setValue("Book Order");
m.put("keyword2", keyword2);
TemplateData keyword3 = new TemplateData();
keyword3.setColor("#328392");
keyword3.setValue("lobster");
m.put("keyword3", keyword3);
TemplateData remark = new TemplateData();
remark.setColor("#929232");
remark.setValue("Please confirm the order in time!");
m.put("remark", remark);
WeixinUtil.sendMessageBefore("",template, m);		
public class WeixinUtil {
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
	// Get the interface address of access_token (GET), limited to 200 (times/day)
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	/**
	 * Get access_token
	 * @param appid credentials
	 * @param appsecret key
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// if the request was successful
		if (null != jsonObject) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (JSONException e) {
				accessToken = null;
				// Failed to get token
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}
	/**
	 * Get token before sending template message
	 * @param template_id_short the number of the template in the template library
	 * @param t
	 * @param m
	 */
	public static void sendMessageBefore(String template_id_short,WxTemplate t,Map<String,TemplateData> m){
    	AccessToken token = null;
    	if(TokenThread.accessToken==null || TokenThread.accessToken.getToken()==""){
    		token = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret);
    	}else{
    		token = TokenThread.accessToken;
    	}
    	if(template_id_short!=null&&!"".equals(template_id_short)){
    		Template template = WeixinUtil.getTemplate(template_id_short,token.getToken());
        	t.setTemplate_id (template.getTemplate_id ());
    	}
    	t.setData(m);
    	int result = WeixinUtil.sendMessage(t,token.getToken());
    }
	/**
	 * Send template message
	 * @param t
	 * @param accessToken
	 * @return
	 */
	public static int sendMessage(WxTemplate t,String accessToken) {
		int result = 0;
		// assemble the url to create the menu
		String url = sendTemplateMessage_url.replace("ACCESS_TOKEN", accessToken);
		// Convert menu object to json string
		String jsonMenu = JSONObject.fromObject(t).toString();
		// Call the interface to create the menu
		JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				log.error("Failed to send template message errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return result;
	}

So far, the process of sending messages has been completed. If there are any deficiencies, puzzles or improvements, please point them out in the comment area.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326260565&siteId=291194637