C # Implement Message sending in WeChat public account group (solve the limit that messages can only be sent once a day)

Source: Internet
Author: User

Overall Thinking: 1. First, you must apply for a public account on the public platform.

2. Simulate login. (Because I do not know the http Transmission Principle and programming very well, I am not very clear about the simulated login. I hope you can give me some advice)

3. After simulated login, a token and cookie will be obtained.

4. After simulated login, it is equivalent to entering the public platform, where you can capture the required data, such as the nickname of a public friend and fakeId. Fakeid is very important because the data transmitted must know the fakeid of the other party.

5. You can send data by knowing the fakeid of the other party.

The code for my entire project is downloaded.

However, there are still some minor issues. I hope someone can continue to modify and discuss them! Some people also say that this will be blocked, so proceed with caution.

Let's talk about the main content of my project.

1. The WeiXinLogin. cs class is used to execute the login function.
// Perform MD5 encryption on the password


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 ();
}

// Perform the login operation
Public static bool ExecLogin (string name, string pass)
{
Bool result = false;
String password = GetMd5Str32 (pass). ToUpper ();
String padata = "username =" + name + "& pwd =" + password + "& imgcode = & f = json ";
String url = "http://mp.weixin.qq.com/cgi-bin/login? Lang = zh_CN "; // the login request URL
Try
{
CookieContainer cc = new CookieContainer (); // receives the cache
Byte [] byteArray = Encoding. UTF8.GetBytes (padata); // convert
HttpWebRequest webRequest2 = (HttpWebRequest) WebRequest. Create (url); // Create a new WebRequest object to request or respond to a url
WebRequest2.CookieContainer = cc; // Save the cookie
WebRequest2.Method = "POST"; // The Request Method is POST.
WebRequest2.ContentType = "application/x-www-form-urlencoded"; // The request content is in the format of application/x-www-form-urlencoded
WebRequest2.ContentLength = byteArray. Length;
Stream newStream = webRequest2.GetRequestStream (); // return the Stream used to write data to Internet resources.
// Send the data.
NewStream. Write (byteArray, 0, byteArray. Length); // Write Parameters
NewStream. Close ();
HttpWebResponse response2 = (HttpWebResponse) webRequest2.GetResponse ();
StreamReader sr2 = new StreamReader (response2.GetResponseStream (), Encoding. Default );
String text2 = sr2.ReadToEnd ();


// Newtonsoft is used for serialization.
WeiXinRetInfo retinfo = Newtonsoft. Json. JsonConvert. DeserializeObject <WeiXinRetInfo> (text2 );
String token = string. Empty;
If (retinfo. ErrMsg. Length> 0)
{
Token = retinfo. errMsg. split (new char [] {'&'}) [2]. split (new char [] {'='}) [1]. toString (); // get the token
LoginInfo. LoginCookie = cc;
LoginInfo. CreateDate = DateTime. Now;
LoginInfo. Token = token;
Result = true;
}
}
Catch (Exception ex)
{

Throw new Exception (ex. StackTrace );
}
Return result;
}


Public static class LoginInfo
{
/// <Summary>
/// Token obtained after Logon
/// </Summary>
Public static string Token {get; set ;}
/// <Summary>
/// Cookie obtained after Logon
/// </Summary>
Public static CookieContainer LoginCookie {get; set ;}
/// <Summary>
/// Creation Time
/// </Summary>
Public static DateTime CreateDate {get; set ;}


}

 

 

2. implement data transmission in the WeiXin. cs class
Public static bool SendMessage (string Message, string fakeid)
{
Bool result = false;
CookieContainer cookie = null;
String token = null;
Cookie = WeiXinLogin. LoginInfo. LoginCookie; // obtain the cookie
Token = WeiXinLogin. LoginInfo. Token; // get token


String strMsg = System. Web. HttpUtility. UrlEncode (Message); // url encode the transmitted information
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); // convert


HttpWebRequest webRequest2 = (HttpWebRequest) WebRequest. Create (url );


WebRequest2.CookieContainer = cookie; // cache obtained upon Logon


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); // Write Parameters


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;
}

 

 

 

 

3. In SendMessage. aspx. cs, the fakeid is obtained.
Public static ArrayList SubscribeMP ()
{

Try
{
CookieContainer cookie = null;
String token = null;



Cookie = WeiXinLogin. LoginInfo. LoginCookie; // obtain the cookie
Token = WeiXinLogin. LoginInfo. Token; // get token


/* Obtain the url of user information. Here are several parameters for your reference. 1. The token parameter is the top token parameter. 2. pagesize. this parameter is the number of records displayed on each page.


3. pageid is the current page number, and 4. groupid is the group id of the user group on the public platform. Of course, this is also my guess */
String Url = "https://mp.weixin.qq.com/cgi-bin/contactmanagepage? T = wxm-friend & token = "+ token +" & lang = zh_CN & pagesize = 10 & pageidx = 0 & type = 0 & groupid = 0 ";
HttpWebRequest webRequest2 = (HttpWebRequest) WebRequest. Create (Url );
WebRequest2.CookieContainer = cookie;
WebRequest2.ContentType = "text/html; charset = UTF-8 ";
WebRequest2.Method = "GET ";
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. Default );
String text2 = sr2.ReadToEnd ();
MatchCollection mc;


// Because the information obtained by this method is an html webpage, a regular expression is used here, note: (this regular expression only obtains fakeid information. If you want to obtain other information, modify the regular expression here .)
Regex r = new Regex ("\" fakeId \ "\ s \: \ s \" \ d + \ ""); // defines a Regex object instance
Mc = r. Matches (text2 );
Int32 friendSum = mc. Count; // total number of friends


String fackID = "";


ArrayList fackID1 = new ArrayList ();


For (int I = 0; I <friendSum; I ++)
{
FackID = mc [I]. Value. Split (new char [] {':'}) [1];
FackID = fackID. Replace ("\" "," "). Trim ();
FackID1.Add (fackID );
}


Return fackID1;
}
Catch (Exception ex)
{
Throw new Exception (ex. StackTrace );
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.