首页 > 代码库 > 微信主动推送文本消息C#
微信主动推送文本消息C#
1. 登陆,根据用户名和密码登陆到微信公众平台管理页面,获取token,模拟登陆请求地址:http://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN,
2. 登陆后,获取用户所有的信息,地址:https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token=,根据前面的token。
3. 发送消息,地址:https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN,这个只支持文本发送。fromfakeid是用户的id
说明,在获取所有用户信息的,用的是循环页数,设置最大的页数(1000000)配置
/// <summary>
/// 发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
lblMsg.Text = "";
Button1.Enabled = false;
if (TextBox1.Text.Trim() == "")
{
lblMsg.Text = "内容不能为空!";
return;
}
string username = TextBox2.Text.Trim();
string password = TextBox3.Text.Trim();
Wx_MoniLoGin wx = new Wx_MoniLoGin();
//登陆,获取Token.
bool flag = wx.ExecLogin(username, password);
if (flag)
{
//登陆成功后,去获取fakeid,所有的用户唯一标识
Dictionary<string, string> di = wx.SubscribeMP();
if (di != null)
{
_log.Info("总数:" + di.Count);
foreach (string key in di.Keys)
{
_log.Info("key 值是" + key.ToString());
bool re = false;
re = wx.SendMessage(TextBox1.Text.Trim(), key.ToString());
if (re)
{
lblMsg.Text += key.ToString() + "发送成功!";
}
else
{
lblMsg.Text += key.ToString() + "发送失败!";
}
}
}
}
Button1.Enabled = true;
}
/// <summary>
/// 执行登陆操作
/// </summary>
/// <param name="name"></param>
/// <param name="pass"></param>
/// <returns></returns>
public bool ExecLogin(string name, string pass)
{
bool result = false;
string password = GetMd5Str32(pass).ToUpper();
string padata = "http://www.mamicode.com/username=" + name + "&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); //新建一个WebRequest对象用来请求或者响应url
webRequest2.CookieContainer = cc; //保存cookie
webRequest2.Method = "POST"; //请求方式是POST
webRequest2.ContentType = "application/x-www-form-urlencoded"; //请求的内容格式为application/x-www-form-urlencoded
webRequest2.ContentLength = byteArray.Length;
webRequest2.Referer = "https://mp.weixin.qq.com/";
Stream newStream = webRequest2.GetRequestStream(); //返回用于将数据写入 Internet 资源的 Stream。
// 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来序列化
WeiXinRetInfo retinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeiXinRetInfo>(text2);
string token = string.Empty;
if (retinfo.Redirect_url.Length > 0)
{
token = retinfo.Redirect_url.Split(new char[] { ‘&‘ })[2].Split(new char[] { ‘=‘ })[1].ToString();//取得令牌
LoginInfo.LoginCookie = cc;
LoginInfo.CreateDate = DateTime.Now;
LoginInfo.Token = token;
result = true;
}
}
catch (Exception ex)
{
throw new Exception(ex.StackTrace);
}
return result;
}
/// <summary>
/// 获取所有用户fakeid
/// </summary>
/// <returns></returns>
public Dictionary<string, string> SubscribeMP()
{
try
{
Dictionary<string,string> di=new Dictionary<string,string>();
CookieContainer cookie = null;
string token = null;
cookie = LoginInfo.LoginCookie;//取得cookie
token = LoginInfo.Token;//取得token
int pageID = Util.TrimIntNull(ConfigurationManager.AppSettings["WXMaxPageID"].ToString());
for (int j = 0; j < pageID; j++)
{
string Url = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token=" + token + "&lang=zh_CN&pagesize=10&pageidx=" + j + "&type=0&groupid=0";
HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(Url);
webRequest2.CookieContainer = cookie;
webRequest2.ContentType = "text/html; charset=UTF-8";
webRequest2.Method = "GET";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
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";
HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
string text2 = sr2.ReadToEnd();
#region 解析字符串
string jsonString = "";
int start = text2.IndexOf("friendsList");
int end = text2.IndexOf(".contacts,");
if (start <= -1 || end <= -1)
{
//没有找到数据
break;
}
jsonString = text2.Substring(start, end - start);
if (jsonString != "")
{
int c = jsonString.IndexOf("contacts");
jsonString = jsonString.Substring(c, jsonString.Length - c - 1);
jsonString = "{\"" + jsonString;
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jo["contacts"] != null)
{
int k = (jo["contacts"]).AsEnumerable().Count();
if (k > 0)
{
for (int i = 0; i < k; i++)
{
string id = jo["contacts"][i]["id"].ToString();
string nick_name = jo["contacts"][i]["nick_name"].ToString();
//fackID1.Add(id);
di.Add(id, nick_name);
}
}
else
{
break;
}
}
}
else
{
break;
}
#endregion
}
return di;
}
catch (Exception ex)
{
_log.Error(ex);
}
return null;
}
/// <summary>
/// 发送文本消息
/// </summary>
/// <param name="Message"></param>
/// <param name="fakeid"></param>
/// <returns></returns>
public bool SendMessage(string Message, string fakeid)
{
bool result = false;
CookieContainer cookie = null;
string token = null;
cookie = LoginInfo.LoginCookie;//取得cookie
token = LoginInfo.Token;//取得token
string strMsg = System.Web.HttpUtility.UrlEncode(Message); //对传递过来的信息进行url编码
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";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
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();
_log.Info(text2);
if (text2.Contains("ok"))
{
result = true;
}
return result;
}
相关配置说明:
<!--微信查询用户信息的最大页数-->
<add key="WXMaxPageID" value="http://www.mamicode.com/1000000"/>
DemoWXPush完整项目下载地址
相关资料地址: