static void Main(string[] args) { // Please enter your application access key string applicationAccessKey = ""; AppAccessToken token = new AppAccessToken(Guid.Parse(applicationAccessKey)); // Please enter your API key string dataCenterApiKey = ""; int checkIntervalInSeconds = 120; using (ILeadScoringEventClient client = new LeadScoringEventClient(token, dataCenterApiKey, checkIntervalInSeconds)) { // Always use the Subscribe method that allows you to plug in your custom error handling logic. client.Subscribe(ProcessLeadScoringThresholdPasses, ErrorHandler); int intervalInMinutes = TimeSpan.FromSeconds(checkIntervalInSeconds).Minutes; Console.WriteLine($"Waiting for {intervalInMinutes} minutes to receive Lead Scoring Threshold Passes. Pres any key to stop and exit"); Console.ReadLine(); Console.WriteLine("Unsubscribing from the LeadScoringEventClient. Waiting for pending operations to complete."); client.Unsubscribe(); Console.WriteLine("Pending operations complete."); } }
public async Task Handle_GetAppAccessTokenCommand_AccessTokenExisted() { //Arrange var expected = new AppAccessToken() { access_token = "789012", expires_in = 7200, time_stamp = DateTime.Now }; var db = new List <AppAccessToken>() { expected }; context.SetupGet(c => c.AppAccessTokens).Returns(Mocking.GetMockDbSet(db)); var command = new GetAppAccessTokenCommand(); var handler = createHandler(); //Act var result = await handler.Handle(command); //Assert context.VerifyAll(); Assert.True(Jsonning.EqualsOrThrows(expected, result)); Assert.Same(expected, db.FirstOrDefault()); }
public async Task GetAppAccessTokenAsync_WeChatCommunicator() { //Arrange var appid = "wxf1759596e3365d3e"; var secret = "50d58aee48c9e5cb8a593b93cc182547"; var access_token = "123456"; var expires_in = 7200; var expected = new AppAccessToken() { access_token = access_token, expires_in = expires_in, time_stamp = new DateTime(2017, 1, 1) }; var service = createService(); http.Setup(h => h.GetAsync($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}")) .Returns(Task.FromResult(JsonConvert.SerializeObject(new { access_token = access_token, expires_in = expires_in }))); provider.Setup(p => p.GetNow()).Returns(new DateTime(2017, 1, 1)); config["AppId"] = appid; config["Secret"] = secret; //Act var actual = await service.GetAppAccessTokenAsync(); //Assert http.VerifyAll(); provider.VerifyAll(); Assert.True(Jsonning.EqualsOrThrows(expected, actual)); }
protected void Page_Load(object sender, EventArgs e) { string urlInfo = HttpContext.Current.Request.Url.Query; string szopenid = Request["openid"]; if (string.IsNullOrEmpty(GetCode()) && string.IsNullOrEmpty(szopenid)) { string szParm = Request["ticket"]; string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + szAppID + "&redirect_uri=" + Server.UrlEncode(szICURL + "/pages/") + "shareredirt.aspx&response_type=code&scope=snsapi_base&state=" + szParm; Response.Redirect(url); Response.End(); } else { if (!string.IsNullOrEmpty(szopenid)) { // openid.Value = szopenid; } else { AppAccessToken accTocken = GetAppToken(); string szTicket = Request["state"];//乱转获取ticket string szWxUserID = GetInfoFromUrl(szWxUrl, "access_token=" + accTocken.access_token + "&ticket=" + szTicket); Response.Write(urlInfo); Response.Write("<br />"); Response.Write(accTocken.ToString()); Response.Write("<br />"); Response.Write("tickt=" + szTicket + "<br />"); Response.Write("szWxUserIDtext=" + szWxUserID); Response.End(); } } }
public async Task <IActionResult> Google([FromBody] GoogleModel googleModel) { var appAccessToken = new AppAccessToken(); var tokenResponse = await Client.PostAsync($"https://www.googleapis.com/oauth2/v4/token?code={googleModel.Code}&client_id={_googleAuthModel.ClientId}&client_secret={_googleAuthModel.ClientSecret}&redirect_uri=http://localhost/oauth2callback&grant_type=authorization_code", null); if (tokenResponse.StatusCode != HttpStatusCode.OK) { return(new BadRequestObjectResult(new { code = "InvalidCode", description = tokenResponse.Content.ReadAsStringAsync().Result }));// "Google authorization code is not valid."}); } appAccessToken = JsonConvert.DeserializeObject <AppAccessToken>(tokenResponse.Content.ReadAsStringAsync().Result); var userResponse = await Client.GetStringAsync($"https://www.googleapis.com/oauth2/v2/userinfo?access_token={appAccessToken.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <GoogleUserData>(userResponse); var existingUser = await _userManager.FindByEmailAsync(userInfo.Email); if (existingUser == null) { var user = new ApplicationUser { GoogleId = userInfo.Id, Email = userInfo.Email, UserName = userInfo.FirstName + userInfo.LastName, PictureUrl = userInfo.Picture, Visibility = true, Nationality = "US" }; if (userInfo.Gender != null) { user.Gender = userInfo.Gender.Equals("male") ? Gender.Male : userInfo.Gender.Equals("female") ? Gender.Female : Gender.Other; } else { user.Gender = Gender.None; } user.UserName = UserExtensions.RemoveDiacritics(user.UserName); var result = await _userManager.CreateAsync(user, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(new BadRequestObjectResult(result.Errors)); } else { existingUser = await _userManager.FindByNameAsync(user.UserName); } } var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(existingUser.UserName, existingUser.Id), _jwtFactory, existingUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }, existingUser.ProfileComplete); return(new OkObjectResult(jwt)); }
public static void Add_UpdateToken(int userId, TokenDetails _token, int forceupdate = 0, string deviceType = null) { try { LystenEntities db = new LystenEntities(); var chkToken = db.AppAccessTokens.Where(x => x.UserId == userId).FirstOrDefault(); if (chkToken != null) { if (chkToken.ExpiresOn <= DateTime.Now) { db.Entry(chkToken).State = EntityState.Modified; TimeSpan t = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["TokenExpireHour"].ToString())); chkToken.AuthToken = _token.access_token; chkToken.ExpiresOn = DateTime.Now.Add(t); chkToken.IssuedOn = DateTime.Now; db.SaveChanges(); } else { if (forceupdate > 0) { db.Entry(chkToken).State = EntityState.Modified; TimeSpan t = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["TokenExpireHour"].ToString())); chkToken.AuthToken = _token.access_token; chkToken.ExpiresOn = DateTime.Now.Add(t); chkToken.IssuedOn = DateTime.Now; chkToken.DeviceType = deviceType; db.SaveChanges(); } } } else { AppAccessToken _tokenDetails = new AppAccessToken(); _tokenDetails.UserId = userId; _tokenDetails.IssuedOn = DateTime.Now; TimeSpan t = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["TokenExpireHour"].ToString())); _tokenDetails.ExpiresOn = DateTime.Now.Add(t); _tokenDetails.AuthToken = _token.access_token; _tokenDetails.DeviceType = deviceType; db.AppAccessTokens.Add(_tokenDetails); db.SaveChanges(); } db.Dispose(); } catch (Exception ex) { } }
public AppAccessToken GetAppToken() { AppAccessToken accToken = null; if ( (Session["WAccessToken"] == null) || Session["WAccessToken"].GetType() != typeof(AppAccessToken) || (string.IsNullOrEmpty(((AppAccessToken)Session["WAccessToken"]).openid)) || (Session["WAccessToken_Time"] == null) || ((DateTime.Now - (DateTime)Session["WAccessToken_Time"]).TotalSeconds >= ((AppAccessToken)Session["WAccessToken"]).expires_in)) { String tok = Request["tok"]; if (!String.IsNullOrEmpty(tok)) { string szAccToken2 = GetWebRequest("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + szAppID + "&grant_type=refresh_token&refresh_token=" + tok); accToken = JSON.parse <AppAccessToken>(szAccToken2); if (accToken != null && accToken.access_token != null) { Session["WAccessToken"] = accToken; Session["WAccessToken_Time"] = DateTime.Now; //Logger.trace("oauth2 get refresh_token:" + accToken.openid); return(accToken); } else { Logger.Trace(szAccToken2); } } string szCode = GetCode(); string szAccToken = GetWebRequest("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + szAppID + "&secret=" + szAPPSercert + "&code=" + szCode + "&grant_type=authorization_code"); accToken = JSON.parse <AppAccessToken>(szAccToken); if (accToken != null && accToken.access_token != null) { Session["WAccessToken"] = accToken; Session["WAccessToken_Time"] = DateTime.Now; //Session.Timeout = 10; Logger.trace("szAccToken info=:" + szAccToken); Logger.trace("oauth2 get access_token:" + accToken.openid); } else { Logger.Trace(szAccToken); } } else { accToken = (AppAccessToken)Session["WAccessToken"]; } return(accToken); }
static void Main(string[] args) { string yourApplicationKey = ""; AppAccessToken token = new AppAccessToken(Guid.Parse(yourApplicationKey)); string yourDecDataCenterApiKey = ""; int checkIntervalInSeconds = 120; using (ILeadScoringEventClient client = new LeadScoringEventClient(token, yourDecDataCenterApiKey, checkIntervalInSeconds)) { client.Subscribe(ProcessLeadScoringThresholdPasses); int intervalInMinutes = TimeSpan.FromSeconds(checkIntervalInSeconds).Minutes; Console.WriteLine("Waiting for {0} minutes to receive Lead Scoring Threshold Passes. Pres any key to stop and exit", intervalInMinutes); Console.ReadLine(); Console.WriteLine("Unsubscribing from the LeadScoringEventClient. Waiting for pending operations to complete."); client.Unsubscribe(); Console.WriteLine("Pending operations complete."); } }
static void Main(string[] args) { string yourApplicationKey = ""; AppAccessToken token = new AppAccessToken(Guid.Parse(yourApplicationKey)); string yourDecDataCenterApiKey = ""; int checkIntervalInSeconds = 120; using (ILeadScoringEventClient client = new LeadScoringEventClient(token, yourDecDataCenterApiKey, checkIntervalInSeconds)) { client.Subscribe(ProcessLeadScoringThresholdPasses); int intervalInMinutes = TimeSpan.FromSeconds(checkIntervalInSeconds).Minutes; Console.WriteLine("Waiting for {0} minutes to receive Lead Scoring Threshold Passes. Pres any key to stop and exit", intervalInMinutes); Console.ReadLine(); Console.WriteLine("Unsubscribing from the LeadScoringEventClient. Waiting for pending operations to complete."); client.Unsubscribe(); Console.WriteLine("Pending operations complete."); } }
public async Task Handle_GetAppAccessTokenCommand_AccessTokenNotExisted() { //Arrange var expected = new AppAccessToken(); var db = new List <AppAccessToken>(); communicator.Setup(c => c.GetAppAccessTokenAsync()) .Returns(Task.FromResult(expected)); context.SetupGet(c => c.AppAccessTokens).Returns(Mocking.GetMockDbSet(db)); context.Setup(c => c.SaveAsync()).Returns(Task.CompletedTask); var command = new GetAppAccessTokenCommand(); var handler = createHandler(); //Act var result = await handler.Handle(command); //Assert communicator.VerifyAll(); context.VerifyAll(); Assert.True(Jsonning.EqualsOrThrows(expected, result)); Assert.Same(expected, db.FirstOrDefault()); }
public async Task Handle_GetAppAccessTokenCommand_AccessTokenOutDated() { //Arrange var expected = new AppAccessToken() { access_token = "789012", expires_in = 7200, time_stamp = DateTime.Now }; var db = new List <AppAccessToken>() { new AppAccessToken { access_token = "123456", expires_in = 7200, time_stamp = DateTime.Now.AddHours(-3) } }; communicator.Setup(c => c.GetAppAccessTokenAsync()) .Returns(Task.FromResult(expected)); context.SetupGet(c => c.AppAccessTokens).Returns(Mocking.GetMockDbSet(db)); context.Setup(c => c.SaveAsync()).Returns(Task.CompletedTask); var command = new GetAppAccessTokenCommand(); var handler = createHandler(); //Act var result = await handler.Handle(command); //Assert communicator.VerifyAll(); context.VerifyAll(); Assert.True(Jsonning.EqualsOrThrows(expected, result)); Assert.Equal(expected.access_token, db.FirstOrDefault().access_token); Assert.Equal(expected.expires_in, db.FirstOrDefault().expires_in); Assert.Equal(expected.time_stamp, db.FirstOrDefault().time_stamp); }
public string GetToken() { bool bNeedNew = true; if (Application["access_token"] != null && Application["expires_in"] != null) { DateTime dt = DateTime.Parse(Application["expires_in"].ToString()); TimeSpan sp = DateTime.Now.Subtract(dt); if (sp.TotalMinutes > 1) { return(Application["access_token"].ToString()); bNeedNew = false; } } if (bNeedNew) { string szRes = GetWebRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + szAppID + "&secret=" + szAPPSercert + ""); AppAccessToken apptocken = JSON.parse <AppAccessToken>(szRes); return(apptocken.access_token); } return(null); }
protected void Page_Load(object sender, EventArgs e) { string urlInfo = HttpContext.Current.Request.Url.Query; AppAccessToken accTocken = GetAppToken(); string szopenid = accTocken.openid; Response.Redirect("http://ic.unifound.net/pages/seatyyy.aspx?openid=" + szopenid); Response.End(); string szTicket = Request["state"]; //乱转获取ticket string szWxUserID = GetWebRequest(szWxUrl + "?access_token=" + accTocken.access_token.ToString() + "&ticket=" + szTicket); // GetInfoFromUrl(szWxUrl, "access_token=" + accTocken.refresh_token.ToString() +"&ticket=" + szTicket); Response.Write(urlInfo); Response.Write("<br />"); Response.Write("openid=" + accTocken.openid.ToString()); Response.Write("<br />"); Response.Write("access_token=" + accTocken.access_token.ToString()); Response.Write("<br />"); Response.Write("tickt=" + szTicket + "<br />"); Response.Write("szWxUserIDtext=" + szWxUserID); Response.End(); }