C# .NET 微信开发-------当微信服务器推送消息时如何接收处理
最近一直在看微信,整整一个月了,看到现在说实话还有很多没看的,从前两周一点看不懂到现在单个功能的一步步实现,不知道这样的速度是否太慢了。
不过现在往下看还是有思路了,目前整个文档完成学习只有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 微信开发-------当微信服务器推送消息时如何接收处理的更多相关文章
- HTML5服务器推送消息的各种解决办法,html5服务器
HTML5服务器推送消息的各种解决办法,html5服务器 摘要 在各种BS架构的应用程序中,往往都希望服务端能够主动地向客户端推送各种消息,以达到类似于邮件.消息.待办事项等通知. 往BS架构本身存在 ...
- [wxpusher]分享一个服务器推送消息到微信上的小工具,可以用于微信推送提醒和告警。
背景 作为一个程序员,业余搞点自己的东西很正常,一般程序员都会有一两台自己的服务器,谁叫今天xx云搞活动,明天yy云搞活动呢. 自家的服务器用来跑爬虫,跑博客,或者跑一些个人业务,但当服务有新状态,抢 ...
- 微信小程序简单的推送消息流程
1.进入开发设置-消息推送,启用消息推送 url: 启用并设置消息推送配置后,用户发给小程序的消息以及开发者需要的事件推送,都将被微信转发至该服务器地址中. 2.创建消息模板. 3.WXML代码: 4 ...
- 微信硬件平台(八) 4 ESP8266通过微信公众号给用户推送消息
https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=自己申请微信公众号的TOKEN 输出结果: 由于aRDUINO串 ...
- HTML5服务器推送消息的各种解决办法
摘要 在各种BS架构的应用程序中,往往都希望服务端能够主动地向客户端推送各种消息,以达到类似于邮件.消息.待办事项等通知. 往BS架构本身存在的问题就是,服务器一直采用的是一问一答的机制.这就意味着如 ...
- iOS 推送,当接到推送消息时如何处理?
接收到通知时有两种进入的方式:1.当app未运行时(BOOL)application:(UIApplication *)application didFinishLaunchingWithOption ...
- IOS 在不打开电话服务的时候,可以响应服务器的推送消息,从而接收服务器的推送消息
在做即时通讯(基于xmpp框架)的时候遇到这样一个问题,就是在真机测试的时候,你按Home键返回桌面,在你返回桌面的时候,这是你的程序的挂起状态的,在你挂起的时候, 相当于你的程序是死的,程序的所有进 ...
- 跨平台移动开发 Android使用JPush推送消息
二话不说,直接上图,看效果 第一步在官网下载 Android Push SDK https://www.jpush.cn/sdk/android 第二步 创建注册帐号,应用 第三步 下载应用,导入l ...
- post推送消息时的乱码
URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求 ...
随机推荐
- python3 速查参考- python基础 9 -> MySQL基础概念、数据库create、alter、insert、update、delete、select等基础命令
前置步骤: 下载一个绿色版的mysql数据库客户端连接工具 :http://wosn.net/821.html mysql平台为win7(以后会有CentOS上的) 学习目的: 掌握数据库的基本概念, ...
- USACO 1.2 Broken Necklace
断点是白色的情况在做题的时候完全没有想到呢... 看到了数据才发现这个问题$qwq$ /* ID:Starry21 LANG:C++ TASK:beads */ #include<iostrea ...
- 调用存储在session属性里的东西
将对象放在session里面 request.getSession().setAttribute("username", username); //放到会话里 永EL表达式调用 $ ...
- 11个顶级 JavaScript 日历插件
参考链接:https://mp.weixin.qq.com/s?__biz=MzI3NzIzMDY0NA==&mid=2247487050&idx=1&sn=e1cf66726 ...
- Spark性能调优:广播大变量broadcast
Spark性能调优:广播大变量broadcast 原文链接:https://blog.csdn.net/leen0304/article/details/78720838 概要 有时在开发过程中,会遇 ...
- PAT B1006 换个格式输出整数 (15)
AC代码 #include <cstdio> const int max_n = 3; char radix[max_n] = {' ', 'S', 'B'}; int ans[max_n ...
- c语言中int long float double 等类型所占字节及输出表示(转)
16位编译器 char :1个字节 char*(即指针变量): 2个字节 short int : 2个字节 int: 2个字节 unsigned int : 2个字节 float: 4个字节 doub ...
- Docker——网络和存储(数据卷)
iptables -t nat -vnL |grep docker 查看docker桥接网卡:brctl show 本地端口随机映射到docker容器的80端口上: docker run -d -P ...
- Windows authentication for WCF web services error
WCF Web服务的Windows身份验证在部署到IIS时,默认网站添加应用程序的方式.浏览运行.svc文件报错. 错误代码: The authentication schemes configure ...
- Scala学习五——类
一.本章要点 类中的字段自动带有getter方法和setter方法 你可以用定制的getter/setter方法替换掉字段的定义,而不必修改使用类的客户端——这就是所谓的”统一访问原则“ 用@Bean ...