.Net HttpClient 模拟登录微信公众平台发送消息

时间:2023-03-09 04:10:01
.Net HttpClient 模拟登录微信公众平台发送消息

1.模拟登录

 public WeiXinRetInfo ExecLogin(string name, string pass)
{
CookieContainer cc = new CookieContainer();//接收缓存
WeiXinRetInfo retinfo = null; try
{
string password = Common.GetMd5Str32(pass).ToUpper(); HttpClientHandler hchandler = new HttpClientHandler()
{
CookieContainer = cc
}; HttpClient hclient = new HttpClient(hchandler);
hclient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36");
hclient.DefaultRequestHeaders.Add("Referer", "https://mp.weixin.qq.com");
//hclient.DefaultRequestHeaders.Add("Host", "mp.weixin.qq.com");
//hclient.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
//hclient.DefaultRequestHeaders.ExpectContinue = false; HttpContent hcontent = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"username",name},
{"pwd",password},
{"imgcode",""},
{"f","json"}
}); //https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN
HttpResponseMessage hresponse = hclient.PostAsync(Wx_Const.LOGIN_URL, hcontent).Result; hresponse.EnsureSuccessStatusCode(); string str_response = hresponse.Content.ReadAsStringAsync().Result; retinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeiXinRetInfo>(str_response); if (retinfo.base_resp.err_msg.Equals("ok"))
{
string token = retinfo.redirect_url.Split(new char[] { '&' })[].Split(new char[] { '=' })[].ToString();//取得令牌
lgin.CreateDate = DateTime.Now;
lgin.Token = token; string[] strCookies = (string[])hresponse.Headers.GetValues("Set-Cookie");
HttpClientCookies hcckis = new HttpClientCookies();
hcckis.AddCookie(strCookies);
lgin.hcckis = hcckis; lgin.LoginCookie = cc;
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("ExecLogin Exception[{0}]", ex.Message));
//throw;
} return retinfo;
}

2.新增图文消息(返回msgid),后续发送图文消息是用到

 /// <summary>
/// 新增图文消息
/// </summary>
/// <returns></returns>
public CreateMsgRs AddWeixinImgTextMsg()
{
string str_url_add_appmsg = string.Format("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=10&token={0}&lang=zh_CN", this.lgif.Token); //https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=10&token={0}&lang=zh_CN HttpClientHandler httpClientHandler = new HttpClientHandler()
{
CookieContainer = this.lgif.LoginCookie,
}; HttpClient client = new HttpClient(httpClientHandler); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); client.DefaultRequestHeaders.Add("Origin", "https://mp.weixin.qq.com"); client.DefaultRequestHeaders.Add("Referer", string.Format("https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10&lang=zh_CN&token={0}", this.lgif.Token));
//
//client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); //client.DefaultRequestHeaders.ty string fileid0 = ""; UploadImgRs uploadImgRs = AddImg(); if (uploadImgRs.base_resp.ErrMsg.Equals("ok"))
{
fileid0 = uploadImgRs.content;
} HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"token",this.lgif.Token},
{"lang","zh_CN"},
{"f","json"},
{"ajax",""},
{"random","0.9338385944720358"},
{"AppMsgId",""},
{"count",""},
{"title0","张静初出演电影版《三体》 获小说作者肯定"},
{"content0","2015年,被媒体称为中国“科幻元年”,多部科幻片启动了拍摄计划,《三体》当然是最受瞩目的,宣布的开机消息如是说“影片由小说原作者刘慈欣出任监制、游族影业CEO孔二狗担任总制片人、新锐导演张番番历经三年苦心筹备出任影片导演,台前众多国内实力派艺人担纲出演,幕后则由国际团队承担起拍摄、特效等重任,力求将本片打造成一部制作精良、高度还原的史诗级国产科幻片开山之作。”看着这依然模棱两可的说辞,网友们忧心忡忡,去年一片“求不渣”的请求声再起"},
{"digest0","2015年,被媒体称为中国“科幻元年”,多部科幻片启动了拍摄计划,《三体》当然是最受瞩目的"},
{"author0","李晓婕 仲敏"},
{"fileid0",fileid0},//图片文件ID
{"show_cover_pic0",""},
{"shortvideofileid0",""},
{"copyright_type0",""},
{"can_reward0",""},
{"reward_wording0",""},
{"sourceurl0",""},
{"vid",""},
//{"preusername",""}
});
HttpResponseMessage response = client.PostAsync(str_url_add_appmsg, content).Result;
//{"base_resp":{"ret":0,"err_msg":"ok"},"ret":"0","msg":"","appMsgId":204514536}
string s = response.Content.ReadAsStringAsync().Result; CreateMsgRs cmrs = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateMsgRs>(s); return cmrs;
}

