static public bool Auth() { #if DEBUG return(true); #endif //if (hasBeenAuth) if (Properties.Settings.Default.openid == "" || Properties.Settings.Default.userNickname == "") { return(true); } else if (AuthExpiredTimeLeft > TimeSpan.Zero) { return(true); } else { CancellationTokenSource cts = new CancellationTokenSource(); bool networkException = false; DateTime n = UpdateAuth(cts.Token, out networkException); if (networkException) { //MessageBox.Show("获取授权失败,请检查网络是否连接!", // "获取授权失败", MessageBoxButtons.OK, MessageBoxIcon.Error); AutoCloseMessageBox.ShowMessage(-1, "获取授权失败,请检查网络是否连接!"); return(false); } else if (n.AddMinutes(20) > DateTime.Now) { TurnOnAuth(); return(true); } else { Task t = SendAuthRequestNotificationAsync(); AutoCloseMessageBox.ShowMessage(-1, "执行此操作需要微信绑定者进行授权!\n请按照公众号提示操作后重试!"); //MessageBox.Show("执行此操作需要微信绑定者点击公众号授权按钮进行授权!\n请在公众号菜单中点击授权按钮后重试!", // "操作未授权", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } }
private async Task SetQrcodeAsync(CancellationToken cancellationToken) { try { qrCodePictureBox.Cursor = Cursors.WaitCursor; HttpClientHandler handler = new HttpClientHandler() { UseProxy = false }; HttpClient client = new HttpClient(handler); JObject createUserObj = new JObject(); createUserObj["token"] = webToken; //createUserObj["uuid"] = "dummy-uuid"; //HttpResponseMessage msg = client.PostAsync(Properties.Settings.Default.createUserUrl, formContent).Result; HttpResponseMessage msg = await client.PostAsync(Properties.Settings.Default.createSceneUrl, new StringContent(createUserObj.ToString(), Encoding.UTF8, "application/json"), cancellationToken); msg.EnsureSuccessStatusCode(); string retStr = await msg.Content.ReadAsStringAsync(); JObject retObj = JObject.Parse(retStr); int userid = int.Parse(retObj["scene_id"].ToString()); string qrcodeCreateUrl = string.Format(Properties.Settings.Default.wechatCreateQrcodeUrl, retObj["access_token"]); JObject requestObj = new JObject(); requestObj["expire_seconds"] = 604800; requestObj["action_name"] = "QR_SCENE"; requestObj["action_info"] = new JObject(); requestObj["action_info"]["scene"] = new JObject(); requestObj["action_info"]["scene"]["scene_id"] = userid; string x = requestObj.ToString(); msg = await client.PostAsync(qrcodeCreateUrl, new StringContent(requestObj.ToString(), Encoding.UTF8, "application/json"), cancellationToken); retStr = await msg.Content.ReadAsStringAsync(); retObj = JObject.Parse(retStr); string ticket = retObj["ticket"].ToString(); string qrcodeUrl = retObj["url"].ToString(); //msg = await client.GetAsync(string.Format(Properties.Settings.Default.wechatGetQrcodeUrl, HttpUtility.UrlEncode(ticket)), cancellationToken); //msg.EnsureSuccessStatusCode(); //Stream img = await msg.Content.ReadAsStreamAsync(); //Bitmap bmp = new Bitmap(img); //generate qrcode myself to decrease the latency QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(qrcodeUrl, QRCodeGenerator.ECCLevel.Q); //直接从微信获取,防止本地生成发生错误 //qrCodePictureBox.ImageLocation = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket; qrCodePictureBox.Image = qrCode.GetGraphic(20); qrCodePictureBox.Cursor = Cursors.Default; //qrCodePictureBox.Image = bmp; //qrCodePictureBox.ImageLocation = string.Format(Properties.Settings.Default.wechatGetQrcodeUrl, HttpUtility.UrlEncode(ticket)); //qrCodePictureBox.LoadAsync(string.Format(Properties.Settings.Default.wechatGetQrcodeUrl, HttpUtility.UrlEncode(ticket))); JObject sceneRequestObj = new JObject(); sceneRequestObj["token"] = webToken; sceneRequestObj["scene_id"] = userid; while (true) { //防止由于某次连接异常,导致无法继续的问题 //try //{ msg = await client.PostAsync(Properties.Settings.Default.getSceneUrl, new StringContent(sceneRequestObj.ToString(), Encoding.UTF8, "application/json"), cancellationToken); msg.EnsureSuccessStatusCode(); retStr = await msg.Content.ReadAsStringAsync(); retObj = JObject.Parse(retStr); if (retObj["openid"] != null && retObj["openid"].ToString() != "") { string openid = retObj["openid"].ToString(); log.Info("scaned by: " + openid); tipLabel.Text = "扫码成功,正在获取用户信息!"; Properties.Settings.Default.openid = openid; Properties.Settings.Default.Save(); break; } //} //catch(Exception exp) //{ log.Error("error of getting scene: " + exp.ToString()); } await Task.Delay(2000); log.Info("one time again for getting scene!"); } while (true) { //防止由于某次连接异常,导致无法继续的问题 try { JObject userInfoRequestObj = new JObject(); userInfoRequestObj["token"] = webToken; userInfoRequestObj["openid"] = Properties.Settings.Default.openid; msg = await client.PostAsync(Properties.Settings.Default.getUserInfoUrl, new StringContent(userInfoRequestObj.ToString(), Encoding.UTF8, "application/json"), cancellationToken); msg.EnsureSuccessStatusCode(); retStr = await msg.Content.ReadAsStringAsync(); //如果没有用户信息,这里retStr是null,下面进行解析会出异常 //如果不捕获该异常并反复尝试,这里在界面上会表现为卡住 retObj = JObject.Parse(retStr); JToken openidToken = retObj["openid"]; JToken nicknameToken = retObj["nickname"]; JToken headimgurlToken = retObj["headimgurl"]; if (nicknameToken != null && nicknameToken.ToString() != "") { string nickname = nicknameToken.ToString(); string headimgurl = headimgurlToken.ToString(); log.Info("binding by: " + nickname); tipLabel.Text = "绑定成功!"; Properties.Settings.Default.userNickname = nickname; Properties.Settings.Default.userHeadimgurl = headimgurl; Properties.Settings.Default.Save(); try { WebClient downloadClient = new WebClient(); downloadClient.Proxy = null; downloadClient.DownloadFile(headimgurl, Program.AppLocalDir + "UserHeadImage"); } catch (Exception excep) { log.Error(excep.ToString()); } BindingSuccess = true; Program.RealBindingSucess = true; //if(MainForm.Instance != null) // MainForm.Instance.mainPanelControl.RefreshWechatInfo(); break; } else { tipLabel.Text = "请点击公众号绑定按钮完成绑定!"; } } catch (Exception exp) { log.Error("Error of getting user info: " + exp.ToString()); } await Task.Delay(2000); log.Info("one time again for getting user info!"); } log.Info("Binding Success!"); Close(); } catch (System.Net.Http.HttpRequestException reqErr) { AutoCloseMessageBox.ShowMessage(-1, "网络无法连接,请检查网络后点击刷新二维码重新绑定!"); log.Error(reqErr.ToString()); } catch (Exception err) { //AutoCloseMessageBox.ShowMessage(-1, "绑定出错,请点击刷新二维码重试!"); log.Error(err.ToString()); } }