Home  >  Article  >  WeChat Applet  >  C# develops WeChat portal and applies public account template message management

C# develops WeChat portal and applies public account template message management

高洛峰
高洛峰Original
2017-03-07 10:14:421875browse

Through the template message interface, official accounts can send preset template messages to users who follow their accounts. Template messages are only used by 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 swipe notifications, product purchase success notifications, etc. Marketing messages such as advertisements and all other messages that may cause harassment to users are not supported. This article mainly introduces the development and implementation of public account template message management functions based on C#.

"The launch of the template message function will greatly enhance the service notification capabilities of service accounts." In the eyes of some public account operators who have been looking forward to the opening of the WeChat template message function, the social attributes of WeChat's one-on-one communication , making the reach rate of information push more accurate, which also gives enterprises many advantages in terms of cost, service efficiency, and performance. It not only enriches the enterprise's service forms, enhances user interaction and stickiness, but also brings users More diverse, rich and timely service experience.

1. Industry classification management and description of templates

Template information is divided according to industry, and different templates are designed according to different usage scenarios. For example, under the software industry, there are registration success notifications, viewing Templates that may be used in various scenarios such as room reminders, order reminders, member recharges, and member consumption notifications.

C#开发微信门户及应用公众号模板消息管理

If our public account needs to use templates, then we need to add the required templates from the template library (the current limit is 15). After the template is added to my template, each template generates a random value, which is the [template ID]. When we send information, we send it according to this template ID.

C#开发微信门户及应用公众号模板消息管理

Each template has detailed parameter descriptions and sample effects.

C#开发微信门户及应用公众号模板消息管理

The relevant person in charge of the WeChat team said: The opening of template messages is mainly to help public accounts complete closed-loop services. Existing public accounts have limited ability to actively send messages (monthly Four messages can be sent in groups), which prevents many companies from pushing proactive notifications of service results and other information to users. After the template message is opened, enterprises can use the WeChat platform to use template messages to access information more quickly during external services and internal management processes, and provide users with more thoughtful services.

WeChat has been continuously optimizing the user experience. The opening of template messages has provided enterprises with more basic capabilities, such as richer two-way interactions, more accurate information reminders, etc., which have enhanced the quality of enterprises. , the depth and breadth of personalized services, which is why institutions and companies in finance, civil aviation, government affairs and other fields are looking forward to WeChat opening the template messaging function. In the future, with the further improvement of the template message function, perhaps company employee salary details, household monthly electricity consumption, electricity bills and other electricity consumption details, and even driver's license expiration and need to be replaced, etc., can be disclosed to the public through WeChat of companies and departments. The account's template message is instantly delivered to the corresponding user.

2. Use template messages for development

The relevant information about templates and the introduction of individual templates have been introduced before. If we need to integrate template message sending in the background program, then we need to understand the template What are the messaging APIs? How to use template message API to send messages?

Let’s first take a look at the instructions for using template messages:

1、所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口,但只有认证后的服务号才可以申请模板消息的使用权限并获得该权限;
2、需要选择公众账号服务所处的2个行业,每月可更改1次所选行业;
3、在所选择行业的模板库中选用已有的模板进行调用;
4、每个账号可以同时使用15个模板。
5、当前每个模板的日调用上限为10万次【2014年11月18日将接口调用频率从默认的日1万次提升为日10万次,可在MP登录后的开发者中心查看】。

The management functions of template messages are:

 1 Set the industry
 2 Obtain the template ID
3 Send template message
4 Event push

2.1 Set the industry

Setting the industry can be completed in MP, and the industry can be modified once a month, and the account number Only relevant templates in the industry can be used. For the convenience of third-party developers, the industry to which the account belongs is modified through interface calling. The details are as follows:

Interface call request instructions

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=ACCESS_TOKEN

POST data description

POST data examples are as follows:

      {
          "industry_id1":"1",
          "industry_id2":"4"
       }

According to the description, we can define an interface class ITemplateMessageApi, and then define and set the interface for the industry to which it belongs. The function is as follows:

        /// 
        /// 设置所属行业        /// 
        /// 
        /// 公众号模板消息所属行业编号(主营行业)
        /// 公众号模板消息所属行业编号(副营行业)
        /// 
        CommonResult SetIndustry(string accessToken, IndustryCode industry_id1, IndustryCode industry_id2);

For convenience, we define IndustryCode as an enumeration object, which lists all industry codes supported by the system, as follows Show.

C#开发微信门户及应用公众号模板消息管理

而实现代码和之前的函数处理类似,都是POST数据到一个连接即可,并解析返回的结果就可以了,具体实现代码如下所示。

/// 
        /// 设置所属行业
        /// 
        /// 访问凭证
        /// 公众号模板消息所属行业编号(主营行业)
        /// 公众号模板消息所属行业编号(副营行业)
        /// 
        public CommonResult SetIndustry(string accessToken, IndustryCode industry_id1, IndustryCode industry_id2)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={0}", accessToken);
            var data = new
            {
                industry_id1 = (int)industry_id1,
                industry_id2 = (int)industry_id2
            };
            string postData = data.ToJson();

            return Helper.GetExecuteResult(url, postData);
        }

