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(); // 设置通用的请求 ...
随机推荐
- maven-插件地址
Maven官方有两个插件列表, 第一个列表的GroupId 为 org.apache.maven.plugins,这里的插件最为成熟,具体地址为:http://maven.apache.org/plu ...
- Redis4.0新特性 -Lazy Free
Redis4.0新增了非常实用的lazy free特性,从根本上解决Big Key(主要指定元素较多集合类型Key)删除的风险.笔者在redis运维中也遇过几次Big Key删除带来可用性和性能故障. ...
- PHP非对称加密
加密的类型: 在日常设计及开发中,为确保数据传输和数据存储的安全,可通过特定的算法,将数据明文加密成复杂的密文.目前主流加密手段大致可分为单向加密和双向加密. 单向加密:通过对数据进行摘要计算生成密文 ...
- 【并行计算-CUDA开发】有关CUDA当中global memory如何实现合并访问跟内存对齐相关的问题
ps:这是英伟达二面面的一道相关CUDA的题目.<NVIDIA CUDA编程指南>第57页开始 在合并访问这里,不要跟shared memory的bank conflic ...
- Hive概述
HIVE是什么 开发调试麻烦 只能用java开发 需要对hadoop的底层及api比较了解才能开发复杂代码 HQL Hive是基于Hadoop的一个数据仓库工具.可以将结构化的数据 ...
- 快速排序的Python代码实现
选择一个数,和它后面的数比较,把比它小的放在它的左边,大的在右边(位置可能会因为左边元素的添加而右移) def quick_sort(arr): if arr==[]: return[] else: ...
- IDEA安装maven
1.先到maven的官网下载安装包:http://maven.apache.org/download.cgi 解压安装包 2.配置环境变量 新建变量名MAVEN_HOME 变量值 D:\Soft ...
- Prefix to Infix Conversion
Infix : An expression is called the Infix expression if the operator appears in between the operands ...
- 数值或者电话号码被EXCEL转成了科学计数法,用XSSFCell 如何读取
public static Map<String, Integer> readXls() throws IOException { //用来获取每一个小号重复多次,被多少账号用了.来平均 ...
- JXOI 2018滚粗记
--Update5.2 成绩出了,见后文 听说省选VAN写游记是传统,本蒟蒻也来发一篇吧. DAY 0 本来以为省选不在JKFZ举行的结果又是在JKFZ,本校作战感觉终究会是好一些吧,和jyh一起向教 ...