最近一直在看微信,整整一个月了,看到现在说实话还有很多没看的,从前两周一点看不懂到现在单个功能的一步步实现,不知道这样的速度是否太慢了。

不过现在往下看还是有思路了,目前整个文档完成学习只有1/3左右,但是看过的每个接口都是测试过的。学习很重要,但是有人指引将会效率翻倍,但是谁会愿意无偿花自己的时间给你呢,所以嘛。。。就不说了,

好了,牢骚到此,对于我这篇文章有什么不明白的或者需要交流的请加   QQ群:216390234

首先来门要有思路对吧,我们不是流水线的工人,而是系统的创造者,所以我们要有思想而不是一味的写代码,写到最后发现哪哪都不合适然后去修改,发现修改的时间远远大于开发的时间,那样就徒劳了。

这篇很简单适用于刚刚入门的开发者:

对于微信的基本配置我就不阐述了,网上讲解的很详细了。

1、项目:MVC(不是api)

2、

  public ActionResult Index()
{
string result = "";
string postString = string.Empty;
if (Request.HttpMethod.ToUpper() == "POST")
{
using (Stream stream = System.Web.HttpContext.Current.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, , (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
if (!string.IsNullOrEmpty(postString))
{
string SendToWx = string.Empty;
//这里写方法解析Xml
XmlDocument xml = new XmlDocument();//
xml.LoadXml(postString);
XmlElement xmlElement = xml.DocumentElement;
//这里进行判断MsgType
switch (xmlElement.SelectSingleNode("MsgType").InnerText)
{
case "text":
SendToWx = WxText.GetWxTextXml(postString);
break;
case "image":
SendToWx = WxImage.GetWxImageXml(postString);
break;
case "voice":
break;
case "video":
break;
case "shortvideo":
break;
case "location":
break;
case "link":
break;
case "event":
string eventKey = xmlElement.SelectSingleNode("EventKey").InnerText == null ? "" : xmlElement.SelectSingleNode("EventKey").InnerText;
switch (xmlElement.SelectSingleNode("Event").InnerText)
{
case "subscribe":
if (string.IsNullOrEmpty(eventKey))
{
//model = new Models.Receive_Event();
}
else
{
//model = new Models.Receive_Event_Scan();
}
break;
case "unsubscribe":
break;
case "SCAN":
break;
case "LOCATION":
break;
case "CLICK":
break;
case "VIEW":
break;
default:
break;
}
break;
default:
result = "没有识别的类型消息:" + xmlElement.SelectSingleNode("MsgType").InnerText;
WriteLog(result);
break;
}
if (!string.IsNullOrEmpty(SendToWx))
{
System.Web.HttpContext.Current.Response.Write(SendToWx);
System.Web.HttpContext.Current.Response.End();
}
else
{
result = "回传数据为空";
WriteLog(result);
}
}
else
{
result = "微信推送的数据为:" + postString;
WriteLog(result);
}
}
}
else if (Request.HttpMethod.ToUpper() == "GET")
{
string token = ConfigurationManager.AppSettings["WXToken"];//从配置文件获取Token
if (string.IsNullOrEmpty(token))
{
result = string.Format("微信Token配置项没有配置!");
WriteLog(result);
}
string echoString = System.Web.HttpContext.Current.Request.QueryString["echoStr"];
string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];
string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];
string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];
if (CheckSignature(token, signature, timestamp, nonce))
{
if (!string.IsNullOrEmpty(echoString))
{
System.Web.HttpContext.Current.Response.Write(echoString);
System.Web.HttpContext.Current.Response.End();
result = string.Format("微信Token配置成功,你已成为开发者!");
WriteLog(result);
}
}
}
result = string.Format("页面被访问,没有请求数据!");
WriteLog(result);
return View();
}
  public bool CheckSignature(string token, string signature, string timestamp, string nonce)
{
string[] ArrTmp = { token, timestamp, nonce };
Array.Sort(ArrTmp);
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
  private void WriteLog(string str)
{
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("//LLog//log.txt"), System.IO.FileMode.Append))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs))
{
string strlog = "----" + DateTime.Now.ToString("yyyyMMddHHmmss") + ":" + str + "-----";
sw.WriteLine(strlog);
sw.Close();
}
}
}
catch
{ }
}
  public class WxText
{
public static string GetWxTextXml(string StrXml)
{
string result = string.Empty;
//加载xml
XmlDocument textXml = new XmlDocument();
textXml.LoadXml(StrXml);
XmlElement xmlElement = textXml.DocumentElement;
//转成model对象
Receive_Text model = new Receive_Text()
{
ToUserName = xmlElement.SelectSingleNode("ToUserName").InnerText,
FromUserName = xmlElement.SelectSingleNode("FromUserName").InnerText,
CreateTime = xmlElement.SelectSingleNode("CreateTime").InnerText,
MsgType = xmlElement.SelectSingleNode("MsgType").InnerText,
Content = xmlElement.SelectSingleNode("Content").InnerText,
MsgId = xmlElement.SelectSingleNode("MsgId").InnerText
};
//数据组织拼接返回xml
if (model.Content == "你好!")
{
//返回的xml
result = string.Format(Xml.TextMsg,model.FromUserName,model.ToUserName,DateTimeHelper.DateTimeToUnixInt(DateTime.Now),"你好!接口测试通过了!恭喜你!");
}
return result;
}
}
     public abstract class ReceiveModel
{ /// <summary>
/// 接收方帐号(收到的OpenID)
/// </summary>
public string ToUserName { get; set; }
/// <summary>
/// 发送方帐号(一个OpenID)
/// </summary>
public string FromUserName { get; set; }
/// <summary>
/// 消息创建时间 (整型)
/// </summary>
public string CreateTime { get; set; }
/// <summary>
/// 消息类型
/// </summary>
public string MsgType { get; set; } /// <summary>
/// 当前实体的XML字符串
/// </summary>
public string Xml { get; set; }
}
/// <summary>
/// 接收普通消息-文本消息
/// </summary>
public class Receive_Text : ReceiveModel
{ /// <summary>
/// 文本消息内容
/// </summary>
public string Content { get; set; } /// <summary>
/// 消息id,64位整型
/// </summary>
public string MsgId { get; set; }
}
  public class Xml
{
#region 文本xml
/// <summary>
/// ToUserName:用户ID(OpenID)
/// FromUserName:开发者
/// CreateTime:时间
/// Content:内容
/// </summary>
public static string TextMsg
{
get
{
return @"
<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{3}]]></Content>
</xml>
";
}
}
#endregion
}

