using System.Text; using System.Text.Json; using Fake.Application; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.OpenApi; using Oms.Application.Dtos.Orders; using Oms.Application.Integrations.SmallBagTrack; using Oms.Application.Services.Orders; using Oms.Application.Shared; using Oms.Domain.OrdersAggregate.Consts; namespace Oms.Application.Services.OpenApi; /// /// 客户对外开放 API(Swagger 文档分组:openApi)。 /// 统一响应:{ code, msg, data }。 /// 鉴权:Header appKey + timestamp + sign(HMAC-SHA256,5 分钟窗口);Secret 不上传。 /// 仓配 Token 接口见分组 warehouseOpenApi。 /// [ApiExplorerSettings(GroupName = "openApi")] public class OpenApiService : ApplicationService { private static readonly JsonSerializerOptions BodyJsonOptions = new() { PropertyNameCaseInsensitive = true }; private CustomerOpenApiAuthHelper AuthHelper => LazyServiceProvider.GetRequiredService(); private PickupOrderFeePushService FeePush => LazyServiceProvider.GetRequiredService(); private OrderService OrderService => LazyServiceProvider.GetRequiredService(); private OrderFileManager OrderFileManager => LazyServiceProvider.GetRequiredService(); private OpenApiCustomerOrderResolver OrderResolver => LazyServiceProvider.GetRequiredService(); private ISmallBagTrackOrderClient TrackClient => LazyServiceProvider.GetRequiredService(); private IHttpContextAccessor HttpContextAccessor => LazyServiceProvider.GetRequiredService(); /// /// 推送揽收件重尺并按当前产品计算应收应付(上游 itfx 鉴权后转发,无需客户凭证)。 /// [AllowAnonymous] [HttpPost("/openapi/pickup-order/push-fee")] public async Task> PushFeeAsync( [FromBody] PickupOpenApiPushFeeInput input) { try { var data = await FeePush.PushFeeAsync(input); return OpenApiEnvelope.Ok(data); } catch (BusinessException ex) { return OpenApiEnvelope.Fail(ex.Message); } catch (Exception ex) { return OpenApiEnvelope.Fail( string.IsNullOrWhiteSpace(ex.Message) ? "系统异常" : ex.Message, "500"); } } /// /// 创建订单包裹(仅自发货)。 /// Header:appKey、timestamp(Unix 秒)、sign。 /// sign = hex(HMAC-SHA256(appSecret, appKey + "\n" + timestamp + "\n" + sha256Hex(rawBody)))。 /// [AllowAnonymous] [HttpPost("/openapi/parcel/create")] [Consumes("application/json")] [Produces("application/json")] public async Task> CreateParcelAsync( [FromHeader(Name = CustomerOpenApiAuthHelper.AppKeyHeaderName)] string? appKey, [FromHeader(Name = CustomerOpenApiAuthHelper.TimestampHeaderName)] string? timestamp, [FromHeader(Name = CustomerOpenApiAuthHelper.SignHeaderName)] string? sign, [FromBody] OpenApiParcelCreateInput? requestBody) { try { var rawBody = await ReadRawBodyAsync(); var (customer, _) = await AuthHelper.ResolveSignedAsync(appKey, timestamp, sign, rawBody); var input = JsonSerializer.Deserialize(rawBody, BodyJsonOptions); if (input == null) { throw new BusinessException("请求体不能为空"); } var data = await OrderService.CreateParcelForCustomerOpenApiAsync( input.ToOrderParcelCreateInput(customer.Id)); return OpenApiEnvelope.Ok(data); } catch (BusinessException ex) { return OpenApiEnvelope.Fail(ex.Message); } catch (JsonException) { return OpenApiEnvelope.Fail("请求体格式错误"); } catch (Exception ex) { return OpenApiEnvelope.Fail( string.IsNullOrWhiteSpace(ex.Message) ? "系统异常" : ex.Message, "500"); } } /// /// 查询轨迹。Header 同创建包裹。按 clientNo / serviceNo / trackNo 定位本客户订单。 /// [AllowAnonymous] [HttpPost("/openapi/track/query")] [Consumes("application/json")] [Produces("application/json")] public async Task> QueryTrackAsync( [FromHeader(Name = CustomerOpenApiAuthHelper.AppKeyHeaderName)] string? appKey, [FromHeader(Name = CustomerOpenApiAuthHelper.TimestampHeaderName)] string? timestamp, [FromHeader(Name = CustomerOpenApiAuthHelper.SignHeaderName)] string? sign, [FromBody] OpenApiTrackQueryInput? requestBody) { try { var rawBody = await ReadRawBodyAsync(); var (customer, _) = await AuthHelper.ResolveSignedAsync(appKey, timestamp, sign, rawBody); var input = DeserializeBody(rawBody); var order = await OrderResolver.ResolveAsync(customer.Id, input); if (string.IsNullOrWhiteSpace(order.ServiceNo)) { throw new BusinessException("订单无服务单号,无法查询轨迹"); } var events = await TrackClient.QuerySmallBagTracksAsync(order.ServiceNo); return OpenApiEnvelope.Ok(new OpenApiTrackQueryOutput { OrderId = order.Id, ClientNo = order.ClientNo, ServiceNo = order.ServiceNo, TrackNo = order.TrackNo, Events = events }); } catch (BusinessException ex) { return OpenApiEnvelope.Fail(ex.Message); } catch (JsonException) { return OpenApiEnvelope.Fail("请求体格式错误"); } catch (Exception ex) { return OpenApiEnvelope.Fail( string.IsNullOrWhiteSpace(ex.Message) ? "系统异常" : ex.Message, "500"); } } /// /// 按附件类型获取文件。Header 同创建包裹。 /// fileType:tradeProof / systemLabel / lastMileLabel / infraredImage / pod。不含 downstreamLabel。 /// [AllowAnonymous] [HttpPost("/openapi/files/get")] [Consumes("application/json")] [Produces("application/json")] public async Task> GetFilesAsync( [FromHeader(Name = CustomerOpenApiAuthHelper.AppKeyHeaderName)] string? appKey, [FromHeader(Name = CustomerOpenApiAuthHelper.TimestampHeaderName)] string? timestamp, [FromHeader(Name = CustomerOpenApiAuthHelper.SignHeaderName)] string? sign, [FromBody] OpenApiFilesGetInput? requestBody) { try { var rawBody = await ReadRawBodyAsync(); var (customer, _) = await AuthHelper.ResolveSignedAsync(appKey, timestamp, sign, rawBody); var input = DeserializeBody(rawBody); if (string.IsNullOrWhiteSpace(input.FileType)) { throw new BusinessException("请传入 fileType"); } if (!OrderFileTypeCodes.IsCustomerOpenApiAllowed(input.FileType)) { throw new BusinessException("不支持的附件类型"); } var order = await OrderResolver.ResolveAsync(customer.Id, input); var files = await OrderFileManager.GetByTypeAsync(order.Id, input.FileType); return OpenApiEnvelope.Ok(new OpenApiFilesGetOutput { OrderId = order.Id, ClientNo = order.ClientNo, ServiceNo = order.ServiceNo, FileType = OrderFileTypeCodes.Normalize(input.FileType), Files = files.Select(x => new OpenApiFileItemDto { Id = x.Id, FileName = x.FileName, FileUrl = x.FileUrl, ContentType = x.ContentType, FileSize = x.FileSize, Source = x.Source, CreateTime = x.CreateTime }).ToList() }); } catch (BusinessException ex) { return OpenApiEnvelope.Fail(ex.Message); } catch (JsonException) { return OpenApiEnvelope.Fail("请求体格式错误"); } catch (Exception ex) { return OpenApiEnvelope.Fail( string.IsNullOrWhiteSpace(ex.Message) ? "系统异常" : ex.Message, "500"); } } private T DeserializeBody(string rawBody) { if (string.IsNullOrWhiteSpace(rawBody)) { throw new BusinessException("请求体不能为空"); } var input = JsonSerializer.Deserialize(rawBody, BodyJsonOptions); if (input == null) { throw new BusinessException("请求体不能为空"); } return input; } private async Task ReadRawBodyAsync() { var http = HttpContextAccessor.HttpContext ?? throw new BusinessException("凭证无效"); var request = http.Request; request.EnableBuffering(); if (request.Body.CanSeek) { request.Body.Position = 0; } using var reader = new StreamReader(request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true); var raw = await reader.ReadToEndAsync(); if (request.Body.CanSeek) { request.Body.Position = 0; } return raw; } }