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(); // 设置通用的请求 ...
随机推荐
- TensorFlow2.0(12):模型保存与序列化
.caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...
- svn clearup svn cleanup failed–previous operation has not finished; run cleanup if it was int错误的解决办法
今天svn提交,出现异常:svn cleanup failed–previous operation has not finished; run cleanup if it was interrupt ...
- 【Web网站服务器开发】apache和tomcat 阿帕奇和汤姆猫
经常在用apache和tomcat等这些服务器,可是总感觉还是不清楚他们之间有什么关系,在用tomcat的时候总出现apache,总感到迷惑,到底谁是主谁是次,因此特意在网上查询了一些这方面的资料,总 ...
- mysq的慢查询日志
MySQL 慢查询日志是排查问题 SQL 语句,以及检查当前 MySQL 性能的一个重要功能. 查看是否开启慢查询功能: mysql> show variables like 'slow_que ...
- Excel小技巧(生成数字篇)
1. 自动生成1-1000: =ROW() 2.随机生成 1-100 : =RANDBETWEEN(1,100) // 若要包含小数点n位,就把(MIN,MAX)改成 (MIN*10^n,MAX*10 ...
- 红米K20PRO解锁Bootloader权限并刷入recovery
手机里反正没什么东西了,聊天记录啊好像也没很重要得了,索性全部清除,刷机玩玩. 把稳定版刷成第三方开发版,这样又有时间去折腾root权限,面具和xposed的各种插件了,嘿嘿. 解锁小米手机 我的账号 ...
- Spring4学习回顾之路08- FactoryBean配置Bean
建立Student.java package com.lql.srping04; /** * @author: lql * @date: 2019.10.28 * Description: */ pu ...
- uname、hostname命令
一.uname:显示系统信息. 语法: uname [OPTION] ... 描述 打印某些系统信息. 没有选项,与-s相同. -a,--all ...
- Docker——入门
虚拟化最大区别:虚拟化技术元件,资源申请调度到其他硬件服务器: Docker是一个开源得应用容器引擎,让开发者可以打包他们得应用以及依赖包到一共可移植得容器中,然后发布到任何流行得linux机器上,也 ...
- 怎样修改输入框 placehoder 提示文本的颜色?
1. 在这个问题上, 不同浏览器的设置方法有所差异, 可以写成下面这种形式. ::-webkit-input-placeholder { /* WebKit browsers */ color: #9 ...