Example: Use C#.NET to teach you how to develop WeChat official accounts (17)--Template messages for official accounts to actively send messages to fans

As mentioned above, it is WeChat users who take the initiative to send information to the official account or an operation triggers the official account to respond and give the user a reply. If WeChat users do not actively initiate interaction, how should the official account send messages to WeChat users?

This article gives a solution: template message. Let's take a look at the official documentation first:

Template messages are only used for official accounts to send important service notifications to users, and can only be used in service scenarios that meet their requirements, such as credit card swiping notifications, product purchase success notifications, etc. Marketing messages such as advertisements and all other messages that may harass users are not supported.

Regarding the rules of use, please note:

  1. All service accounts can see the entry to apply for the template message function at the function -> add function plug-in, but only the authenticated service account can apply for and obtain the permission to use the template message;
  2. It is necessary to select 2 industries in which the public account service is located , and the selected industry can be changed once a month;
  3. Select an existing template in the template library of the selected industry to call;
  4. Each account can use 25 templates at the same time.
  5. Currently, the daily limit for calling template messages for each account is 100,000 times , and there is no special limit for a single template. [On November 18, 2014, the frequency of interface calls was increased from the default 10,000 times a day to 100,000 times a day, which can be viewed in the developer center after logging in with MP]. When the number of followers of the account exceeds 10W/100W/1000W, the upper limit of template messages’ daily calls will be increased accordingly, and the number indicated on the official account MP background developer center page shall prevail.

Note about interface documentation:

  1. The template ID and the assignment content of each parameter in the template are mainly required when the template message is called;
  2. The parameter content in the template must end with ".DATA", otherwise it is regarded as a reserved word;
  3. The symbol "" is reserved for templates.

Note that the words marked in red above are the main points of use. First of all, the official account must be authenticated to enable the template message function, and you cannot send messages to WeChat users at will, especially marketing messages and messages with sensitive words, otherwise the template will be the first If the message fails, it will even lead to the banning of the official account in serious cases. Be sure to understand the rules in detail before using it.

Now let's look at the implementation steps.

1. Official account certification

Log in to the background of the WeChat official account, follow the prompts to complete the official account authentication, and there is a service fee of 300 yuan per year.

 

2. Choose template message

After authentication, go to the WeChat official account and select the template message type you want to use. The operation diagram is as follows:

 

 

 

 

 

3. Write common template message classes

Prepare the above content, now you can write the commonly used template messages into a dedicated class, I put it in the SendTemplateMessage class of the QinMing.WeixinTemplateMessage namespace, save it as QinMingWeixinTemplateMessage.cs file, put it in the App_Code directory, the source code is as follows (only for demonstration) two):

using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using LitJson;
using System.Net;
using System.IO;
using QinMing.WeixinContainer;
using QinMing.Config;

namespace QinMing.WeixinTemplateMessage
{
    public class SendTemplateMessage
    {

		/// <summary>
        /// 模板消息:派单成功提醒,用于对公众号管理员发送各类提醒信息
        /// </summary>
		public static void SendRemindMsg(string open_id, string msg_title, string redirect_url) 
		{  
			QinMingWeixinContainer gt=new QinMingWeixinContainer();
			string access_token = gt.GetAccessToken();
			string msgid = "";  

			string poster = "{\"touser\": \"" + open_id + "\",\"template_id\":\"Y3-mTYsfrPBA_SzTqQraaaaaaaKH_9eF_kMGE3o0\", "
				+ "\"url\":\"" + redirect_url + "\"," 
				+ "\"data\":{\"first\":{\"value\":\"" + msg_title + "\",\"color\":\"#ff0000\"},"
				+ "\"keyword1\":{\"value\":\"" + DateTime.Now.ToString("yyyyMMddHHmmssms") + "\",\"color\":\"#ff0000\"},"
				+ "\"keyword2\":{\"value\":\"" + DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss") + "\",\"color\":\"#ff0000\"},"
				+ "\"remark\":{\"value\":\"点击这里查看详情。\",\"color\":\"#0000ff\"}"
				+ " } }";  
			string resultStr = GetPage("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, poster);  

		}

		/// <summary>
        /// 模板消息:新会员或新合伙人注册成功提醒,用于对公众号管理员发送提醒信息
        /// </summary>
		public static void SendNewMemberMsg(string open_id, string mobile, string msg_title, string redirect_url) 
		{  
			QinMingWeixinContainer gt=new QinMingWeixinContainer();
			string access_token = gt.GetAccessToken();
			string msgid = "";  

			string poster = "{\"touser\": \"" + open_id + "\",\"template_id\":\"tQ_vHnFzPSl5TLbbbbbbbb8yroNhJw2713SMF0\", "
				+ "\"url\":\"" + redirect_url + "\"," 
				+ "\"data\":{\"first\":{\"value\":\"" + msg_title + "\",\"color\":\"#ff0000\"},"
				+ "\"keyword1\":{\"value\":\"" + open_id + "\",\"color\":\"#ff0000\"},"
				+ "\"keyword2\":{\"value\":\"" + mobile + "\",\"color\":\"#ff0000\"},"
				+ "\"keyword3\":{\"value\":\"" + DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss") + "\",\"color\":\"#ff0000\"},"
				+ "\"remark\":{\"value\":\"点击这里查看详情。\",\"color\":\"#0000ff\"}"
				+ " } }";  
			string resultStr = GetPage("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, poster);  

		}
		
        public static string GetPage(string posturl, string postData)  
        {  
			Stream outstream = null;  
			Stream instream = null;  
			StreamReader sr = null;  
			HttpWebResponse response = null;  
			HttpWebRequest request = null;  
			Encoding encoding = Encoding.UTF8;  
			byte[] data = encoding.GetBytes(postData);  
			// 准备请求...  
			try  
			{  
				// 设置参数  
				request = WebRequest.Create(posturl) as HttpWebRequest;  
				CookieContainer cookieContainer = new CookieContainer();  
				request.CookieContainer = cookieContainer;  
				request.AllowAutoRedirect = true;  
				request.Method = "POST";  
				request.ContentType = "application/x-www-form-urlencoded";  
				request.ContentLength = data.Length;  
				outstream = request.GetRequestStream();  
				outstream.Write(data, 0, data.Length);  
				outstream.Close();  
				//发送请求并获取相应回应数据  
				response = request.GetResponse() as HttpWebResponse;  
				//直到request.GetResponse()程序才开始向目标网页发送Post请求  
				instream = response.GetResponseStream();  
				sr = new StreamReader(instream, encoding);  
				//返回结果网页(html)代码  
				string content = sr.ReadToEnd();  
				string err = string.Empty;  
				return content;  
			}  
			catch (Exception ex)  
			{  
				string err = ex.Message;  
				return string.Empty;  
			}  
        }  


    }

}

The QinMing.Config, QinMing.WeixinContainer namespaces and their class implementations used in the above code have been given in the previous articles (1) and (4).
Specific usage examples of template messages:

//给管理员发送粉丝点击菜单通知
QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("指定openid", "粉丝点击菜单信息提醒" + FromUserName, "http://www.yourweb.com/OneUser.aspx?open_id=" + FromUserName);  

Because static classes and static methods are used, there is no need to create objects in advance, and they can be used directly every time.

4. Demonstration

Is it convenient to use? The key is free! ! ! Remember to follow the official rules, otherwise the template message function will be easily blocked. 

Guess you like

Origin blog.csdn.net/daobaqin/article/details/124909086