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

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

posted on 2013-06-22 16:32  王朝东  阅读(14403)  评论(8编辑  收藏  举报