最近研究微信公眾平臺(tái),這里整理了一下向特定用戶推送消息的思路 一、首先需要將微信的openid與系統(tǒng)用戶綁定。 在用戶關(guān)注公眾平臺(tái)的時(shí)候,回復(fù)一個(gè)鏈接,要求用戶綁定,可以設(shè)計(jì)如下消息進(jìn)行回復(fù),(openid最好進(jìn)行加密處理,后者還需要用這個(gè)字段綁定fakeid)。 歡迎關(guān)注有問必答平臺(tái),<a href='http://myweixin123./bind.html?openid=@openid'>點(diǎn)擊此處進(jìn)行用戶綁定</a>! 在bind.html頁(yè)面將openid與系統(tǒng)的usercode進(jìn)行綁定,這個(gè)綁定過程非常簡(jiǎn)單,這里不詳敘述。 二、將openid與fakeid進(jìn)行綁定 微信公眾平臺(tái)是一回一答的模式;但是在微信公眾平臺(tái)后臺(tái),可以向特定用戶進(jìn)行消息發(fā)送。我們利用這個(gè)機(jī)制使用代碼去模擬這個(gè)過程來實(shí)現(xiàn)消息推送。 首先需要模擬登錄: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using System.Net; using System.IO; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; /// <summary> ///WeiXinLogin 的摘要說明 /// </summary> public class WeiXinLogin { /// <summary> /// MD5 32位加密 /// </summary> /// <param name="str"></param> /// <returns></returns> 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 = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN ";//請(qǐng)求登錄的URL try { CookieContainer cc = new CookieContainer();//接收緩存 byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 轉(zhuǎn)化 HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url); //新建一個(gè)WebRequest對(duì)象用來請(qǐng)求或者響應(yīng)url ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy(); webRequest2.CookieContainer = cc; //保存cookie webRequest2.Method = "POST"; //請(qǐng)求方式是POST webRequest2.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36"; webRequest2.Referer = "https://mp.weixin.qq.com/"; webRequest2.ContentType = "application/x-www-form-urlencoded"; //請(qǐng)求的內(nèi)容格式為application/x-www-form-urlencoded webRequest2.ContentLength = byteArray.Length; Stream newStream = webRequest2.GetRequestStream(); //返回用于將數(shù)據(jù)寫入 Internet 資源的 Stream。 // Send the data. newStream.Write(byteArray, 0, byteArray.Length); //寫入?yún)?shù) 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> /// 創(chuàng)建時(shí)間 /// </summary> public static DateTime CreateDate { get; set; } } internal class AcceptAllCertificatePolicy : ICertificatePolicy { public AcceptAllCertificatePolicy() { } public bool CheckValidationResult(ServicePoint sPoint, X509Certificate cert, WebRequest wRequest, int certProb) { // Always accept return true; } } } 獲取fakeid public static ArrayList SubscribeMP() { try { CookieContainer cookie = null; string token = null; cookie = WeiXinLogin.LoginInfo.LoginCookie;//取得cookie token = WeiXinLogin.LoginInfo.Token;//取得token /*獲取用戶信息的url,這里有幾個(gè)參數(shù)給大家講一下,1.token此參數(shù)為上面的token 2.pagesize此參數(shù)為每一頁(yè)顯示的記錄條數(shù) 3.pageid為當(dāng)前的頁(yè)數(shù),4.groupid為微信公眾平臺(tái)的用戶分組的組id,當(dāng)然這也是我的猜想不一定正確*/ string Url = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&token=" + token + "&lang=zh_CN"; 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; //由于此方法獲取過來的信息是一個(gè)html網(wǎng)頁(yè)所以此處使用了正則表達(dá)式,注意:(此正則表達(dá)式只是獲取了fakeid的信息如果想獲得一些其他的信息修改此處的正則表達(dá)式就可以了。) Regex r = new Regex("\"id\"\\:\\d+,\"nick_name\""); //定義一個(gè)Regex對(duì)象實(shí)例 mc = r.Matches(text2); Int32 friendSum = mc.Count; //好友總數(shù) string fackID = ""; ArrayList fackID1 = new ArrayList(); for (int i = 0; i < friendSum; i++) { //"id":208989515,"nick_name" fackID = mc[i].Value.Replace(",\"nick_name\"", "").Split(new char[] { ':' })[1]; fackID = fackID.Replace("\"", "").Trim(); fackID1.Add(fackID); } return fackID1; } catch (Exception ex) { throw new Exception(ex.StackTrace); } } 根據(jù)fakeid獲取openid public static string GetOpenidByFakeid(string fakeid) { try { CookieContainer cookie = null; string token = null; cookie = WeiXinLogin.LoginInfo.LoginCookie;//取得cookie token = WeiXinLogin.LoginInfo.Token;//取得token string Url = "https://mp.weixin.qq.com/cgi-bin/singlemsgpage?msgid=&source=&count=20&t=wxm-singlechat&fromfakeid=" + fakeid + "&token=" + token + "&lang=zh_CN"; 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.UTF8); string text2 = sr2.ReadToEnd(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(text2); var str = doc.GetElementbyId("json-msgList").InnerHtml; JArray messages = JArray.Parse(str); foreach (var message in messages) { string strContent = HttpUtility.HtmlDecode(message["content"].ToString()); Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""\s]?)(?<href>[^'""\s]*)\1[^>]*?>"); MatchCollection match = reg.Matches(strContent); var href = ""; foreach (Match m in match) { href = m.Groups["href"].Value; } var openid = GetUrlParamValue(href, "openid"); if (!string.IsNullOrEmpty(openid)) return openid; } return ""; } catch (Exception ex) { return ""; } }
由于之前有建立openid與usercode的關(guān)系,所以可以根據(jù)usercode找到openid,又可以根據(jù)openid找到fakeid。使用下面代碼進(jìn)行推送: 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); //對(duì)傳遞過來的信息進(jìn)行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); // 轉(zhuǎn)化 HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url); webRequest2.CookieContainer = cookie; //登錄時(shí)得到的緩存 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); //寫入?yún)?shù) 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; }
可以寫一個(gè)長(zhǎng)期運(yùn)行的windows服務(wù)用于建立fakeid和openid的關(guān)系,這里不再詳訴。
|
|