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

Table of Contents
Become a developer
Follow the account, trigger messages, automatically respond, event response
Home WeChat Applet WeChat Development C# .net WeChat development, development certification, attention to trigger messages, automatic response, event response, custom menu

C# .net WeChat development, development certification, attention to trigger messages, automatic response, event response, custom menu

Feb 13, 2017 pm 12:00 PM

Become a developer


string[]?ArrTmp?=?{?"token",?
Request["timestamp"],?
Request["nonce"]?};
Array.Sort(ArrTmp);?????
//字典排序string?tmpStr?=?string.Join("",?ArrTmp);
tmpStr?=?FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr,?"SHA1");
tmpStr?=?tmpStr.ToLower();if?(tmpStr?!=?Request["signature"].ToLower())
{
???Response.Write(Request["echostr"]);
}


Follow the account, trigger messages, automatically respond, event response

C# .net微信開發(fā),開發(fā)認證,關(guān)注觸發(fā)消息,自動應(yīng)答,事件響應(yīng),自定義菜單 C# .net微信開發(fā),開發(fā)認證,關(guān)注觸發(fā)消息,自動應(yīng)答,事件響應(yīng),自定義菜單

C# .net微信開發(fā),開發(fā)認證,關(guān)注觸發(fā)消息,自動應(yīng)答,事件響應(yīng),自定義菜單 C# .net微信開發(fā),開發(fā)認證,關(guān)注觸發(fā)消息,自動應(yīng)答,事件響應(yīng),自定義菜單 ##

namespace ElegantWM.WebUI.Areas.WeiXin.Controllers
{
    /// <summary>
    /// 微信公共服務(wù)類
    /// </summary>
    public class RobotController : BaseController
    {
        /// <summary>
        /// 接收微信請求接口,認證的接口
        /// </summary>
        /// <returns></returns>
        public ContentResult Index()
        {
            string result = AnalyzeXmlFromWeiXin();
            return Content(result);
        }

        /// <summary>
        /// 分析微信POST到本服務(wù)器的XML數(shù)據(jù)
        /// </summary>
        /// <param name="xmlStream"></param>
        /// <returns></returns>
        private string AnalyzeXmlFromWeiXin()
        {
            StreamReader reader = new StreamReader(Request.InputStream);
            string xml = reader.ReadToEnd();
            //獲取MsgType
            log.Info(xml);
            string msgType = XmlHelper.ReadXmlStr(xml, "/xml/MsgType", "");
            switch (msgType)
            {
                case "event"://如果是事件
                    return OnAttention(xml);
                case "text"://如果是文本消息
                    return OnReceiveTextMsg(xml);
                default:
                    return "不被支持的關(guān)鍵字!";
            }
        }

        /// <summary>
        /// 響應(yīng)文本消息
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private string OnReceiveTextMsg(string xml)
        {
            WxTextMsg msg = XmlEntityExchange<WxTextMsg>.ConvertXml2Entity(xml);
            //返回消息,互換收發(fā)用戶
            string toUser = msg.FromUserName;
            msg.FromUserName = msg.ToUserName;
            msg.ToUserName = toUser;

            switch (msg.Content.Trim())
            {
                case "?":
                    msg.Content = HelpDocument();
                    break;
                case "?":
                    msg.Content = HelpDocument();
                    break;
                case "1":
                    msg.Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    break;
                case "2":
                    msg.Content = Tools.HttpCrossDomain.Get("http://www.weather.com.cn/data/sk/101210301.html");
                    break;
                case "3":
                    msg.Content = "來吧,想嘮點什么呢? [偷笑]";
                    break;
                case "你是男的女的":
                    msg.Content = "姑娘一枚 [偷笑]";
                    break;
                default:
                    msg.Content = "抱歉哦,我不認識您輸入的命令。/害羞 /:,@-D";
                    break;
            }
            return XmlEntityExchange<WxTextMsg>.ConvertEntity2Xml(msg);
        }
        /// <summary>
        /// 獲取幫助菜單文檔
        /// </summary>
        /// <returns></returns>
        private string HelpDocument()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("HI,請回復(fù)數(shù)字,選擇服務(wù)").Append("\n\n");
            sb.Append("1. 當(dāng)前時間").Append("\n");
            sb.Append("2. 天氣信息").Append("\n");
            sb.Append("3. 聊天嘮嗑").Append("\n");
            sb.Append("n. 更多服務(wù)開發(fā)中...").Append("\n");
            sb.Append("回復(fù)【?】顯示此幫助菜單");
            return sb.ToString();
        }

        /// <summary>
        /// 當(dāng)用戶關(guān)注微信帳號的時候觸發(fā),事件響應(yīng)
        /// </summary>
        /// <param name="xml"></param>
        private string OnAttention(string xml)
        {
            WxEvent wxevent = XmlEntityExchange<WxEvent>.ConvertXml2Entity(xml);
            WxTextMsg msg = new WxTextMsg();
            msg.ToUserName = wxevent.FromUserName;
            msg.FromUserName = wxevent.ToUserName;
            msg.CreateTime = DateTime.Now.Ticks;
            msg.MsgType = "text";
            //如果是關(guān)注,則發(fā)送歡迎消息
            switch (wxevent.Event)
            {
                case "subscribe":
                    msg.Content = System.Configuration.ConfigurationManager.AppSettings["DefaultWxMsg"];
                    break;
                case "CLICK":
                    msg.Content = "您單擊的是:" + wxevent.EventKey;
                    break;
                default:
                    msg.Content = "暫未處理的事件:Event" + wxevent.Event + ";EventKey:" + wxevent.EventKey;
                    break;
            }
            string rst = XmlEntityExchange<WxTextMsg>.ConvertEntity2Xml(msg);
            log.Info(rst);
            return rst;
        }
    }
}

