/// <summary> /// 开始初始化所有关键内容 /// </summary> private void Init() { try { string webwxinitUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxinit?r={0}pass_ticket={1}", Utils.Get_r(), passTicket); JObject postjson = JObject.FromObject(new { BaseRequest = baseRequest }); InitResponse initMsg = httpClient.PostJson <InitResponse>(webwxinitUrl, postjson); if (initMsg.BaseResponse.Ret != 0) { throw new Exception("程序初始化失败"); } //初始化2次,官网也是初始化2次,这样貌似比较稳定 httpClient.PostJson <InitResponse>(webwxinitUrl, postjson); user = initMsg.User; mpSubscribeMsgList = initMsg.MPSubscribeMsgList; syncKey = initMsg.SyncKey; //初始化的时候会返回一个最近联系人列表,但是主要还是以第一次sync获得的最近联系人为准。 asyncOperation.Post( new SendOrPostCallback((list) => { BatchGetContactComplete?.Invoke(this, new TEventArgs <List <Contact> >((List <Contact>)list)); }), initMsg.ContactList); asyncOperation.Post( new SendOrPostCallback((obj) => { LoginComplete?.Invoke(this, new TEventArgs <User>((User)obj)); }), user); } catch (Exception ex) { FileLog.Exception("Init", ex); asyncOperation.Post( new SendOrPostCallback((obj) => { ExceptionCatched?.Invoke(this, new TEventArgs <Exception>((Exception)obj)); }), ex); //throw ex; } }
/// <summary> /// 开始轮询检测是否有新消息 /// </summary> private void Sync() { while (syncPolling) { try { string syncCheckUrl = string.Format(pushHost + "/cgi-bin/mmwebwx-bin/synccheck?r={0}&skey={1}&sid={2}&uin={3}&deviceid={4}&synckey={5}&_={6}", Utils.GetJavaTimeStamp(), baseRequest.Skey, baseRequest.Sid, baseRequest.Uin, baseRequest.DeviceID, syncKey.ToString(), syncKey.Step); string syncCheckResult = httpClient.GetString(syncCheckUrl); if (!syncPolling) { return; } MatchCollection matchCollection = Regex.Matches(syncCheckResult, @"\d+"); string retcode = matchCollection[0].Value; string selector = matchCollection[1].Value; Utils.Debug("retcode:" + retcode + " selector:" + selector); switch (retcode) { case "0": if (selector != "0") { //有新消息,拉取信息。 SyncRequest syncRequest = new SyncRequest(); syncRequest.BaseRequest = baseRequest; syncRequest.SyncKey = syncKey; syncRequest.rr = Utils.Get_r(); string syncUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsync?sid={0}&skey={1}&pass_ticket={2}", baseRequest.Sid, baseRequest.Skey, passTicket); SyncResponse syncResponse = httpClient.PostJson <SyncResponse>(syncUrl, syncRequest); if (!syncPolling) { return; } else { syncKey = syncResponse.SyncKey; //只要不是0,就是有消息,有消息我们处理就行了,不管selector是几 if (syncResponse.AddMsgCount == 0 && syncResponse.DelContactCount == 0 && syncResponse.ModContactCount == 0 && syncResponse.ModChatRoomMemberCount == 0) { //会有这么一种情况,selector=2,但是没有任何消息体,这样会导致持续快速的空交互 //除非下次有新消息,或者主动点击手机触发消息 //为了防止这种情况,做个5秒停顿。 Thread.Sleep(5000); } else { if (syncResponse.AddMsgList.Count > 0) { asyncOperation.Post( new SendOrPostCallback((obj) => { ReceiveMsg?.Invoke(this, new TEventArgs <List <AddMsg> >((List <AddMsg>)obj)); }), syncResponse.AddMsgList); } if (syncResponse.ModContactCount > 0) { asyncOperation.Post( new SendOrPostCallback((obj) => { ModContactListComplete?.Invoke(this, new TEventArgs <List <ModContactItem> >((List <ModContactItem>)obj)); }), syncResponse.ModContactList); } if (syncResponse.DelContactCount > 0) { asyncOperation.Post( new SendOrPostCallback((obj) => { DelContactListComplete?.Invoke(this, new TEventArgs <List <DelContactItem> >((List <DelContactItem>)obj)); }), syncResponse.DelContactList); } if (syncResponse.ModChatRoomMemberCount > 0) { //待分析,这个消息基本没有 } } } } break; case "1100": //登出了微信,很可能是wx.qq.com和wx2.qq.com调用接口不一致导致的,注意登陆时候的跳转地址 Close(); asyncOperation.Post( new SendOrPostCallback((obj) => { LogoutComplete?.Invoke(this, new TEventArgs <User>((User)obj)); }), user); break; case "1101": Close(); asyncOperation.Post( new SendOrPostCallback((obj) => { LogoutComplete?.Invoke(this, new TEventArgs <User>((User)obj)); }), user); throw new Exception("1101可能其他地方登录/登出了 WEB 版微信,请检查手机端已登出WEB微信,然后稍后再试"); break; case "1102": Close(); asyncOperation.Post( new SendOrPostCallback((obj) => { LogoutComplete?.Invoke(this, new TEventArgs <User>((User)obj)); }), user); throw new Exception("1102被强制登出(很可能cookie冲突),请检查手机端已登出WEB微信,然后稍后再试"); break; default: //有其他任何异常,取消轮询 throw new Exception("轮询结果异常,停止轮询:" + syncCheckResult); break; } Thread.Sleep(1000); } catch (Exception ex) { FileLog.Exception("Init", ex); asyncOperation.Post( new SendOrPostCallback((obj) => { ExceptionCatched?.Invoke(this, new TEventArgs <Exception>((Exception)obj)); }), ex); } } }
/// <summary> /// 检测手机是否扫码 /// </summary> private void CheckSacnLogin() { try { byte[] userAvatar = null; ScanState scanState = ScanState.UnKnown; while (syncPolling && (scanState != ScanState.Login)) { string timespan = Utils.GetTimeStamp(); string loginUrl = string.Format("https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=0&r={1}&_={2}", uuid, Utils.Get_r(), Utils.GetTimeStamp()); //采用长轮询的方式,25秒返内回一次检测数据。 string checkResult = httpClient.GetString(loginUrl); Utils.Debug("CheckSacnLogin " + checkResult); if (checkResult.IndexOf("window.code=408;") != -1) { scanState = ScanState.Timeout; } else if (checkResult.IndexOf("window.code=201;") != -1) { scanState = ScanState.Scan; //有些号没有头像就跳过这个步骤 if (checkResult.IndexOf("window.userAvatar") != -1) { //扫码返回的头像是base64格式,需要转化 string subStr = "window.code=201;window.userAvatar = 'data:img/jpg;base64,"; string base64UserAvatar = checkResult.Substring(subStr.Length, checkResult.Length - subStr.Length - 2); byte[] arr = Convert.FromBase64String(base64UserAvatar); userAvatar = arr; asyncOperation.Post( new SendOrPostCallback((obj) => { CheckScanComplete?.Invoke(this, new TEventArgs <byte[]>((byte[])obj)); }), userAvatar); } } else if (checkResult.IndexOf("window.code=200;") != -1) { scanState = ScanState.Login; string subStr = "window.code=200;\nwindow.redirect_uri=\""; cookieRedirectUri = checkResult.Substring(subStr.Length, checkResult.Length - subStr.Length - 2); //跳转登录页获取cookie,并且获取关键参数,根据跳转地址,获相应提交地址 string cookieRedirectResult = httpClient.LoginString(cookieRedirectUri); if (cookieRedirectUri.StartsWith("https://wx2.qq.com")) { host = "https://wx2.qq.com"; pushHost = "https://webpush.wx2.qq.com"; uploadHost = "https://file.wx2.qq.com"; } else if (cookieRedirectUri.StartsWith("https://wx8.qq.com")) { host = "https://wx8.qq.com"; pushHost = "https://webpush.wx8.qq.com"; uploadHost = "https://file.wx8.qq.com"; } else if (cookieRedirectUri.StartsWith("https://web2.wechat.com")) { host = "https://web2.wechat.com"; pushHost = "https://webpush.web2.wechat.com"; uploadHost = "https://file.web2.wechat.com"; } else if (cookieRedirectUri.StartsWith("https://web.wechat.com")) { host = "https://web.wechat.com"; pushHost = "https://webpush.web.wechat.com"; uploadHost = "https://file.web.wechat.com"; } else { host = "https://wx.qq.com"; pushHost = "https://webpush.wx.qq.com"; uploadHost = "https://file.wx.qq.com"; } httpClient.Referer = host; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(cookieRedirectResult); //如果返回异常,则可能被暂封,无法登陆网页版 if (xmlDoc["error"]["ret"].InnerText != "0") { throw new Exception(xmlDoc["error"]["message"].InnerText); } else { baseRequest.Sid = xmlDoc["error"]["wxsid"].InnerText; baseRequest.Uin = Convert.ToInt64(xmlDoc["error"]["wxuin"].InnerText); baseRequest.Skey = xmlDoc["error"]["skey"].InnerText; passTicket = xmlDoc["error"]["pass_ticket"].InnerText; } } else if (checkResult.IndexOf("window.code=400;") != -1) { scanState = ScanState.Expires; GetLoginQrCode(); } else { scanState = ScanState.UnKnown; } Thread.Sleep(1000); } } catch (Exception ex) { FileLog.Exception("CheckSacnLogin", ex); asyncOperation.Post( new SendOrPostCallback((obj) => { ExceptionCatched?.Invoke(this, new TEventArgs <Exception>((Exception)obj)); }), ex); throw ex; } }