73 lines
2.8 KiB
C#
73 lines
2.8 KiB
C#
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Fake.DependencyInjection;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Oms.Application.Integrations.Itfx;
|
|
|
|
internal sealed class ItfxForwardClient(
|
|
IHttpClientFactory httpClientFactory,
|
|
IOptions<ItfxGatewayOptions> options,
|
|
IHttpContextAccessor httpContextAccessor) : IItfxForwardClient, IScopedDependency
|
|
{
|
|
public const string HttpClientName = nameof(ItfxForwardClient);
|
|
public const string CreateOrderOneStandardCode = "createOrderOne";
|
|
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
WriteIndented = true
|
|
};
|
|
|
|
public async Task<ItfxForwardResult> ForwardCreateOrderOneAsync(
|
|
string supplierCode,
|
|
string appKey,
|
|
string appSecret,
|
|
object body,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
var settings = options.Value;
|
|
if (string.IsNullOrWhiteSpace(settings.BaseUrl))
|
|
{
|
|
throw new InvalidOperationException("Itfx BaseUrl not configured");
|
|
}
|
|
|
|
var root = $"{settings.BaseUrl.Trim().TrimEnd('/')}/InterfaceForward/ForwardWithSubscribe";
|
|
var url =
|
|
$"{root}?standardCode={CreateOrderOneStandardCode}&supplierCode={Uri.EscapeDataString(supplierCode)}";
|
|
var requestJson = JsonSerializer.Serialize(body, JsonOptions);
|
|
|
|
using var request = new HttpRequestMessage(HttpMethod.Post, url);
|
|
request.Headers.TryAddWithoutValidation("appkey", appKey);
|
|
request.Headers.TryAddWithoutValidation("appSecret", appSecret);
|
|
request.Headers.TryAddWithoutValidation("followName", "0");
|
|
ForwardAuthorization(request);
|
|
request.Content = JsonContent.Create(body, options: JsonOptions);
|
|
|
|
var client = httpClientFactory.CreateClient(HttpClientName);
|
|
client.Timeout = TimeSpan.FromSeconds(Math.Max(30, settings.TimeoutSeconds));
|
|
|
|
using var response = await client.SendAsync(request, cancellationToken);
|
|
var responseBody = await response.Content.ReadAsStringAsync(cancellationToken);
|
|
return new ItfxForwardResult
|
|
{
|
|
Success = response.IsSuccessStatusCode,
|
|
Url = url,
|
|
RequestJson = requestJson,
|
|
StatusCode = (int)response.StatusCode,
|
|
ResponseBody = responseBody
|
|
};
|
|
}
|
|
|
|
private void ForwardAuthorization(HttpRequestMessage request)
|
|
{
|
|
var authorization = httpContextAccessor.HttpContext?.Request.Headers.Authorization.ToString();
|
|
if (!string.IsNullOrWhiteSpace(authorization))
|
|
{
|
|
request.Headers.Authorization = AuthenticationHeaderValue.Parse(authorization);
|
|
}
|
|
}
|
|
}
|