欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现微信公众号群发消息(解决一天只能发一次的限制)实例分享

程序员文章站 2023-12-20 21:18:58
总体思路: 1.首先必须要在微信公众平台上申请一个公众号。 2.然后进行模拟登陆。(由于我对http传输原理和编程不是特别懂,在模拟登陆的地方,不是特别清楚,希望有大神...

总体思路:

1.首先必须要在微信公众平台上申请一个公众号。

2.然后进行模拟登陆。(由于我对http传输原理和编程不是特别懂,在模拟登陆的地方,不是特别清楚,希望有大神指教)

3.模拟登陆后会获得一个token(令牌)和cookie。

4.因为模拟登陆后相当于就进入了微信公众平台,在这个里面就可以抓取到需要的数据,如公众好友的昵称,fakeid。其中的fakeid非常重要,因为传输数据必须要知道对方的fakeid。

5.知道对方的fakeid就可以进行数据的发送了。

这里是整个项目的源码下载:

不过里面还有一些小问题,希望有人继续修改和讨论!也有人说这样会被封号,所以请谨慎操作
讲一下我项目里面的主要内容
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<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)
        {
            throw new exception(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; }
    }

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

上一篇:

下一篇: