asp.net 实现微信公众平台的主动推送信息
通过学习借鉴朋友的实现方法进行整理(微信公众帐号主动发送消息给用户,asp.net版本)。
/// <summary>
/// MD5 32位加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static string GetMd5Str32(string str)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
char[] temp = str.ToCharArray();
byte[] buf = new byte[temp.Length];
for (int i = 0; i < temp.Length; i++)
{
buf[i] = (byte)temp[i];
}
byte[] data = md5Hasher.ComputeHash(buf);
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
public static bool ExecLogin()
{
bool result = false;
string password = GetMd5Str32(strMPPassword).ToUpper(); //注意转换为大写
string padata = "username=" + System.Web.HttpUtility.UrlEncode(strMPAccount) + "&pwd=" + password + "&imgcode=&f=json";
string url = "http://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN ";//请求登录的URL
try
{
CookieContainer cc = new CookieContainer();//接收缓存
byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 转化
HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url);
webRequest2.CookieContainer = cc;
webRequest2.Method = "POST";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.ContentLength = byteArray.Length;
Stream newStream = webRequest2.GetRequestStream();
// Send the data.
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
string text2 = sr2.ReadToEnd();
//此处用到了newtonsoft来序列化
SunnyInfo.Web.Class.WeiXinRetInfo retinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<SunnyInfo.Web.Class.WeiXinRetInfo>(text2);
string token = string.Empty;
if (retinfo.ErrMsg.Length > 0)
{
token = retinfo.ErrMsg.Split(new char[] { '&' })[2].Split(new char[] { '=' })[1].ToString();//取得令牌
LoginInfo.LoginCookie = cc;
LoginInfo.CreateDate = DateTime.Now;
LoginInfo.Token = token;
result = true;
}
}
catch (Exception ex)
{
Company.PubClass.WriteLog("Erro[" + DateTime.Now.ToString() + "]" + ex.StackTrace);
}
return result;
}
public static class LoginInfo
{
/// <summary>
/// 登录后得到的令牌
/// </summary>
public static string Token { get; set; }
/// <summary>
/// 登录后得到的cookie
/// </summary>
public static CookieContainer LoginCookie { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public static DateTime CreateDate { get; set; }
}
//发送信息
public static bool SendMessage(string Message, string fakeid)
{
bool result = false;
CookieContainer cookie = null;
string token = null;
//此处的作用是判断Cookie是否过期如果过期就重新获取,获取cookie的方法本人在.net 实现微信公众平台的主动推送信息中有源码。大家可以去看一下。这里就不再粘源代码了。
if (null == Class.WeiXinLogin.LoginInfo.LoginCookie || Class.WeiXinLogin.LoginInfo.CreateDate.AddMinutes(Convert.ToInt32(Class.WeiXinLogin.strLoingMinutes)) < DateTime.Now)
{
Class.WeiXinLogin.ExecLogin();
}
cookie = Class.WeiXinLogin.LoginInfo.LoginCookie;//取得cookie
token = Class.WeiXinLogin.LoginInfo.Token;//取得token
string strMsg = System.Web.HttpUtility.UrlEncode(Message);
string padate = "type=1&content=" + strMsg + "&error=false&tofakeid=" + fakeid + "&token=" + token + "&ajax=1";
string url = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN";
byte[] byteArray = Encoding.UTF8.GetBytes(padate); // 转化
HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url);
webRequest2.CookieContainer = cookie; //登录时得到的缓存
webRequest2.Referer = "https://mp.weixin.qq.com/cgi-bin/singlemsgpage?token=" + token + "&fromfakeid=" + fakeid + "&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN";
webRequest2.Method = "POST";
webRequest2.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.ContentLength = byteArray.Length;
Stream newStream = webRequest2.GetRequestStream();
// Send the data.
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
string text2 = sr2.ReadToEnd();
if (text2.Contains("ok"))
{
result = true;
}
return result;
}
该代码已经在项目中使用,欢迎大家进行交流。
asp.net 实现微信公众平台的主动推送信息的更多相关文章
- ASP.NET 微信公众平台模板消息推送功能完整开发
最近公众平台的用户提出了新需求,他们希望当收到新的邮件或者日程的时候,公众平台能主动推送一条提醒给用户.看了看平台提供的接口,似乎只有[模板消息]能尽量满足这一需求,但不得不说微信提供的实例太少,而且 ...
- PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制
2013年10月06日最新整理. PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制 微信公共平台消息主动推送接口一直是腾讯的私用接口,相信很多朋友都非常想要用到这个功能. 通过学习 ...
- C# asp.net 搭建微信公众平台(可实现关注消息与消息自动回复)的代码以及我所遇到的问题
[引言] 利用asp.net搭建微信公众平台的案例并不多,微信官方给的案例是用PHP的,网上能找到的代码很多也是存在着这样那样的问题或者缺少部分方法,无法使用,下面是我依照官方文档写的基于.net 搭 ...
- [C#]asp.net开发微信公众平台----目录汇总-持续更新
1.[c#]asp.net微信公众平台开发(1)数据库设计 2.[c#]asp.net微信公众平台开发(2)多层架构框架搭建和入口实现 3.[c#]asp.net微信公众平台开发(3)微信消息封装及反 ...
- [c#]asp.net开发微信公众平台(8)微信9大高级接口,自定义菜单
前7篇把最基础的消息接收和回复全做完了, 也把高级接口的入口和分拆处理写好了空方法, 此篇接着介绍微信的9大高级接口, 并着重讲解其中的自定义菜单. 微信9大接口为: 1.语音识别接口 2.客服接 ...
- [c#]asp.net开发微信公众平台(7)前6篇的整体框架demo源码
这里给出的demo是具备整体框架的微信公众平台源码, 所谓demo就是拿过去就可以直接演示使用的东西, 当然不会具备非常详细的具体到业务层面.数据层面的东西, 每个人都可以在此基础上自由发挥, 只 ...
- [c#]asp.net开发微信公众平台(6)阶段总结、服务搭建、接入
经过前5篇,跟着一步步来的话,任何人都能搭建好一个能处理各种微信消息的框架了,总结一下最容易忽略的问题: 1.文本消息中可以使用换行符\n : 2.微信发来的消息中带的那个长整型的时间,我们完全 ...
- [c#]asp.net开发微信公众平台(5)微信图文消息
上篇已经成功响应了关注事件,也实现了文本消息的发送,这篇开始图文消息处理, 微信中最常用的消息类型就是图文消息了,因为它图文并茂,最能表达信息. 图文消息在微信中的接口定义如下: <xml> ...
- asp.net开发微信公众平台----目录汇总-持续更新
1.[c#]asp.net微信公众平台开发(1)数据库设计 2.[c#]asp.net微信公众平台开发(2)多层架构框架搭建和入口实现 3.[c#]asp.net微信公众平台开发(3)微信消息封装及反 ...
随机推荐
- 结合Git实现Mysql差异备份,可用于生产环境
埋头苦干多年一直没写过文章,今天突发狂想,为LNMP阵营贡献一些力量.就从平时工作过程中的心得和一些技巧分享出来.今天就猿们最熟悉的Mysql开始宅鸟的开篇博客文章.欢迎猿们拍砖.转载. 注意:宅鸟的 ...
- 标准的CSS盒子模型?与低版本IE的盒子模型有什么不同的?
CSS盒子模型:由四个属性组成的外边距(margin).内边距(padding).边界(border).内容区(width和height); 标准的CSS盒子模型和低端IE CSS盒子模型不同:宽高不 ...
- jQuery在HTML文档加载完毕后自动执行某个事件;
原来onchange=“fucntionname(parms)”: <select name="country" id="selCountries_{$sn}&qu ...
- php 提示Warning: mysql_fetch_array() expects
我的高度代码如下 include("conn.php"); if(!empty($_GET['id'])){ $sql="select * from ne ...
- 随机获取Mysql数据表的一条或多条记录
随机获得Mysql数据表的一条或多条记录有很多方法,下面我就以users(userId,userName,password......)表(有一百多万条记录)为例,对比讲解下几个方法效率问题: sel ...
- Ubuntu 12.04 添加新用户并启用root登录
启动root sudo passwd 输入密码 输入root 新密码并重复 su 切换root 添加用户比如hduser 修改密码hduserchmod u+w /etc/sudoersvi sudo ...
- i++与++i的误解
javap -c xx.class {i=0i=i++}0: bipush 02: istore_1 stack ->var13: iload_1 var1->stack4: iinc 1 ...
- Android UI效果实现——Activity滑动退出效果
更新说明: 1.在QQ网友北京-旭的提醒下,在SlideFrame的initilize方法中添加了focusable.focusableInTouch.clickable的状态设置,否则会导致部分情况 ...
- windows32位下安装mongodb
下载mongodb:http://downloads.mongodb.org/win32/mongodb-win32-i386-2.4.5.zip 给mongodb指定一个数据存放路径:这里我们放在m ...
- oracle 各种问题排查
一.ORA-00257 ORA-00257归档日志写满,最简单方法.可以更改归档的大小. 二.job不自动运行解决方法 http://www.cnblogs.com/xbding/p/5861443. ...