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(); // 设置通用的请求 ...
随机推荐
- Zabbix官方部署搭建
Zabbix在企业生产环境中是用的最广泛的服务器监控软件,其功能强大.配置简单.开源免费,是企业监控软件的首选. 一.Zabbix简介 zabbix是一个基于WEB界面的提供分布式系统监视以及网络 ...
- C语言递归之对称二叉树
题目描述 给定一个二叉树,检查它是否是镜像对称的. 示例 二叉树 [1,2,2,3,4,4,3] 是对称的. / \ / \ / \ [1,2,2,null,3,null,3] 则不是镜像对称的. / ...
- python脚本调用外部程序的若干种方式以及利弊
脚本执行外部程序的常用几种方式: # os.popen(path)# subprocess.run(cmd,shell=True)# subprocess.check_call(cmd,shell = ...
- Mac 操作小技巧
系统版本 MacOs Mojava # 快捷键篇: 1. 打开终端:command+空格,输入terminal:在终端页面,新建终端command + T 2. 打开文件夹:command + T 3 ...
- SQL server 维护计划中 “清除维护任务” 执行报错
SQL server 维护计划中 “清除维护任务” 执行报错,错误如下: 执行查询“EXECUTE master.dbo.xp_delete_file 0,N'',N'',N'2019...”失败,错 ...
- Codeforces 1148E Earth Wind and Fire
分析 必要条件: ① $\sum_{i=1}^{n} s_i = \sum_{i=1}^{n} t_i$ 预处理: 将 $s, t$ 从小到大排序. 尝试一 首尾匹配.例子 s = 2, 2, 4, ...
- strCmd.Format("delete FROM userTable where name = '%s'", name);
string.Format("select * from 数据库表 where 用户名='%s' and 密码='%s' ",m_1,m_2); 把[m_1]和[m_2]的值按照[ ...
- PAT A1009 Product of Polynomials(25)
课本AC代码 #include <cstdio> struct Poly { int exp;//指数 double cof; } poly[1001];//第一个多项式 double a ...
- Scala学习十——特质
一.本章要点 类可以实现任意数量的特质 特质可以要求实现它们的类具备特定的字段,方法或超类 和Java接口不同,Scala特质可以提供方法和字段实现 当你将多个特质叠加在一起时,顺序很重要——其方法先 ...
- join函数详解
定义:join() 方法用于把数组中的所有元素放入一个字符串. 语法 : ArrayObject.join(separator) separator 可选.指定要使用的分隔符.如果省略该参数,则使 ...