惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
O
OpenAI News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
Arctic Wolf
T
Tor Project blog
G
GRAHAM CLULEY
I
InfoQ
博客园_首页
IT之家
IT之家
The Register - Security
The Register - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
K
Kaspersky official blog
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
U
Unit 42
PCI Perspectives
PCI Perspectives
量子位
P
Palo Alto Networks Blog
S
Securelist
T
Troy Hunt's Blog
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security Affairs
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
博客园 - 聂微东
罗磊的独立博客
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
NISL@THU
NISL@THU
C
Cisco Blogs
T
Threatpost
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
T
The Exploit Database - CXSecurity.com
Cloudbric
Cloudbric
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security

博客园 - 王朝东

微信公众平台定制开发 音视频程序定制开发 联华ok卡自动并卡程序 企业邮件管理解决方案 电信自动并卡软件 c# tooltip 使用 基于(ICSharpCode.SharpZipLib.dll)的文件压缩方法,类文件 日期格式转换--年 月 周数 日 - 王朝东 不同数据库数据导入方法 Asp.net弹出层并且有遮罩层 OCX制作CAB Asp.net中用户自定义控件 ascx的使用 C#.net ListView item 拖动排序实现方法 对操作系统一些常用模块调用的简单总结 - 王朝东 - 博客园 水晶报表连续打印 好长时间没上了,呵呵!最近在学习Web Service,顺便写个简单的体会吧 使用sql语句实现跨数据库获取信息 asp.net中生成缩略图,并在图片上加入图片版板等信息 如何将数据导入word,excel,文本文件的类
asp.net 实现微信公众平台的主动推送信息
王朝东 · 2013-06-22 · via 博客园 - 王朝东

通过学习借鉴朋友的实现方法进行整理(微信公众帐号主动发送消息给用户,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;
}

该代码已经在项目中使用,欢迎大家进行交流。