Auxiliary class

//實體
public class WxEvent
    {
        /// <summary>
        /// 接收人
        /// </summary>
        public string ToUserName { get; set; }
        /// <summary>
        /// 發(fā)送人
        /// </summary>
        public string FromUserName { get; set; }
        /// <summary>
        /// 時間
        /// </summary>
        public string CreateTime { get; set; }
        /// <summary>
        /// 類型
        /// </summary>
        public string MsgType { get; set; }
        /// <summary>
        /// 事件
        /// </summary>
        public string Event { get; set; }

        public string EventKey { get; set; }
    }

public class WxTextMsg
    {
        /// <summary>
        /// 接收人
        /// </summary>
        public string ToUserName { get; set; }
        /// <summary>
        /// 發(fā)送人
        /// </summary>
        public string FromUserName { get; set; }
        /// <summary>
        /// 時間
        /// </summary>
        public long CreateTime { get; set; }
        /// <summary>
        /// 類型
        /// </summary>
        public string MsgType { get; set; }
        /// <summary>
        /// 內(nèi)容
        /// </summary>
        public string Content { get; set; }
    }
//XML和實體對象間的相互轉(zhuǎn)化
namespace ElegantWM.WebUI.Areas.WeiXin
{
    public class XmlEntityExchange<T> where T : new()
    {
        /// <summary>
        /// 將XML轉(zhuǎn)換為對象
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T ConvertXml2Entity(string xml)
        {
            XmlDocument doc = new XmlDocument();
            PropertyInfo[] propinfos = null;
            doc.LoadXml(xml);
            XmlNodeList nodelist = doc.SelectNodes("/xml");
            T entity = new T();
            foreach (XmlNode node in nodelist)
            {
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = entity.GetType();
                    propinfos = objtype.GetProperties();
                }
                //填充entity類的屬性
                foreach (PropertyInfo pi in propinfos)
                {
                    XmlNode cnode = node.SelectSingleNode(pi.Name);
                    pi.SetValue(entity, Convert.ChangeType(cnode.InnerText, pi.PropertyType), null);
                }
            }
            return entity;
        }

        /// <summary>
        /// 構(gòu)造微信消息
        /// </summary>
        /// <param name="t">對象實體</param>
        /// <returns>返回微信消息xml格式</returns>
        public static string ConvertEntity2Xml(T t)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<xml>");
            Type objtype = t.GetType();
            //填充entity類的屬性
            foreach (PropertyInfo pi in objtype.GetProperties())
            {
                object obj = pi.GetValue(t);
                string value = obj == null ? "" : obj.ToString();
                if (pi.PropertyType.Name.ToLower() == "int64")
                    builder.Append("<" + pi.Name + ">" + value + "</" + pi.Name + ">");
                else
                    builder.Append("<" + pi.Name + "><![CDATA[" + value + "]]></" + pi.Name + ">");
            }
            builder.Append("</xml>");
            return builder.ToString();
        }
    }
}

C# .net微信開發(fā),開發(fā)認證,關(guān)注觸發(fā)消息,自動應(yīng)答,事件響應(yīng),自定義菜單

Basic class: http request

/* *
 * Copyright ? 2013 CCT All Rights Reserved 
 * 作者:JackChain 
 * 時間:2013/8/23 18:21:23
 * 功能:跨域訪問
 * 版本:V1.0
 *
 * 修改人:
 * 修改點:
 * */namespace ElegantWM.Tools
{    public class HttpCrossDomain
    {        /// <summary>
        /// 跨域訪問        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Post(string url, string param, int time = 60000)
        {
            Uri address = new Uri(url);
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8"; //"application/x-www-form-urlencoded";
            request.Timeout = time;            byte[] byteData = UTF8Encoding.UTF8.GetBytes(param == null ? "" : param);
            request.ContentLength = byteData.Length;            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }            string result = "";            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }            return (result);
        }        /// <summary>
        /// 跨域訪問        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Get(string url, int time = 60000)
        {
            Uri address = new Uri(url);
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/json;charset=utf-8"; //"application/x-www-form-urlencoded";
            request.Timeout = time;            string result = "";            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }            return (result);
        }

    }
}


Get Token:


public class CommonController : Controller
    {
        /// <summary>
        /// 獲取微信憑證
        /// </summary>
        /// <returns></returns>
        public JsonResult GetWxCredential()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
            url = string.Format(url, ConfigurationManager.AppSettings["AppId"], ConfigurationManager.AppSettings["AppSecret"]);
            string rst = HttpCrossDomain.Get(url);
            if (rst.Contains("access_token"))
            {
                string tokenId=rst.Replace("{\"access_token\":\"", "").Replace("\",\"expires_in\":7200}", "");
                CacheHelper.CacheInsertAddMinutes("access_token",tokenId,120);
                return Json(tokenId, JsonRequestBehavior.AllowGet);
            }
            else
                return Json(rst, JsonRequestBehavior.AllowGet);
        }
    }


Get and update menu


/// <summary>
        /// 獲取微信菜單
        /// </summary>
        /// <returns></returns>
        public JsonResult Get()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";
            if (CacheHelper.CacheValue("access_token") != null)
            {
                url = url + CacheHelper.CacheValue("access_token").ToString();
            }
            string rst = HttpCrossDomain.Get(url);
            return Json(rst,JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 創(chuàng)建Menu
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Create(string json)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
            if (CacheHelper.CacheValue("access_token") != null)
            {
                url = url+CacheHelper.CacheValue("access_token").ToString();
            }
            string rst = HttpCrossDomain.Post(url, json);
            return Json(rst);
        }


More C# .net WeChat development, development certification, attention to trigger messages, automatic responses, event responses, custom menus related Please pay attention to the PHP Chinese website for articles!

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