public async Task <SapLoginCookies> StartSession() { if (_sapCookies is null || _dateTimeProvider.UtcNow > _sapCookies.SessionEndAt) { try { var client = _httpClientFactory.CreateClient(); var sapResponse = await client.SendAsync(new HttpRequestMessage { RequestUri = new Uri($"{_sapServiceConfig.BaseServerUrl}Login/"), Content = new StringContent(JsonConvert.SerializeObject( new SapServiceConfig { CompanyDB = _sapServiceConfig.CompanyDB, Password = _sapServiceConfig.Password, UserName = _sapServiceConfig.UserName }), Encoding.UTF8, "application/json"), Method = HttpMethod.Post }); sapResponse.EnsureSuccessStatusCode(); var sessionTimeout = JObject.Parse(await sapResponse.Content.ReadAsStringAsync()); _sapCookies = new SapLoginCookies { B1Session = sapResponse.Headers.GetValues("Set-Cookie").Where(x => x.Contains("B1SESSION")) .Select(y => y.ToString().Substring(0, 46)).FirstOrDefault(), RouteId = sapResponse.Headers.GetValues("Set-Cookie").Where(x => x.Contains("ROUTEID")) .Select(y => y.ToString().Substring(0, 14)).FirstOrDefault(), SessionEndAt = _dateTimeProvider.UtcNow.AddMinutes((double)sessionTimeout["SessionTimeout"] - _sapConfig.SessionTimeoutPadding) }; } catch (Exception e) { _logger.LogError(e, "Error starting session in Sap."); throw; } } return(_sapCookies); }
private async Task <SapTaskResult> SendIncomingPaymentToSap(SapServiceConfig serviceSetting, string sapSystem, SapSaleOrderInvoiceResponse response, string transferReference, SapLoginCookies cookies) { var billingMapper = GetMapper(sapSystem); var incomingPaymentRequest = billingMapper.MapSapIncomingPayment(response.DocEntry, response.CardCode, response.DocTotal, response.DocDate, transferReference); var message = new HttpRequestMessage { RequestUri = new Uri($"{serviceSetting.BaseServerUrl}{serviceSetting.BillingConfig.IncomingPaymentsEndpoint}"), Content = new StringContent(JsonConvert.SerializeObject(incomingPaymentRequest), Encoding.UTF8, "application/json"), Method = HttpMethod.Post }; message.Headers.Add("Cookie", cookies.B1Session); message.Headers.Add("Cookie", cookies.RouteId); var client = _httpClientFactory.CreateClient(); var sapResponse = await client.SendAsync(message); if (!sapResponse.IsSuccessStatusCode) { _logger.LogError($"Incoming Payment could'n create to SAP because exists an error: '{sapResponse.Content.ReadAsStringAsync()}'."); } return(new SapTaskResult { IsSuccessful = sapResponse.IsSuccessStatusCode, SapResponseContent = await sapResponse.Content.ReadAsStringAsync(), TaskName = "Creating Billing Request" }); }