2.2 获得模板ID

获得模板ID,也就是从模板库里面添加对应的模板消息到我的模板里面。

从行业模板库选择模板到账号后台,获得模板ID的过程可在MP中完成。为方便第三方开发者,提供通过接口调用的方式来修改账号所属行业,具体如下:

接口调用请求说明

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN

POST数据说明

POST数据示例如下:

      {
           "template_id_short":"TM00015"
       }

C#函数实现代码如下所示:

/// 
        /// 获得模板ID.
        /// 从行业模板库选择模板到账号后台,获得模板ID的过程可在MP中完成。
        /// 
        /// 访问凭证
        /// 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
        /// 
        public AddTemplateResult AddTemplate(string accessToken, string template_id_short)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={0}", accessToken);
            var data = new
            {
                template_id_short = template_id_short
            };
            string postData = data.ToJson();

            return JsonHelper.ConvertJson(url, postData);
        }

2.3 发送模板消息

根据上面小节处理,添加到我的模板里面的操作得到的模板ID,我们就可以调用发送模板消息的API进行模板消息发送了。

接口调用请求说明

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

POST数据说明

POST数据示例如下:

      {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",
           "topcolor":"#FF0000",
           "data":{
                   "first": {
                       "value":"恭喜你购买成功!",
                       "color":"#173177"
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keynote2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keynote3": {
                       "value":"2014年9月16日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买!",
                       "color":"#173177"
                   }
           }
       }

根据上面的JSON参数,我们可以看到,有部分是模板消息公共的部分,有部分则是模板消息的具体参数,这些参数需要根据不同的模板进行不同的赋值。

如这部分是共同的:

   touser":"OPENID",
   "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
   "url":"http://weixin.qq.com/download",
   "topcolor":"#FF0000",

根据这个特点,我们定义发送模板消息的接口如下所示:

/// 
        /// 模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。
        /// 不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。
        /// 
        /// 访问凭证
        /// 账号的openID
        /// 在公众平台线上模板库中选用模板获得ID
        /// 模板的变化参数数据
        /// ,URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)。
        /// 顶部颜色,默认为#173177
        /// 
        SendMassMessageResult SendTemplateMessage(string accessToken, string openId, string templateId, object data, string url, string topcolor = "#173177");

我们用object data来定义模板的变化参数数据。

具体的实现还是和前面的方法提交数据处理差不多,代码如下所示。

/// 
        /// 模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。
        /// 不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。
        /// 
        /// 
        /// 访问凭证
        /// 
        /// 在公众平台线上模板库中选用模板获得ID
        /// 
        /// ,URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)。
        /// 
        /// 
        public SendMassMessageResult SendTemplateMessage(string accessToken, string openId, string templateId, object data, string url, string topcolor = "#173177")
        {
            var postUrl = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", accessToken);
            var msgData = new TemplateData()
            {
                touser = openId,
                template_id = templateId,
                topcolor = topcolor,
                url = url,
                data = data
            };
            string postData = msgData.ToJson();

            SendMassMessageResult result = JsonHelper.ConvertJson(postUrl, postData);
            return result;
        }

发送模板的消息相对其他两个接口的使用复杂一些,例如我以一个会员通知的模板消息为例,模板的详细情况如下:

C#开发微信门户及应用公众号模板消息管理

具体的测试代码如下所示。

#region 发送模板消息

            var data = new
            {
                //使用TemplateDataItem简单创建数据。
                first = new TemplateDataItem("您好,您已成为微信【广州爱奇迪】会员。"),
                type = new TemplateDataItem("18620292076"),
                address = new TemplateDataItem("广州市白云区广州大道北"),
                VIPName = new
                {
                    //使用new 方式,构建数据,包括value, color两个固定属性。
                    value = "伍华聪",
                    color = "#173177"
                },
                VIPPhone = new TemplateDataItem("18620292076"),
                expDate = new TemplateDataItem("2016年4月18日"),
                remark = new TemplateDataItem("如有疑问,请咨询18620292076。", "#173177"),
            };

            #endregion
            string url = "http://www.iqidi.com";
            string topColor = "#173177";

            string templateId = "-5LbClAa9KUlEmr5bCSS0rxU_I2iT16iYBDxCVU1iJg";
            SendMassMessageResult sendResult = api.SendTemplateMessage(token, openId, templateId, data, url, topColor);
            if(sendResult != null)
            {
                Console.WriteLine(sendResult.msg_id);
            }

那么我们得到的提示效果如下所示。

C#开发微信门户及应用公众号模板消息管理

微信模板消息,能够让我们与客户之间沟通不受每月几条数量的限制,同时也能够利用微信模板库丰富的内容,实现强大的应用场景。

更多C#开发微信门户及应用公众号模板消息管理 相关文章请关注PHP中文网! 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn