c# 微信公众号模板消息推送

1.将你要部署的程序的域名加入微信公众号后台域名授权,将授权文件放到程序部署网站的根目录下,以及IP地址加入IP白名单

2.微信公众号后台搜索合适的模板并将模板id记录下来

3.新建模板类

public class BaseMessage
        {
            /// <summary>
            /// openid
            /// </summary>
            public string openid
            {
                get;
                set;
            }
            /// <summary>
            /// 点击跳转url
            /// </summary>
            public string url
            {
                get;
                set;
            }
            /// <summary>
            /// 标题
            /// </summary>
            public string first
            {
                get;
                set;
            }
            /// <summary>
            /// 模板内容1
            /// </summary>
            public string keyword1
            {
                get;
                set;
            }
            /// <summary>
            /// 模板内容2
            /// </summary>
            public string keyword2
            {
                get;
                set;
            }
            /// <summary>
            /// 模板内容3
            /// </summary>
            public string keyword3
            {
                get;
                set;
            }
            /// <summary>
            /// 模板内容4
            /// </summary>
            public string keyword4
            {
                get;
                set;
            }
        /// <summary>
        /// 模板内容5
        /// </summary>
        public string keyword5
        {
            get;
            set;
        }
        /// <summary>
        /// 模板结尾
        /// </summary>
        public string remark
            {
                get;
                set;
            }

            /// <summary>
            /// 选用的模板
            /// </summary>
            public string templateType;

        }

public class MessageModel
        {
            [DataMember(Order = 0)]
            public string touser
            {
                get;
                set;
            }
            [DataMember(Order = 1)]
            public string template_id
            {
                get;
                set;
            }
            [DataMember(Order = 2)]
            public string url
            {
                get;
                set;
            }
            [DataMember(Order = 3)]
            public BaseData data
            {
                get;
                set;
            }

        }
public class BaseData
        {
            [DataMember(Order = 0)]
            public font first
            {
                get;
                set;
            }
            [DataMember(Order = 1)]
            public font keyword1
            {
                get;
                set;
            }
            [DataMember(Order = 2)]
            public font keyword2
            {
                get;
                set;
            }
            [DataMember(Order = 3)]
            public font keyword3
            {
                get;
                set;
            }
            [DataMember(Order = 4)]
            public font keyword4
            {
                get;
                set;
            }
        [DataMember(Order = 5)]
        public font keyword5
        {
            get;
            set;
        }
        [DataMember(Order = 6)]
            public font remark
            {
                get;
                set;
            }
        }
 /// <summary>
        /// 字体
        /// </summary>
        public class font
        {
            public string value
            {
                get;
                set;
            }
            public string color
            {
                get;
                set;
            }
        }

4.首先进入页面时先获取openid并存session(微信公众号用户唯一标识),回调地址得到返回值

 //采用排序的Dictionary的好处是方便对数据包进行签名,不用再签名之前再做一次排序
        private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
        /**
        * 设置某个字段的值
        * @param key 字段名
         * @param value 字段值
        */
        public void SetValue(string key, object value)
        {
            m_values[key] = value;
        }

        /**
        * 根据字段名获取某个字段的值
        * @param key 字段名
         * @return key对应的字段值
        */
        public object GetValue(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            return o;
        }

public static string GetOpenidAndAccessToken()
        {

            string redirect_uri = HttpUtility.UrlEncode(System.Configuration.ConfigurationManager.AppSettings["WechatAPIUrl"]);
            WxPayDataParamIn data = new WxPayDataParamIn();
            data.SetValue("appid", System.Configuration.ConfigurationManager.AppSettings["WeixinAppId"]);
            data.SetValue("redirect_uri", redirect_uri);
            data.SetValue("response_type", "code");
            data.SetValue("scope", "snsapi_base");
            data.SetValue("state", "STATE" + "#wechat_redirect");
            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
            try
            {
                //触发微信返回code码         
                return url;//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                return "";
            }
        }

redirect_uri(回调地址)获取到openid和accesstoken

public ActionResult ResponseCode()
        {
            string url = "";
            string code = "";
            string openid = "";
            string access_token = "";
            string ret = CookieHelper.ReadCookies("RedirectUrlRe");
            try
            {
                Log.WriteLog("ResponseCode2:" + SessionHelper.RedirectUrl);
                if (Request.QueryString["code"] != null)
                {
                    code = Request.QueryString["code"];
                    AccesstokenTemplate model = new TjjgService().GetTemp(SessionHelper.YYBH, "1");
                    WxPayDataParamIn wechatOpration = new WxPayDataParamIn();
                    wechatOpration.GetOpenidAndAccessTokenFromCode(code, model);
                    openid = wechatOpration.Openid;
                    access_token = wechatOpration.Access_token;
                    url = VerfityRedirectUrl(ret) + "code=" + code + "&openid=" + openid + "&access_token=" + access_token;
                    Response.Redirect(url);
                }
                else
                {
                    url = VerfityRedirectUrl(ret) + "errorCode=06&errorMessage=code为空";
                    Response.Redirect(url);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.ToString());

                url = VerfityRedirectUrl(ret) + "errorCode=05&errorMessage=获取openid时报错";
                Response.Redirect(url);
            }
            return null;
        }

