通过学习借鉴朋友的实现方法进行整理(微信公众帐号主动发送消息给用户,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 实现微信公众平台的主动推送信息的更多相关文章

  1. ASP.NET 微信公众平台模板消息推送功能完整开发

    最近公众平台的用户提出了新需求,他们希望当收到新的邮件或者日程的时候,公众平台能主动推送一条提醒给用户.看了看平台提供的接口,似乎只有[模板消息]能尽量满足这一需求,但不得不说微信提供的实例太少,而且 ...

  2. PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制

    2013年10月06日最新整理. PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制 微信公共平台消息主动推送接口一直是腾讯的私用接口,相信很多朋友都非常想要用到这个功能. 通过学习 ...

  3. C# asp.net 搭建微信公众平台(可实现关注消息与消息自动回复)的代码以及我所遇到的问题

    [引言] 利用asp.net搭建微信公众平台的案例并不多,微信官方给的案例是用PHP的,网上能找到的代码很多也是存在着这样那样的问题或者缺少部分方法,无法使用,下面是我依照官方文档写的基于.net 搭 ...

  4. [C#]asp.net开发微信公众平台----目录汇总-持续更新

    1.[c#]asp.net微信公众平台开发(1)数据库设计 2.[c#]asp.net微信公众平台开发(2)多层架构框架搭建和入口实现 3.[c#]asp.net微信公众平台开发(3)微信消息封装及反 ...

  5. [c#]asp.net开发微信公众平台(8)微信9大高级接口,自定义菜单

    前7篇把最基础的消息接收和回复全做完了,  也把高级接口的入口和分拆处理写好了空方法,  此篇接着介绍微信的9大高级接口, 并着重讲解其中的自定义菜单. 微信9大接口为: 1.语音识别接口 2.客服接 ...

  6. [c#]asp.net开发微信公众平台(7)前6篇的整体框架demo源码

    这里给出的demo是具备整体框架的微信公众平台源码, 所谓demo就是拿过去就可以直接演示使用的东西,  当然不会具备非常详细的具体到业务层面.数据层面的东西, 每个人都可以在此基础上自由发挥,  只 ...

  7. [c#]asp.net开发微信公众平台(6)阶段总结、服务搭建、接入

    经过前5篇,跟着一步步来的话,任何人都能搭建好一个能处理各种微信消息的框架了,总结一下最容易忽略的问题: 1.文本消息中可以使用换行符\n    : 2.微信发来的消息中带的那个长整型的时间,我们完全 ...

  8. [c#]asp.net开发微信公众平台(5)微信图文消息

    上篇已经成功响应了关注事件,也实现了文本消息的发送,这篇开始图文消息处理, 微信中最常用的消息类型就是图文消息了,因为它图文并茂,最能表达信息. 图文消息在微信中的接口定义如下: <xml> ...

  9. asp.net开发微信公众平台----目录汇总-持续更新

    1.[c#]asp.net微信公众平台开发(1)数据库设计 2.[c#]asp.net微信公众平台开发(2)多层架构框架搭建和入口实现 3.[c#]asp.net微信公众平台开发(3)微信消息封装及反 ...

随机推荐

  1. nth-of-type和nth-child的区别

    看CSS3时发现了一个nth-of-type选择器,发现平时基本没见过用,就研究了一下,w3c是这样说明的: :nth-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素的每个元素 ...

  2. vue.js插件使用(01) vue-resource

    本文的主要内容如下: 介绍vue-resource的特点 介绍vue-resource的基本使用方法 基于this.$http的增删查改示例 基于this.$resource的增删查改示例 基于int ...

  3. BM串匹配算法

    串匹配算法最常用的情形是从一篇文档中查找指定文本.需要查找的文本叫做模式串,需要从中查找模式串的串暂且叫做查找串吧. BM算法好后缀规则 公式: 对于长度为m的模式串P,在i处失配时,模式串向前滑动的 ...

  4. windows服务器记录3389远程桌面IP策略

    以下代码复制存成一个批处理文件后双击即可! 3389IP日志路径是C:\WINDOWS\PDPLOG\RDPlog.txt  代码: MD C:\WINDOWS\PDPLOG  " /f  ...

  5. mysql存储引擎(mysql学习六)

    存储引擎 现在只有InnoDB支持外键 上接着学习笔记五 class表中有外键,所以不能修改存储引擎 表类型   默认的服务器表类型,通过my.ini可以配置    Default-storage-e ...

  6. 清理文件默认打开方式.bat

    @echo offsetlocal enabledelayedexpansionset "ext=%~x1":loopif defined ext set "ext=!e ...

  7. C++primer 阅读点滴记录(二)

      智能指针(smart point)       除了增加功能外,其行为像普通指针一样. 一般通过使用计数(use count)或引用计数(reference count)实现智能指针,防止出现指针 ...

  8. PHP取当前页面完整URL地址

    #测试网址: http://localhost/blog/testurl.php?id=5 //获取域名或主机地址 echo $_SERVER['HTTP_HOST']."<br> ...

  9. SQL Server 基础:Case两种用法

    测试数据 1).等值判断->相当于switch case select S#,C#,C#=( case C# when 1 then '语文' when 2 then '数学' when 3 t ...

  10. 如何让dapper支持oracle游标呢?

    Dapper是一个轻型的ORM类.它有啥优点.缺点相信很多朋友都知道了,园里也有很多朋友都有相关介绍,这里就不多废话. 如果玩过Oracle都知道,存储过程基本都是通过游标返回数据的,但是dapper ...