C#微信公衆番号の群発メッセージ(1日に1回しか送信できない制限を解決する)のインスタンス共有を実現

9532 ワード

全体的な考え方:
1.まず、微信の公衆プラットフォームで公衆番号を申請しなければならない.
2.その後、アナログログインを行います.(http伝送の原理やプログラミングがよく分からないので、模擬上陸の場所では、特にはっきりしていないので、大神さんに教えてもらいたいです)
3.シミュレーションログイン後にtoken(トークン)とクッキーが取得されます.
4.アナログログイン後、微信の公衆プラットフォームに入ったことに相当するため、この中で必要なデータ、例えば公衆の友达のニックネーム、fakeIdを捕まえることができます.その中のfakeidは非常に重要です.データを転送するには相手のfakeidを知らなければならないからです.
5.相手のfakeidを知っていればデータの送信ができる.
ここでは、プロジェクト全体のソースコードのダウンロードです.http://http://xiazai.jb51.net/201309/yuanma/webchat.rar
しかし、中にはいくつかの小さな問題があります.誰かが修正して討論し続けることを望んでいます.このように封印されるという人もいるので、慎重に操作して私のプロジェクトの主な内容を話してください.1.WeiXinLogin.cs類はログイン機能を実行するためのものです.
 
  
// MD5
 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(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 ";// 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;
            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(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)
        {
            throw new Exception(ex.StackTrace);
        }
        return result;
    }
    public static class LoginInfo
    {
        ///
        ///
        ///
       
        public static string Token { get; set; }
        ///
        /// cookie
        ///

        public static CookieContainer LoginCookie { get; set; }
        ///
        ///
        ///

        public static DateTime CreateDate { get; set; }
    }

2.WeiXin.csクラスでの送信データの実装
 
  
public static bool SendMessage(string Message, string fakeid)
    {
        bool result = false;
        CookieContainer cookie = null;
        string token = null;
        cookie = WeiXinLogin.LoginInfo.LoginCookie;// cookie
        token =  WeiXinLogin.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";
        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;
    }

3.SendMessage.aspx.csで主にfakeid取得を実現
 
  
public static ArrayList SubscribeMP()
    {
        try
        {
            CookieContainer cookie = null;
            string token = null;
            cookie = WeiXinLogin.LoginInfo.LoginCookie;// cookie
            token = WeiXinLogin.LoginInfo.Token;// token
            /* url, ,1.token token 2.pagesize
            3.pageid ,4.groupid id, */
            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;
            // html , :( fakeid 。)
             Regex r = new Regex("\"fakeId\"\\s\\:\\s\"\\d+\""); // Regex
            mc = r.Matches(text2);
            Int32 friendSum = mc.Count;          //
            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);
        }
    }