5.用户授权登录之后,触发事件,将openid等要发送的内容赋值给一个实体,

 //发微信模版消息
                WeiXinService.BaseMessage bm = new WeiXinService.BaseMessage();
                bm.openid = SessionHelper.OpenId;
                bm.first = "您好,恭喜您预约成功!";
                bm.keyword1 = "";
                bm.keyword2 = "";
                bm.keyword3 = "";
                bm.keyword4 = "";
                bm.keyword5 = "";
                bm.remark = "具体注意事项,请点击下方的链接查看!联系电话:";
                bm.url = null;
                bool s= WeiXinService.SendMessage(bm);

6.给赋值的内容增加字体颜色以及改造成另一个符合微信接口要求的入参格式MessageModel 

/// <summary>
        /// 给用户推送消息(基础)
        /// </summary>
        /// <param name="Message">发送内容</param>
        /// <returns></returns>
        public static bool SendMessage(BaseMessage Message)
        {
            bool result = false;
            MessageModel Model = new MessageModel();
            Model.touser = Message.openid;//用户openid
            Model.url = Message.url;//跳转链接
            if (string.IsNullOrWhiteSpace(Message.templateType) || Message.templateType == "0")
            {
                Model.template_id = WebConfigurationManager.AppSettings["Base_template_id"];//模板id
            }
            else
            {
                Model.template_id = WebConfigurationManager.AppSettings["Base_template_id_" + Message.templateType];//模板id
            }

            Log.WriteLog("常规" + Model.template_id);
            BaseData baseDate = new BaseData();
            font first = new font();
            first.value = Message.first;
            first.color = "#3998fc";
            font keyword1 = new font();
            keyword1.value = Message.keyword1;
            keyword1.color = "";
            font keyword2 = new font();
            keyword2.value = Message.keyword2;
            keyword2.color = "";
            font keyword3 = new font();
            keyword3.value = Message.keyword3;
            keyword3.color = "";
            font keyword4 = new font();
            keyword4.value = Message.keyword4;
            keyword4.color = "";
            font keyword5 = new font();
            keyword5.value = Message.keyword5;
            keyword5.color = "";
            font remark = new font();
            remark.value = Message.remark;
            remark.color = "";
            baseDate.first = first;
            baseDate.keyword1 = keyword1;
            baseDate.keyword2 = keyword2;
            baseDate.keyword3 = keyword3;
            baseDate.keyword4 = keyword4;
            baseDate.keyword5 = keyword5;
            baseDate.remark = remark;
            Model.data = baseDate;
            result = SendMessage(Model);
            return result;
        }

7.首先检查accesstoken是否过期,若无过期则调用接口传参,过期则重新调用微信调用accesstoken接口获取

 /// <summary>
        /// 检查基础token是否过期并刷新
        /// </summary>
        /// <returns></returns>
        public static bool Check_token()
        {
            bool result = false;
            var timespan = (DateTime.Now - access_token_Date);//获取时间差(秒)
            if (timespan.TotalSeconds < expires_in && !string.IsNullOrEmpty(access_token))
            {
                result = true;
                return result;
            }
            else
            {
                result = Base_token();
            }
            return result;
        }
/// <summary>
        /// 获取基础token
        /// </summary>
        /// <returns></returns>
        private static bool Base_token()
        {
            bool result = false;
            string Str = GetJson("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret);
         
            OAuth_Token2 Oauth_Token_Model = Common.JsonHelper.ParseFromJson<OAuth_Token2>(Str);
            if (!string.IsNullOrEmpty(Oauth_Token_Model.access_token))
            {
                access_token = Oauth_Token_Model.access_token;
                access_token_Date = DateTime.Now;
                result = true;
            }
            return result;
        }

8.最后一步调用发送模板消息接口发送数据

/// <summary>
        /// 给用户推送消息
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public static bool SendMessage(MessageModel Model)
        {
            bool result = false;

            if (Check_token())
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
                Log.WriteLog("url:" + Url);
                string JsonParam = JsonHelper.GetJson(Model);
                string Str = PostJson(Url, JsonParam);
                retMess retmess = Common.JsonHelper.ParseFromJson<retMess>(Str);

                Log.WriteLog(retmess.errcode + "|" + retmess.errmsg);
                if (retmess != null)
                {
                    if (retmess.errcode == "0")
                    {
                        result = true;
                       
                    }
                }
            }
            return result;
        }

这样,关注了公众号的用户操作时就可以接受到模板信息啦,实际效果如下:

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值