>  기사  >  위챗 애플릿  >  C# .net WeChat 개발, 개발 인증, 주의 트리거 메시지, 자동 응답, 이벤트 응답, 사용자 정의 메뉴

C# .net WeChat 개발, 개발 인증, 주의 트리거 메시지, 자동 응답, 이벤트 응답, 사용자 정의 메뉴

高洛峰
高洛峰원래의
2017-02-13 12:00:292747검색
개발자 되기


아아아아


계정 팔로우, 메시지 트리거, 자동 응답, 이벤트 응답

C# .net微信开发,开发认证,关注触发消息,自动应答,事件响应,自定义菜单 C# .net微信开发,开发认证,关注触发消息,自动应答,事件响应,自定义菜单

C# .net微信开发,开发认证,关注触发消息,自动应答,事件响应,自定义菜单 C# .net微信开发,开发认证,关注触发消息,自动应答,事件响应,自定义菜单

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"]);
}

보조수업

namespace ElegantWM.WebUI.Areas.WeiXin.Controllers
{
    /// <summary>
    /// 微信公共服务类
    /// </summary>
    public class RobotController : BaseController
    {
        /// <summary>
        /// 接收微信请求接口,认证的接口
        /// </summary>
        /// <returns></returns>
        public ContentResult Index()
        {
            string result = AnalyzeXmlFromWeiXin();
            return Content(result);
        }

        /// <summary>
        /// 分析微信POST到本服务器的XML数据
        /// </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 "不被支持的关键字!";
            }
        }

        /// <summary>
        /// 响应文本消息
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private string OnReceiveTextMsg(string xml)
        {
            WxTextMsg msg = XmlEntityExchange<WxTextMsg>.ConvertXml2Entity(xml);
            //返回消息,互换收发用户
            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,请回复数字,选择服务").Append("\n\n");
            sb.Append("1. 当前时间").Append("\n");
            sb.Append("2. 天气信息").Append("\n");
            sb.Append("3. 聊天唠嗑").Append("\n");
            sb.Append("n. 更多服务开发中...").Append("\n");
            sb.Append("回复【?】显示此帮助菜单");
            return sb.ToString();
        }

        /// <summary>
        /// 当用户关注微信帐号的时候触发,事件响应
        /// </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";
            //如果是关注,则发送欢迎消息
            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;
        }
    }
}
//实体
public class WxEvent
    {
        /// <summary>
        /// 接收人
        /// </summary>
        public string ToUserName { get; set; }
        /// <summary>
        /// 发送人
        /// </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>
        /// 发送人
        /// </summary>
        public string FromUserName { get; set; }
        /// <summary>
        /// 时间
        /// </summary>
        public long CreateTime { get; set; }
        /// <summary>
        /// 类型
        /// </summary>
        public string MsgType { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
    }

C# .net微信开发,开发认证,关注触发消息,自动应答,事件响应,自定义菜单

기본수업 : http 요청

//XML和实体对象间的相互转化
namespace ElegantWM.WebUI.Areas.WeiXin
{
    public class XmlEntityExchange<T> where T : new()
    {
        /// <summary>
        /// 将XML转换为对象
        /// </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>
        /// 构造微信消息
        /// </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();
        }
    }
}


토큰 받기:


/* *
 * Copyright © 2013 CCT All Rights Reserved 
 * 作者:JackChain 
 * 时间:2013/8/23 18:21:23
 * 功能:跨域访问
 * 版本:V1.0
 *
 * 修改人:
 * 修改点:
 * */namespace ElegantWM.Tools
{    public class HttpCrossDomain
    {        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 跨域访问        /// 039f3e95db2a684c7b74365531eb6044
        /// 0ab5e68b8f5d292e9a5f810a0a5b29298bb7487ae6a16a43571bc14c7fcf93c2
        /// 7531765eb83dfc8ac7e7b1c75b5063d28bb7487ae6a16a43571bc14c7fcf93c2
        /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3
        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);
        }        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 跨域访问        /// 039f3e95db2a684c7b74365531eb6044
        /// 0ab5e68b8f5d292e9a5f810a0a5b29298bb7487ae6a16a43571bc14c7fcf93c2
        /// 7531765eb83dfc8ac7e7b1c75b5063d28bb7487ae6a16a43571bc14c7fcf93c2
        /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3
        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);
        }

    }
}


받기 및 업데이트 메뉴


public class CommonController : Controller
    {
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 获取微信凭证
        /// 039f3e95db2a684c7b74365531eb6044
        /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3
        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);
        }
    }


더보기 C#.net WeChat 개발, 개발 인증, 주의 유발 메시지, 자동 응답, 이벤트 응답, 맞춤 메뉴 관련 부탁드립니다. 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.