3.获取图文列表

 /// <summary>
/// 获取图文消息列表
/// </summary>
/// <returns></returns>
public WeixinImgTextMsg GetImgTextList()
{
WeixinImgTextMsg wxImgText = null; string str_url_get_list = string.Format("https://mp.weixin.qq.com/cgi-bin/appmsg?type=10&action=list&begin=0&count=10&f=json&token={0}&lang=zh_CN&token={0}&lang=zh_CN&f=json&ajax=1&random={1}", this.lgif.Token, "0.18148761289194222"); HttpClientHandler httpClientHandler = new HttpClientHandler()
{
CookieContainer = this.lgif.LoginCookie,
}; HttpClient client = new HttpClient(httpClientHandler); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); HttpResponseMessage response = client.GetAsync(str_url_get_list).Result; string s = response.Content.ReadAsStringAsync().Result; wxImgText = Newtonsoft.Json.JsonConvert.DeserializeObject<WeixinImgTextMsg>(s); return wxImgText; }

4.获取订阅用户

 /// <summary>
/// 获取fakeid
/// </summary>
/// <returns></returns>
public ArrayList SubscribeMP()
{
string token = this.loginInfo.Token; string str_url_sendmsg = string.Format("https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&token={0}&lang=zh_CN", token); try
{
HttpClientHandler hchandler = new HttpClientHandler()
{
CookieContainer = this.loginInfo.LoginCookie
}; HttpClient hclient = new HttpClient(hchandler); hclient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); HttpResponseMessage response = hclient.GetAsync(str_url_sendmsg).Result; response.EnsureSuccessStatusCode(); string str_response_html = response.Content.ReadAsStringAsync().Result; MatchCollection mc; //由于此方法获取过来的信息是一个【html网页】所以此处使用了正则表达式,注意:(此正则表达式只是获取了fakeid的信息如果想获得一些其他的信息修改此处的正则表达式就可以了。)
Regex r = new Regex("\"id\"\\:\\d+,\"nick_name\""); //定义一个Regex对象实例
mc = r.Matches(str_response_html);
Int32 friendSum = mc.Count; //好友总数 string fackID = ""; ArrayList fackID1 = new ArrayList(); for (int i = ; i < friendSum; i++)
{
//"id":208989515,"nick_name"
fackID = mc[i].Value.Replace(",\"nick_name\"", "").Split(new char[] { ':' })[];
fackID = fackID.Replace("\"", "").Trim();
fackID1.Add(fackID);
} return fackID1;
}
catch (Exception ex)
{
throw new Exception(ex.StackTrace);
}
}

5.发送消息

 /// <summary>
/// 发送消息
/// </summary>
/// <param name="Message"></param>
/// <param name="fakeid"></param>
public SendMsgRs SendWxMessage(Wx_MsgType WxMsgType, string Message, string fakeid, string msgIdOrFileId)
{
SendMsgRs sendMsgRs = new SendMsgRs(); string token = this.loginInfo.Token; string str_url_sendmsg = string.Format("https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token={0}&lang=zh_CN", token); try
{
HttpClientHandler hchandler = new HttpClientHandler()
{
CookieContainer = this.loginInfo.LoginCookie
}; //HttpContent hcontent = new FormUrlEncodedContent(new Dictionary<string, string>()
//{
// {"type","1"},
// {"content",Message},
// {"error","false"},
// {"tofakeid",fakeid},
// {"token",token},
// {"ajax","1"},
//}); HttpContent hcontent = new FormUrlEncodedContent(this.GetMsgContentByMsgType(WxMsgType, msgIdOrFileId, Message, fakeid)); HttpClient hclient = new HttpClient(hchandler); hclient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36");
hclient.DefaultRequestHeaders.Add("Referer", string.Format("https://mp.weixin.qq.com/cgi-bin/singlemsgpage?token={0}&fromfakeid={1}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN", token, fakeid)); HttpResponseMessage response = hclient.PostAsync(str_url_sendmsg, hcontent).Result; response.EnsureSuccessStatusCode(); string s = response.Content.ReadAsStringAsync().Result; sendMsgRs = Newtonsoft.Json.JsonConvert.DeserializeObject<SendMsgRs>(s);
}
catch (Exception ex)
{
throw;
}
return sendMsgRs;
}

6.新增图文消息是,需要上传一张封面图片,返回fileid

 /// <summary>
