public void Init() { // Configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); IConfiguration config = configBuilder.Build(); // Spotify Client Factory _client = SpotifySdkClientFactory.CreateSpotifySdkClient( config["client_id"], config["client_secret"], redirect_url, state ).Set(country); Assert.IsNotNull(_client); // Spotify Client Token var authenticationToken = new AuthenticationTokenResponse() { Token = config["token"], Refresh = config["refresh"], Expiration = DateTime.Parse(config["expires"]), AuthenticationTokenType = (AuthenticationTokenType)Enum.Parse(typeof(AuthenticationTokenType), config["type"]) }; _client.AuthenticationToken = authenticationToken; _client.Limit = limit; }
private async Task <HttpClient> GetAuthenticateClientAsync(string region) { if (string.IsNullOrEmpty(authenticationTokenResponse.AccessToken) || DateTime.UtcNow > authenticationTokenResponse.ExpireAt) { using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {Base64Encode($"{clientId}:{clientSecret}")}"); var formContent = new List <KeyValuePair <string, string> >(); formContent.Add(new KeyValuePair <string, string>("grant_type", "client_credentials")); var url = $"https://{region}.battle.net/oauth/token"; var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(formContent) }; var httpResponse = await httpClient.SendAsync(httpRequest); if (httpResponse.IsSuccessStatusCode) { authenticationTokenResponse = JsonSerializer.Deserialize <AuthenticationTokenResponse>(await httpResponse.Content.ReadAsStringAsync()); authenticationTokenResponse.ExpireAt = DateTime.UtcNow.AddSeconds(authenticationTokenResponse.ExpiresIn - 100); } else { throw new ApiException("Authentication failed", new Exception(await httpResponse.Content.ReadAsStringAsync())); } } } var httpClientAuth = new HttpClient(); httpClientAuth.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {authenticationTokenResponse.AccessToken}"); return(httpClientAuth); }
public async Task <IActionResult> PaymentPostInfo() { var model = new AuthenticationTokenResponse(); try { model = await FindStatusCallAsync(); //session save HttpContext.Session.Set("syfPaymentInfo", model); if (model.StatusMessage != "Account Authentication Success") { HttpContext.Session.SetString("PaymentMethodError", model.StatusMessage); return(Json(new { update_section = new UpdateSectionJsonModel { name = "Error", html = await RenderPartialViewToStringAsync("~/Plugins/Payments.Synchrony/Views/ErrorMessagepopup.cshtml", null) }, goto_section = "Error" })); } } catch (Exception ex) { await _logger.WarningAsync(ex.Message, ex, await _workContext.GetCurrentCustomerAsync()); HttpContext.Session.SetString("PaymentMethodError", "An error occurred."); return(Json(new { update_section = new UpdateSectionJsonModel { name = "Error", html = await RenderPartialViewToStringAsync("~/Plugins/Payments.Synchrony/Views/ErrorMessagepopup.cshtml", null) }, goto_section = "Error" })); } TempData["SecondModalpopup"] = JsonSerializer.Serialize(model); return(Json(new { update_section = new UpdateSectionJsonModel { name = "Third-Modal-Method", html = await RenderPartialViewToStringAsync("~/Plugins/Payments.Synchrony/Views/ThirdModalpopup.cshtml", model) }, goto_section = "Third_Modal_Method" })); }
private async Task <string> RequestAccessToken(string pin) { string url = "https://api.home.nest.com/oauth2/access_token"; using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; string bodyString = $"client_id={this.Config.ClientId}&client_secret={this.Config.ClientSecret}&grant_type=authorization_code&code={pin}"; byte[] responseBytes = await wc.UploadDataTaskAsync(url, Encoding.ASCII.GetBytes(bodyString)); string responseJson = Encoding.ASCII.GetString(responseBytes); AuthenticationTokenResponse response = JsonConvert.DeserializeObject <AuthenticationTokenResponse>(responseJson); return(response.access_token); } }
public string GetToken() { if (!_authenticationToken.HasToken() || _authenticationToken.HasExpired()) { string url = _marketoInstanceUrl + "identity/oauth/token?grant_type=client_credentials&client_id=" + _marketoClientId + "&client_secret=" + _marketoClientSecret; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); StreamReader reader = new StreamReader(resStream); string json = reader.ReadToEnd(); AuthenticationTokenResponse authenticationTokenResponse = JsonConvert.DeserializeObject <AuthenticationTokenResponse>(json); _authenticationToken = new AuthenticationToken() { AccessToken = authenticationTokenResponse.Access_token, Expires = DateTime.Now.AddSeconds(authenticationTokenResponse.Expires_in - 500) }; } return(_authenticationToken.AccessToken); }
public async Task <IViewComponentResult> InvokeAsync() { var storeScope = await _storeContext.GetActiveStoreScopeConfigurationAsync(); //Stored Merchant Id & Password var merchantId = _settings.MerchantId; var merchantPassword = _settings.MerchantPassword; AuthenticationTokenResponse model = new AuthenticationTokenResponse(); // get authorization region end point string authorizationRegionURL = _settings.Integration == true ? SynchronyPaymentConstants.DemoAuthEndpoint : SynchronyPaymentConstants.LiveAuthEndpoint; // take reference from below link - Answer 1 by Seema As // https://stackoverflow.com/questions/39190018/how-to-get-object-using-httpclient-with-response-ok-in-web-api ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(authorizationRegionURL); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded"); client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0"); List <KeyValuePair <string, string> > keyValues = new List <KeyValuePair <string, string> >(); keyValues.Add(new KeyValuePair <string, string>("merchantId", merchantId)); keyValues.Add(new KeyValuePair <string, string>("password", merchantPassword)); if (_settings.IsDebugMode) { await _logger.InsertLogAsync( LogLevel.Debug, "Synchrony.Payments: Auth Request", "curl --request POST " + $"--url {authorizationRegionURL} " + "--header 'content-type: application/x-www-form-urlencoded' " + $"--data merchantId={merchantId} " + $"--data 'password={merchantPassword}'"); } HttpContent content = new FormUrlEncodedContent(keyValues); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.ContentType.CharSet = "UTF-8"; var result = client.PostAsync(authorizationRegionURL, content).Result; string resultContent = result.Content.ReadAsStringAsync().Result; if (_settings.IsDebugMode) { await _logger.InsertLogAsync( LogLevel.Debug, "Synchrony.Payments: Auth Response", resultContent); } AuthenticationTokenResponse authResponse; try { authResponse = JsonSerializer.Deserialize <AuthenticationTokenResponse>(resultContent); } catch (JsonException e) { await _logger.ErrorAsync($"Issue when converting Synchrony response to JSON, response was {resultContent}: ", e); _httpContextAccessor.HttpContext.Session.SetString("PaymentMethodError", "There was an error when processing Synchrony payments. Please select another payment method."); _httpContextAccessor.HttpContext.Response.Redirect("/checkout/paymentmethod"); return(Content("")); } string token = authResponse.clientToken; _httpContext.HttpContext.Session.Set("token", token); string postBackId = authResponse.postbackid; model.MerchantId = merchantId; model.MerchantPassword = merchantPassword; model.clientToken = token; model.postbackid = postBackId; Random r = new Random(); model.clientTransId = r.Next(11, int.MaxValue).ToString(); model.Integration = _settings.Integration; } return(View("~/Plugins/Payments.Synchrony/Views/PaymentInfo.cshtml", model)); }
public static AccessToken Map(this IMapper mapper, AuthenticationTokenResponse accessToken) => mapper.Map <AccessToken>(accessToken);
private async Task <AuthenticationTokenResponse> FindStatusCallAsync() { var storeScope = await _storeContext.GetActiveStoreScopeConfigurationAsync(); var paySynchronyPaymentSettings = await _settingService.LoadSettingAsync <SynchronyPaymentSettings>(storeScope); var cart = await _shoppingCartService.GetShoppingCartAsync( await _workContext.GetCurrentCustomerAsync(), ShoppingCartType.ShoppingCart, (await _storeContext.GetCurrentStoreAsync()).Id); var orderTotalsModel = await _shoppingCartModelFactory.PrepareOrderTotalsModelAsync(cart, false); string authorizationRegionStatusURL = paySynchronyPaymentSettings.Integration ? SynchronyPaymentConstants.DemoInquiryEndpoint : SynchronyPaymentConstants.LiveInquiryEndpoint; var merchantId = paySynchronyPaymentSettings.MerchantId; var merchantPassword = paySynchronyPaymentSettings.MerchantPassword; var Integration = paySynchronyPaymentSettings.Integration; var token = HttpContext.Session.GetString("token").Replace("\"", ""); var transactionAmount = Convert.ToDecimal(orderTotalsModel.OrderTotal.Replace("$", "")); var model = new AuthenticationTokenResponse(); // take reference from below link - Answer 1 by Seema As // https://stackoverflow.com/questions/39190018/how-to-get-object-using-httpclient-with-response-ok-in-web-api var response = new HttpResponseMessage(); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(authorizationRegionStatusURL); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0"); ServicePointManager.Expect100Continue = true; var requestBody = new { merchantNumber = merchantId, password = merchantPassword, userToken = token }; string json = JsonSerializer.Serialize(requestBody); if (_synchronyPaymentSettings.IsDebugMode) { await _logger.InsertLogAsync(Core.Domain.Logging.LogLevel.Debug, $"FindStatusCallAsync request - {requestBody.ToString()}"); } var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; response = await client.PostAsync(authorizationRegionStatusURL, content); } var authResponseJsonAsString = await response.Content.ReadAsStringAsync(); if (_synchronyPaymentSettings.IsDebugMode) { await _logger.InsertLogAsync(Core.Domain.Logging.LogLevel.Debug, $"FindStatusCallAsync response - {authResponseJsonAsString}"); } if (authResponseJsonAsString.Contains("Unauthorized")) { await _logger.ErrorAsync($"Payments.Synchrony: Failed authenticating - {authResponseJsonAsString}"); throw new HttpRequestException("There was an error, please select another payment method."); } var authResponse = JsonSerializer.Deserialize <AuthenticationTokenResponse>( authResponseJsonAsString ); var customer = await _workContext.GetCurrentCustomerAsync(); var billingAddress = await _addressService.GetAddressByIdAsync(customer.BillingAddressId.Value); model.Integration = Integration; model.MerchantId = merchantId; model.clientToken = token; model.transactionId = authResponse.transactionId; model.responseCode = authResponse.responseCode; model.responseDesc = authResponse.responseDesc; model.ZipCode = billingAddress.ZipPostalCode; model.State = (await _stateProvinceService.GetStateProvinceByAddressAsync( billingAddress )).Abbreviation; model.FirstName = billingAddress.FirstName; model.City = billingAddress.City; model.Address1 = billingAddress.Address1; model.LastName = billingAddress.LastName; model.StatusCode = authResponse.StatusCode; model.AccountNumber = authResponse.AccountNumber; model.StatusMessage = authResponse.StatusMessage; model.TransactionAmount = transactionAmount.ToString(); model.ClientTransactionID = authResponse.ClientTransactionID; model.TransactionDate = authResponse.TransactionDate; model.TransactionDescription = authResponse.TransactionDescription; model.AuthCode = authResponse.AuthCode; model.PromoCode = authResponse.PromoCode; model.PostbackId = authResponse.PostbackId; return(model); }