4、上面是代码整个流程所用到的代码都贴出来了,有什么不明白的可以加上面的QQ群

C# .NET 微信开发-------当微信服务器推送消息时如何接收处理的更多相关文章

  1. HTML5服务器推送消息的各种解决办法,html5服务器

    HTML5服务器推送消息的各种解决办法,html5服务器 摘要 在各种BS架构的应用程序中,往往都希望服务端能够主动地向客户端推送各种消息,以达到类似于邮件.消息.待办事项等通知. 往BS架构本身存在 ...

  2. [wxpusher]分享一个服务器推送消息到微信上的小工具,可以用于微信推送提醒和告警。

    背景 作为一个程序员,业余搞点自己的东西很正常,一般程序员都会有一两台自己的服务器,谁叫今天xx云搞活动,明天yy云搞活动呢. 自家的服务器用来跑爬虫,跑博客,或者跑一些个人业务,但当服务有新状态,抢 ...

  3. 微信小程序简单的推送消息流程

    1.进入开发设置-消息推送,启用消息推送 url: 启用并设置消息推送配置后,用户发给小程序的消息以及开发者需要的事件推送,都将被微信转发至该服务器地址中. 2.创建消息模板. 3.WXML代码: 4 ...

  4. 微信硬件平台(八) 4 ESP8266通过微信公众号给用户推送消息

    https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=自己申请微信公众号的TOKEN 输出结果:  由于aRDUINO串 ...

  5. HTML5服务器推送消息的各种解决办法

    摘要 在各种BS架构的应用程序中,往往都希望服务端能够主动地向客户端推送各种消息,以达到类似于邮件.消息.待办事项等通知. 往BS架构本身存在的问题就是,服务器一直采用的是一问一答的机制.这就意味着如 ...

  6. iOS 推送,当接到推送消息时如何处理?

    接收到通知时有两种进入的方式:1.当app未运行时(BOOL)application:(UIApplication *)application didFinishLaunchingWithOption ...

  7. IOS 在不打开电话服务的时候,可以响应服务器的推送消息,从而接收服务器的推送消息

    在做即时通讯(基于xmpp框架)的时候遇到这样一个问题,就是在真机测试的时候,你按Home键返回桌面,在你返回桌面的时候,这是你的程序的挂起状态的,在你挂起的时候, 相当于你的程序是死的,程序的所有进 ...

  8. 跨平台移动开发 Android使用JPush推送消息

    二话不说,直接上图,看效果 第一步在官网下载 Android Push SDK https://www.jpush.cn/sdk/android 第二步 创建注册帐号,应用 第三步  下载应用,导入l ...

  9. post推送消息时的乱码

    URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求 ...

随机推荐

  1. 树莓派(Linux)添加USB外接硬盘

    1.显示系统的硬盘设备以及分区 sudo fdisk -l 显示设备名,例如/dev/sda1 2.树莓派默认不支持NTFS文件系统,如果需要支持则要安装相应的软件包 sudo apt-get ins ...

  2. $nextTick的使用

    原文地址 概览 官方文档说明: 用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 疑问: DOM 更新循环是指什么? 下次更新循环是什么时候 ...

  3. 部署 --- Docker

    Docker学习 介绍 : Docker速度更快.性能更高.操作更易.我们开发的不同的程序APP是需要在操作系统中单独的环境中隔离运行的. 为了能让我们不同的程序可以在隔离的环境中运行:我们可以使用虚 ...

  4. 阿里P8架构师谈:Restful、SOAP、RPC、SOA、微服务之间的区别(转载)

    转载来源:https://youzhixueyuan.com/the-difference-between-restful-soap-rpc-soa-and-micro-service.html 内容 ...

  5. 二分图的最大匹配以及带权匹配【匈牙利算法+KM算法】

    二分图算法包括 匈牙利算法 与 KM算法. 匈牙利算法 在这里写上模板. 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2063 #include< ...

  6. PTA (Advanced Level)1035.Password

    To prepare for PAT, the judge sometimes has to generate random passwords for the users. The problem ...

  7. SOSdp

    layout: post title: SOSdp author: "luowentaoaa" catalog: true tags: mathjax: true - codefo ...

  8. php 正则替换特殊字符 和检测是否是中文

    如果是只想输入中文的话,就这么写,要注意是分gb2312和utf-8的哦: gb2312:if(!preg_match("/^[".chr(0xa1)."-". ...

  9. Laravel-admin 消息提醒、播放音频、点击跳转

    jquery-toastr 消息提醒.播放音频.点击跳转 应用情景,有新的订单生成,后台进行消息提醒并播放音频(这里用到轮询简单实现):下面附代码 1.找到laravel-admin 中的 index ...

  10. GoJS

    GoJS GoJS示例 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...