微信发送模板消息

构建基类:

 /// <summary>
    /// 模板消息基类
    /// </summary>
    public class BaseTemplateMessage
    {
        /// <summary>
        /// Post模板字段
        /// </summary>
        private static readonly string m_Template = "{\"touser\":\"$[touser]\",\"template_id\":\"$[template_id]\",\"url\":\"$[url]\",\"data\":{$[data]}}";
        /// <summary>
        /// PostUrl
        /// </summary>
        private static readonly string postUrl = @"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";
        /// <summary>
        /// 接收方OPENID
        /// </summary>
        private string touser;
        /// <summary>
        /// 模板ID
        /// </summary>
        protected string templateID;
        /// <summary>
        /// Url
        /// </summary>
        protected string url;
        /// <summary>
        /// Date
        /// </summary>
        private List<TemplateMessageData> data = new List<TemplateMessageData>();

        protected void AddData(string name, string value, string color)
        {
            this.data.Add(new TemplateMessageData { name = name, value = value, color = color });
        }

        public string Result
        {
            get
            {
                string temp = string.Empty;
                string _result = m_Template;
                foreach (var item in data)
                {
                    temp += item.Result + ",";
                }
                if (data.Count > 0)
                {
                    temp = temp.Remove(temp.Length - 1);
                }
                _result = _result.Replace("$[touser]", touser);
                _result = _result.Replace("$[template_id]", templateID);
                _result = _result.Replace("$[url]", url);
                _result = _result.Replace("$[data]", temp);
                return _result;
            }
        }

        public virtual long Send(string touser, string access_token, out string errorMessage)
        {
            this.touser = touser;
            long id = -1;
            errorMessage = string.Empty;
            string pUrl = string.Format(postUrl, access_token);

            if (string.IsNullOrWhiteSpace(touser))
            {
                errorMessage = "接收消息的账号不能为空。";
                return id;
            }
            if (string.IsNullOrWhiteSpace(templateID))
            {
                errorMessage = "模板id不能为空。";
                return id;
            }
            if (data == null || data.Count == 0)
            {
                errorMessage = "模板数据不能为空。";
                return id;
            }
            foreach (var item in data)
            {
                if (string.IsNullOrWhiteSpace(item.name) || string.IsNullOrWhiteSpace(item.value) || string.IsNullOrWhiteSpace(item.color))
                {
                    errorMessage = "模板数据不能为空。";
                    return id;
                }
            }

            //发送数据
            string responseContent;
            try
            {
                responseContent = HttpPost(pUrl, Result);
                //解析结果
                JObject jo = JObject.Parse(responseContent);
                JToken jt;
                if (jo.TryGetValue("errcode", out jt) && jo.TryGetValue("errmsg", out jt))
                {
                    errorMessage = (string)jo["errmsg"];
                    if (jo.TryGetValue("msgid", out jt))
                        id = (long)jt;
                }
                else
                    errorMessage = "解析返回结果失败。";
            }
            catch (Exception e)
            {
                errorMessage = e.Message + " | ";
            }

            return id;
        }

        private string HttpPost(string Url, string json)
        {
            var result = string.Empty;
            var request = WebRequest.Create(Url) as HttpWebRequest;
            request.ContentType = "text/json";
            request.Method = "post";
            //request.CookieContainer = _cookie;

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var response = (HttpWebResponse)request.GetResponse();

                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }
        }
    }

    /// <summary>
    /// 数据类实体
    /// </summary>
    class TemplateMessageData
    {
        public string name { set; get; }
        public string value { set; get; }
        public string color { set; get; }

        /// <summary>
        /// PostData字段
        /// </summary>
        private static readonly string m_Data = "\"{0}\":{\"value\":\"{1}\",\"color\":\"{2}\"}";

        public string Result
        {
            get
            {
                string _result = m_Data;
                _result = _result.Replace("{0}", name);
                _result = _result.Replace("{1}", value);
                _result = _result.Replace("{2}", color);
                return _result;
            }
        }
    }

具体的模板类,继承自基类,提供模板ID,url,和传入数据:

 public class TemplateMessage : BaseTemplateMessage
    {
        public TemplateMessage()
        {
            base.templateID = "EWkztVGvYsMxPfr9ENituBKhkjm3G1cC_A4ozNmu3NE";
            base.url = "#";
        }

        public void SetData(string first, string keyword1, string keyword2, string remark)
        {
            base.AddData("first", first, "#173177");
            base.AddData("keyword1", keyword1, "#173177");
            base.AddData("keyword2", keyword2, "#173177");
            base.AddData("remark", remark, "#173177");
        }
    }

调用:

TemplateMessage tm = new TemplateMessage();
tm.SetData("这是一条测试的模板消息", "考试名称", "审核状态", DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss"));
long result = tm.Send(openid, token, out error);
if (result < 0)
{
  //发送失败
}
else
  //发送成功

 

转载于:https://www.cnblogs.com/sxxsw/p/5058926.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值