亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development .Net implements WeChat public platform development interface 'information reply'

.Net implements WeChat public platform development interface 'information reply'

Feb 24, 2017 pm 05:12 PM

For each POST request, the developer returns a specific XML structure in the response package (Get) to respond to the message (now supports reply text, pictures, graphics, voice, video, music). Please note that when replying to multimedia messages such as pictures, you need to upload multimedia files to the WeChat server in advance. Only certified service accounts are supported.

Today I will talk about the following three

1. Follow the reply

2.Auto reply

3.Keyword reply

1 , follow the reply, automatic default reply

The so-called follow reply is the information that WeChat returns to the user after clicking the follow button when the official account is searched for. The specific implementation method is

Automatically The default reply is the message that the system will reply to by default no matter what message you send, if there is no special treatment.

Receiving and sending information from WeChat are both in XML format, which are specifically explained in the development documents. Now let’s talk about how to implement the processing and response of WeChat information.

1. First save the preset reply information into the database table

CREATE TABLE [dbo].[w_reply](
    [reply_id] [int] IDENTITY(1,1) NOT NULL,
    [reply_text] [varchar](max) NULL,
    [reply_type] [varchar](50) NULL,
    [article_id] [int] NULL,
    [wechat_id] [int] NULL,
    [reply_fangshi] [int] NULL,
 CONSTRAINT [PK_w_reply] PRIMARY KEY CLUSTERED 
(
    [reply_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

wechatapi.aspx page processes the following information

2. Receive the information sent by WeChat

#region 接收微信消息
        /// <summary>
        /// 接收微信信息
        /// </summary>
        private void RequestMsg()
        {
            //接收信息流
            Stream requestStream = System.Web.HttpContext.Current.Request.InputStream;
            byte[] requestByte = new byte[requestStream.Length];
            requestStream.Read(requestByte, 0, (int)requestStream.Length);
            //轉(zhuǎn)換成字符串
            string requestStr = Encoding.UTF8.GetString(requestByte);

            if (!string.IsNullOrEmpty(requestStr))
            {
                //封裝請(qǐng)求類到xml文件中
                XmlDocument requestDocXml = new XmlDocument();
                requestDocXml.LoadXml(requestStr);
                XmlElement rootElement = requestDocXml.DocumentElement;
                XmlNode MsgType = rootElement.SelectSingleNode("MsgType");

                //將XML文件封裝到實(shí)體類requestXml中
                RequestXml requestXml = new RequestXml();
                requestXml.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;//開(kāi)發(fā)者微信號(hào)
                requestXml.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;//發(fā)送方微信號(hào)
                requestXml.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;//消息發(fā)送信息
                requestXml.MsgType = MsgType.InnerText;

                //獲取接收信息的類型
                switch (requestXml.MsgType)
                {
                    //接收普通信息
                    case "text"://文本信息
                        requestXml.Content = rootElement.SelectSingleNode("Content").InnerText;
                        break;
                    case "image"://圖片信息
                        requestXml.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
                        break;
                    case "location"://地理位置信息
                        requestXml.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
                        requestXml.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
                        break;
                    //接收事件推送
                    //大概包括有:關(guān)注/取消關(guān)注事件、掃描帶參數(shù)二維碼事件、上報(bào)地理位置事件、自定義菜單事件、點(diǎn)擊菜單拉取消息時(shí)的事件推送、點(diǎn)擊菜單跳轉(zhuǎn)鏈接時(shí)的事件推送
                    case "event":
                        requestXml.Event = rootElement.SelectSingleNode("Event").InnerText;
                        requestXml.EventKey = rootElement.SelectSingleNode("EventKey").InnerText;
                        break;
                }

                string selday = "0";
                int hh = selday == "0" ? 60 : int.Parse(selday) * 24 * 60;
                //將發(fā)送方和接收方寫(xiě)入cookie中,后期使用
                CookieHelper.WriteCookie("WeChatFrom", "ToUserName", requestXml.ToUserName, hh);
                CookieHelper.WriteCookie("WeChatFrom", "FromUserName", requestXml.FromUserName, hh);

                //回復(fù)消息
                ResponseMsg(requestXml);
            }

        }
        #endregion 接收微信消息

3. Reply message

#region 回復(fù)消息(微信信息返回)
        /// <summary>
        /// 回復(fù)消息(微信信息返回)
        /// </summary>
        /// <param name="weixinXML"></param>
        private void ResponseMsg(RequestXml requestXml)
        {
            string resXml = "";
            string WeChat_Key = Request.QueryString["key"];

            try
            {
                DataTable dtWeChat = wechatdal.GetList("wechat_key=&#39;" + WeChat_Key + "&#39;").Tables[0];

                if (dtWeChat.Rows.Count > 0)
                {
                    replyset.User_ID = dtWeChat.Rows[0]["user_id"].ToString();
                    replyset.WeChat_ID = dtWeChat.Rows[0]["wechat_id"].ToString();
                    replyset.WeChat_Type = dtWeChat.Rows[0]["wechat_type"].ToString();
                    replyset.WeChat_Name = dtWeChat.Rows[0]["wechat_name"].ToString();

                    switch (requestXml.MsgType)
                    {
                        //當(dāng)收到文本信息的時(shí)候回復(fù)信息
                        case "text":
                            resXml = replyset.GetKeyword(requestXml.FromUserName, requestXml.ToUserName, requestXml.Content);
                            break;
                        //當(dāng)接收推送事件時(shí)回復(fù)的信息
                        case "event":
                            switch (requestXml.Event)
                            {
                                //關(guān)注的時(shí)候回復(fù)信息
                                case "subscribe":
                                    resXml = replyset.GetSubscribe(requestXml.FromUserName, requestXml.ToUserName);
                                    break;
                                //自定義菜單的時(shí)候回復(fù)信息
                                case "CLICK":
                                    resXml = replyset.GetMenuClick(requestXml.FromUserName, requestXml.ToUserName, requestXml.EventKey);
                                    break;
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Writebug("異常:" + ex.Message + "Struck:" + ex.StackTrace.ToString());
            }
            //發(fā)送xml格式的信息到微信中
            Response.Write(resXml);
            Response.End();
        }
        #endregion 回復(fù)消息(微信信息返回)

Load time of loading wechatapi.aspx

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod.ToLower() == "post")
            {
                RequestMsg();
            }
            else
            {
                //微信通過(guò)get請(qǐng)求驗(yàn)證api接口
                CheckWeChat();
            }
        }

reply.cs

public class replyset
    {
        public string hostUrl = "http://" + HttpContext.Current.Request.Url.Authority;          //域名
        public string upfileurl = "http://file.api.weixin.qq.com/cgi-bin/media/upload";
        public string baiduImg = "http://api.map.baidu.com/staticimage?center={0},{1}&width=700&height=300&zoom=11";
        public string User_ID = "";
        public string WeChat_ID = "";
        public string WeChat_Type = "";
        public string WeChat_Name = "";



        w_caidan_dal caidandal = new w_caidan_dal();
        w_reply_dal replydal = new w_reply_dal();
        w_article_dal articledal = new w_article_dal();
        w_keyword_dal keyworddal = new w_keyword_dal();
        w_vlimg_dal vlimgdal = new w_vlimg_dal();
        w_vlimg_model vlimgmodel = new w_vlimg_model();
        w_images_dal imagesdal = new w_images_dal();

        common wxCommand = new common();
        JsonOperate JsonOperate = new JsonOperate();
        JavaScriptSerializer Jss = new JavaScriptSerializer();

        public replyset()
        { }

        #region 關(guān)注回復(fù)
        /// <summary>
        /// 關(guān)注的時(shí)候回復(fù)
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <returns></returns>
        public string GetSubscribe(string FromUserName, string ToUserName)
        {
            string resXml = "";
            string sqlWhere = !string.IsNullOrEmpty(WeChat_ID) ? "WeChat_ID=" + WeChat_ID + " and reply_fangshi=2" : "";

            DataTable dtSubscribe = replydal.GetRandomList(sqlWhere, "1").Tables[0];

            if (dtSubscribe.Rows.Count > 0)
            {
                string article_id = dtSubscribe.Rows[0]["article_id"].ToString();
                string reply_type = dtSubscribe.Rows[0]["reply_type"].ToString();
                string reply_text = dtSubscribe.Rows[0]["reply_text"].ToString();

                if (reply_type == "text")
                {
                    resXml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + reply_text + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                }
                else
                {
                    resXml = GetArticle(FromUserName, ToUserName, article_id, User_ID);
                }
            }

            return resXml;
        }
        #endregion 關(guān)注回復(fù)

        #region 自動(dòng)回復(fù)
        /// <summary>
        /// 自動(dòng)默認(rèn)回復(fù)
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="WeChat_ID"></param>
        /// <param name="User_ID"></param>
        /// <returns></returns>
        public string GetDefault(string FromUserName, string ToUserName, string WeChat_ID, string User_ID)
        {
            string resXml = "";
            string sqlWhere = !string.IsNullOrEmpty(WeChat_ID) ? "WeChat_ID=" + WeChat_ID + " and reply_fangshi=1" : "";
            //獲取保存的默認(rèn)回復(fù)設(shè)置信息
            DataTable dtDefault = replydal.GetRandomList(sqlWhere, "1").Tables[0];

            if (dtDefault.Rows.Count > 0)
            {
                string article_id = dtDefault.Rows[0]["article_id"].ToString();
                string reply_type = dtDefault.Rows[0]["reply_type"].ToString();
                string reply_text = dtDefault.Rows[0]["reply_text"].ToString();
                //如果選擇的是文本
                if (reply_type == "text")
                {
                    resXml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + reply_text + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                }
                else
                {
                    //返回素材(圖文列表)
                    resXml = GetArticle(FromUserName, ToUserName, article_id, User_ID);
                }
            }

            return resXml;
        }
        #endregion 默認(rèn)回復(fù)


        #region 關(guān)鍵字回復(fù)
        /// <summary>
        /// 關(guān)鍵字回復(fù)
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        public string GetKeyword(string FromUserName, string ToUserName, string Content)
        {
            string resXml = "";
            string sqlWhere = "wechat_id=" + WeChat_ID + " and keyword_name=&#39;" + Content+"&#39;";

            DataTable dtKeyword = keyworddal.GetList(sqlWhere).Tables[0];
            
            if (dtKeyword.Rows.Count > 0)
            {
                dtKeyword = keyworddal.GetRandomList(sqlWhere, "1").Tables[0];

                if (dtKeyword.Rows.Count > 0)
                {
                    string article_id = dtKeyword.Rows[0]["article_id"].ToString();
                    string keyword_type = dtKeyword.Rows[0]["keyword_type"].ToString();
                    string keyword_text = dtKeyword.Rows[0]["keyword_text"].ToString();

                    switch (keyword_type)
                    {
                        case "text":
                            resXml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + keyword_text + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                            break;
                        case "news":
                            resXml = GetArticle(FromUserName, ToUserName, article_id, User_ID);
                            break;
                    }
                }
            }
            else
            {
                resXml = GetDefault(FromUserName, ToUserName, WeChat_ID, User_ID);
            }

            return resXml;
        }
        #endregion 關(guān)鍵字回復(fù)

        #region 菜單單擊
        /// <summary>
        /// 菜單點(diǎn)擊事件回復(fù)信息
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="EventKey"></param>
        /// <returns></returns>
        public string GetMenuClick(string FromUserName, string ToUserName, string EventKey)
        {
            string resXml = "";
            string sqlWhere = "wechat_id=" + WeChat_ID + " and caidan_key=&#39;" + EventKey + "&#39;";

            WriteTxt(sqlWhere);
            try
            {

                DataTable dtMenu = caidandal.GetList(sqlWhere).Tables[0];

                if (dtMenu.Rows.Count > 0)
                {
                    string article_id = dtMenu.Rows[0]["article_id"].ToString();
                    string caidan_retype = dtMenu.Rows[0]["caidan_retype"].ToString();
                    string caidan_retext = dtMenu.Rows[0]["caidan_retext"].ToString();


                    switch (caidan_retype)
                    {
                        case "text":
                            resXml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + caidan_retext + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                            break;
                        case "news":
                            resXml = GetArticle(FromUserName, ToUserName, article_id, User_ID);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteTxt("異常:" + ex.Message + "Struck:" + ex.StackTrace.ToString());
            }

            return resXml;
        }
        #endregion 菜單單擊

        #region 獲取素材
        /// <summary>
        /// 獲取素材
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="Article_ID"></param>
        /// <param name="User_ID"></param>
        /// <returns></returns>
        public string GetArticle(string FromUserName, string ToUserName, string Article_ID, string User_ID)
        {
            string resXml = "";

            DataTable dtArticle = articledal.GetList("article_id=" + Article_ID + " OR article_layid=" + Article_ID).Tables[0];

            if (dtArticle.Rows.Count > 0)
            {
                resXml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content><ArticleCount>" + dtArticle.Rows.Count + "</ArticleCount><Articles>";

                foreach (DataRow Row in dtArticle.Rows)
                {
                    string article_title = Row["article_title"].ToString();
                    string article_description = Row["article_description"].ToString();
                    string article_picurl = Row["article_picurl"].ToString();
                    string article_url = Row["article_url"].ToString();
                    string article_type = Row["article_type"].ToString();

                    switch (article_type)
                    {
                        case "Content":
                            article_url = hostUrl + "/web/wechat/api/article.aspx?aid=" + Row["Article_ID"].ToString();
                            break;
                        case "Href":
                            article_url = Row["article_url"].ToString();
                            break;
                    }

                    if (string.IsNullOrEmpty(article_url))
                    {
                        article_url = hostUrl + "/web/wechat/api/article.aspx?aid=" + Row["Article_ID"].ToString();
                    }

                    article_url += (article_url.IndexOf("uid=") > -1 ? "" : (article_url.IndexOf("?") > -1 ? "&" : "?") + "uid=" + User_ID);
                    article_url += (article_url.IndexOf("wxid=") > -1 ? "" : (article_url.IndexOf("?") > -1 ? "&" : "?") + "wxid=" + FromUserName);
                    article_url += (article_url.IndexOf("wxref=") > -1 ? "" : (article_url.IndexOf("?") > -1 ? "&" : "?") + "wxref=mp.weixin.qq.com");

                    resXml += "<item><Title><![CDATA[" + article_title + "]]></Title><Description><![CDATA[" + article_description + "]]></Description><PicUrl><![CDATA[" + article_picurl + "]]></PicUrl><Url><![CDATA[" + article_url + "]]></Url></item>";
                }

                resXml += "</Articles><FuncFlag>1</FuncFlag></xml>";
            }

            return resXml;
        }
        #endregion 獲取圖文列表

      

        #region 通用方法
        /// <summary>
        /// unix時(shí)間轉(zhuǎn)換為datetime
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        private DateTime UnixTimeToTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// datetime轉(zhuǎn)換為unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 記錄bug,以便調(diào)試
        /// </summary>
        /// <returns></returns>
        public bool WriteTxt(string str)
        {
            try
            {
                FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("Log/wxbugLog.txt"), FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                //開(kāi)始寫(xiě)入
                sw.WriteLine(str);
                //清空緩沖區(qū)
                sw.Flush();
                //關(guān)閉流
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        #endregion 通用方法
    }
}

2. Keyword reply

Keyword reply is also very simple. We first set the corresponding keywords and returned information, and then return the corresponding information based on whether the set keywords exist in the received information.

1. Set keywords (I won’t say more here)

2. Receiving messages and replying to messages have also been mentioned before. Here I only post the method of judging keyword replies for your reference.

#region 關(guān)鍵字回復(fù)
        /// <summary>
        /// 關(guān)鍵字回復(fù)
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        public string GetKeyword(string FromUserName, string ToUserName, string Content)
        {
            string resXml = "";
            string sqlWhere = "wechat_id=" + WeChat_ID + " and keyword_name=&#39;" + Content+"&#39;";

            DataTable dtKeyword = keyworddal.GetList(sqlWhere).Tables[0];
            
            if (dtKeyword.Rows.Count > 0)
            {
                dtKeyword = keyworddal.GetRandomList(sqlWhere, "1").Tables[0];

                if (dtKeyword.Rows.Count > 0)
                {
                    string article_id = dtKeyword.Rows[0]["article_id"].ToString();
                    string keyword_type = dtKeyword.Rows[0]["keyword_type"].ToString();
                    string keyword_text = dtKeyword.Rows[0]["keyword_text"].ToString();

                    switch (keyword_type)
                    {
                        case "text":
                            resXml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + keyword_text + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                            break;
                        case "news":
                            resXml = GetArticle(FromUserName, ToUserName, article_id, User_ID);
                            break;
                    }
                }
            }
            else
            {
                resXml = GetDefault(FromUserName, ToUserName, WeChat_ID, User_ID);
            }

            return resXml;
        }
        #endregion 關(guān)鍵字回復(fù)

There are many other picture replies, QR code scanning reply information, etc. They are all similar, and the processing methods are similar. You can get it done quickly by referring to the development documents. I won’t go into more details here. I will discuss what I don’t understand.

For more .Net implementation of WeChat public platform development interface "information reply" related articles, please pay attention to the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72