///
/// </summary>
public UploadImgRs AddImg()
{
UploadImgRs uUploadImgRs = new UploadImgRs(); string str_rs = string.Empty; //ticket_id,ticket可从一下地址解析获取
//https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token=1985674500&lang=zh_CN
//https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=1437387422
//string ticket_id = "gh_982977c20410";
//string ticket = "62b2f4612b5b2f30583b517a21a1b76ffb8a7711"; string ticket_id = this.lgif.user_name;
string ticket = this.lgif.CurTicket; string str_url_uploadimg = string.Format("https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&writetype=doublewrite&groupid=1&ticket_id={0}&ticket={1}&token={2}&lang=zh_CN", ticket_id, ticket, this.lgif.Token); HttpClientHandler httpClientHandler = new HttpClientHandler()
{
CookieContainer = this.lgif.LoginCookie,
}; using (HttpClient client = new HttpClient(httpClientHandler))
{
client.DefaultRequestHeaders.Add("Connection", "keep-alive");
client.DefaultRequestHeaders.Add("Origin", "https://mp.weixin.qq.com");
client.DefaultRequestHeaders.Add("Referer", "https://mp.weixin.qq.com/cgi-bin/filepage?type=2&begin=0&count=12&t=media/img_list&token=" + this.lgif.Token + "&lang=zh_CN");
//client.DefaultRequestHeaders.Add("", "");
//client.DefaultRequestHeaders.Add("", "");
//client.DefaultRequestHeaders.Add("", "");
//client.DefaultRequestHeaders.Add("", "");
client.DefaultRequestHeaders.ExpectContinue = false; client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); using (MultipartFormDataContent content = new MultipartFormDataContent())
{
//*******************************************
//*******************************************
//!!!!!!!!!非常重要的地方,致命重要的设置!!!!!!!!!!
//*******************************************
//*******************************************
var boundaryValue = content.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");
boundaryValue.Value = boundaryValue.Value.Replace("\"", String.Empty);
//*******************************************
//*******************************************
//!!!!!!!!!非常重要的地方,致命重要的设置!!!!!!!!!!
//*******************************************
//******************************************* string str_file_path = Environment.CurrentDirectory + @"\ac345982b2b7d0a2f9d24887c9ef76094b369a95.jpg";
FileStream fileStream = File.OpenRead(str_file_path); StringContent sc_id = new StringContent("WU_FILE_0");
sc_id.Headers.Remove("Content-Type");
content.Add(sc_id, "\"id\"");
//content.Add(new StringContent("WU_FILE_0"), "\"id\""); StringContent sc_name = new StringContent("2b5906a9da28784e4a36d6db.jpg");
sc_name.Headers.Remove("Content-Type");
content.Add(sc_name, "\"name\"");
//content.Add(new StringContent("2b5906a9da28784e4a36d6db.jpg"), "\"name\""); StringContent sc_type = new StringContent("image/jpeg");
sc_type.Headers.Remove("Content-Type");
content.Add(sc_type, "\"type\"");
//content.Add(new StringContent("image/jpeg"), "\"type\""); StringContent sc_lastModifiedDate = new StringContent("Thu Mar 19 2015 17:11:58 GMT+0800 (中国标准时间)");
sc_lastModifiedDate.Headers.Remove("Content-Type");
content.Add(sc_lastModifiedDate, "\"lastModifiedDate\"");
//content.Add(new StringContent("Thu Mar 19 2015 17:11:58 GMT+0800 (中国标准时间)"), "\"lastModifiedDate\""); StringContent sc_size = new StringContent(Convert.ToInt32(fileStream.Length).ToString());
sc_size.Headers.Remove("Content-Type");
content.Add(sc_size, "\"size\"");
//content.Add(new StringContent(Convert.ToInt32(fileStream.Length).ToString()), "\"size\""); //***************************
var streamContent = new StreamContent(fileStream); //Content-Disposition: form-data; name="file"; filename="2b5906a9da28784e4a36d6db.jpg"
//Content-Type: image/jpeg
//Content-Disposition: form-data; name="file"; filename="2b5906a9da28784e4a36d6db.jpg"
//Content-Type: image/jpeg
streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(str_file_path) + "\"");
streamContent.Headers.Add("Content-Type", "image/jpeg"); content.Add(streamContent, "file", Path.GetFileName(str_file_path)); HttpResponseMessage response = client.PostAsync(str_url_uploadimg, content).Result; response.EnsureSuccessStatusCode(); string s = str_rs = response.Content.ReadAsStringAsync().Result; uUploadImgRs = Newtonsoft.Json.JsonConvert.DeserializeObject<UploadImgRs>(s);
} //返回结果
//{"base_resp":{"ret":0,"err_msg":"ok"},"location":"bizfile","type":"image","content":"204535433"}
} return uUploadImgRs;
}

以上代码仅是大概流程,又问提的可以留言我.