一、首先需要将微信的openid与系统用户绑定。
在用户关注公众平台的时候,回复一个链接,要求用户绑定,可以设计如下消息进行回复,(openid最好进行加密处理,后者还需要用这个字段绑定fakeid)。
|
在bind.html页面将openid与系统的usercode进行绑定,这个绑定过程非常简单,这里不详叙述。
二、将openid与fakeid进行绑定
微信公众平台是一回一答的模式;但是在微信公众平台后台,可以向特定用户进行消息发送。我们利用这个机制使用代码去模拟这个过程来实现消息推送。
首先需要模拟登录:
|
获取fakeid
|
根据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的关系,所以可以根据usercode找到openid,又可以根据openid找到fakeid。使用下面代码进行推送:
|
可以写一个长期运行的windows服务用于建立fakeid和openid的关系,这里不再详诉。
