diff --git a/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs b/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs index c285e2d..c78fe82 100644 --- a/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs +++ b/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs @@ -61,3 +61,55 @@ public class TrialWechatOrderNotifyInput /// 运单号(OrderId 为空时使用)。 public string? ServiceNo { get; set; } } + +/// 试发结果(含请求/响应明细,供运营排查)。 +public class TrialWechatOrderNotifyResultOutput +{ + /// 是否最终发送成功。 + public bool Success { get; set; } + + /// 是否跳过发送(未启用/未绑 OpenId 等)。 + public bool Skipped { get; set; } + + /// 状态:sent / failed / skipped。 + public string Status { get; set; } = "skipped"; + + /// 说明或错误信息。 + public string? Message { get; set; } + + /// 订单 Id。 + public int OrderId { get; set; } + + /// 运单号。 + public string? ServiceNo { get; set; } + + /// 事件码。 + public string EventCode { get; set; } = string.Empty; + + /// 事件名。 + public string? EventName { get; set; } + + /// 接收 OpenId。 + public string? OpenId { get; set; } + + /// 微信模板 ID。 + public string? TemplateId { get; set; } + + /// 跳转 URL。 + public string? Url { get; set; } + + /// 微信接口地址(不含 access_token)。 + public string? RequestUrl { get; set; } + + /// 发给微信的请求体 JSON。 + public string? RequestBody { get; set; } + + /// 微信返回 JSON(或合成摘要)。 + public string? ResponseBody { get; set; } + + /// 微信 msgid。 + public string? WxMsgId { get; set; } + + /// 微信 errcode。 + public int? ErrCode { get; set; } +} diff --git a/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs b/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs index 1d31de0..8a4edb4 100644 --- a/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs +++ b/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs @@ -84,10 +84,10 @@ public class WechatOrderNotifyConfigService : ApplicationService } /// - /// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId)。 + /// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId);返回请求/响应明细。 /// [HttpPost("/system/wechat-order-notify/trial-send")] - public async Task TrialSendAsync( + public async Task TrialSendAsync( [FromBody] TrialWechatOrderNotifyInput input, CancellationToken cancellationToken = default) { @@ -100,7 +100,7 @@ public class WechatOrderNotifyConfigService : ApplicationService var order = await ResolveOrderAsync(input, cancellationToken) ?? throw new BusinessException("未找到订单"); - await Dispatcher.TryNotifyAsync( + return await Dispatcher.NotifyDetailedAsync( order, code, remark: "运营试发", diff --git a/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs b/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs index a1e71c9..9189a3f 100644 --- a/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs +++ b/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs @@ -1,6 +1,7 @@ using System.Text.Json; using Fake.DependencyInjection; using Microsoft.Extensions.Logging; +using Oms.Application.Dtos.System; using Oms.Application.Integrations.WeChat; using Oms.Application.Shared; using Oms.Domain.CustomersAggregate.Repositories; @@ -23,6 +24,9 @@ public class WechatOrderNotifyDispatcher( IWeChatMpTemplateSender templateSender, ILogger logger) : IScopedDependency { + private const string WechatTemplateSendUrl = + "https://api.weixin.qq.com/cgi-bin/message/template/send"; + private static readonly TimeSpan DedupWindow = TimeSpan.FromMinutes(30); private static readonly JsonSerializerOptions JsonOptions = new() @@ -47,7 +51,7 @@ public class WechatOrderNotifyDispatcher( { try { - await NotifyCoreAsync(order, eventCode, remark, force, cancellationToken); + await NotifyDetailedAsync(order, eventCode, remark, force, cancellationToken); } catch (Exception ex) { @@ -59,24 +63,49 @@ public class WechatOrderNotifyDispatcher( } } - private async Task NotifyCoreAsync( + /// + /// 运营试发:返回请求/响应明细;业务跳过/失败不抛,异常仍向上抛。 + /// + public Task NotifyDetailedAsync( + Order order, + string eventCode, + string? remark = null, + bool force = false, + CancellationToken cancellationToken = default) => + NotifyCoreAsync(order, eventCode, remark, force, cancellationToken); + + private async Task NotifyCoreAsync( Order order, string eventCode, string? remark, bool force, CancellationToken cancellationToken) { + var result = new TrialWechatOrderNotifyResultOutput + { + OrderId = order.Id, + ServiceNo = order.ServiceNo, + EventCode = eventCode, + Status = "skipped", + Skipped = true + }; + if (!WechatOrderNotifyEventCodes.IsKnown(eventCode)) { - return; + result.Message = "未知事件码"; + return result; } var normalized = WechatOrderNotifyEventCodes.Normalize(eventCode); var eventName = WechatOrderNotifyEventCodes.GetName(normalized) ?? normalized; + result.EventCode = normalized; + result.EventName = eventName; var template = await templateRepository.GetByEventCodeAsync(normalized, cancellationToken); if (template == null || !template.IsEnabled) { + result.TemplateId = template?.TemplateId; + result.Message = "运营未启用该事件模板"; await WriteLogAsync( order, customerId: order.CustomerId ?? 0, @@ -84,13 +113,16 @@ public class WechatOrderNotifyDispatcher( openId: null, templateId: template?.TemplateId, status: "skipped", - errMsg: "运营未启用该事件模板", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } + result.TemplateId = template.TemplateId; + if (string.IsNullOrWhiteSpace(template.TemplateId)) { + result.Message = "未配置微信 TemplateId"; await WriteLogAsync( order, customerId: order.CustomerId ?? 0, @@ -98,13 +130,14 @@ public class WechatOrderNotifyDispatcher( openId: null, templateId: null, status: "skipped", - errMsg: "未配置微信 TemplateId", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } if (order.CustomerId is not int customerId || customerId <= 0) { + result.Message = "订单无客户"; await WriteLogAsync( order, customerId: 0, @@ -112,9 +145,9 @@ public class WechatOrderNotifyDispatcher( openId: null, templateId: template.TemplateId, status: "skipped", - errMsg: "订单无客户", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } if (!force) @@ -122,6 +155,7 @@ public class WechatOrderNotifyDispatcher( var pref = await prefRepository.GetByCustomerAndEventAsync(customerId, normalized, cancellationToken); if (pref is not { IsSubscribed: true }) { + result.Message = "客户未订阅该事件"; await WriteLogAsync( order, customerId, @@ -129,14 +163,15 @@ public class WechatOrderNotifyDispatcher( openId: null, templateId: template.TemplateId, status: "skipped", - errMsg: "客户未订阅该事件", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } var since = DateTime.Now.Subtract(DedupWindow); if (await logRepository.ExistsRecentAsync(order.Id, normalized, since, cancellationToken)) { + result.Message = $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过"; await WriteLogAsync( order, customerId, @@ -144,9 +179,9 @@ public class WechatOrderNotifyDispatcher( openId: null, templateId: template.TemplateId, status: "skipped", - errMsg: $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } } @@ -154,6 +189,7 @@ public class WechatOrderNotifyDispatcher( var openId = customer?.WechatOpenid?.Trim(); if (string.IsNullOrWhiteSpace(openId)) { + result.Message = "客户未绑定微信 OpenId"; await WriteLogAsync( order, customerId, @@ -161,15 +197,18 @@ public class WechatOrderNotifyDispatcher( openId: null, templateId: template.TemplateId, status: "skipped", - errMsg: "客户未绑定微信 OpenId", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } + result.OpenId = openId; + var placeholders = BuildPlaceholders(order, eventName, remark, customer?.CustomerName); var data = BuildTemplateData(template.FieldMappingJson, placeholders); if (data.Count == 0) { + result.Message = "字段映射为空或无效"; await WriteLogAsync( order, customerId, @@ -177,12 +216,18 @@ public class WechatOrderNotifyDispatcher( openId, template.TemplateId, status: "skipped", - errMsg: "字段映射为空或无效", + errMsg: result.Message, cancellationToken: cancellationToken); - return; + return result; } var url = await BuildUrlAsync(template.UrlTemplate, order, cancellationToken); + result.Url = url; + result.RequestUrl = WechatTemplateSendUrl; + + var wechatRequest = BuildWechatRequestBody(openId, template.TemplateId.Trim(), url, data); + result.RequestBody = OmsDocHelper.SerializeJson(wechatRequest); + var payloadJson = OmsDocHelper.SerializeJson(new { openId, @@ -198,13 +243,21 @@ public class WechatOrderNotifyDispatcher( data, cancellationToken); + result.Skipped = false; + result.Success = sendResult.Success; + result.Status = sendResult.Success ? "sent" : "failed"; + result.WxMsgId = sendResult.MsgId; + result.ErrCode = sendResult.ErrCode == 0 ? null : sendResult.ErrCode; + result.Message = sendResult.Success ? "发送成功" : (sendResult.ErrMsg ?? "发送失败"); + result.ResponseBody = BuildWechatResponseBody(sendResult); + await WriteLogAsync( order, customerId, normalized, openId, template.TemplateId, - status: sendResult.Success ? "sent" : "failed", + status: result.Status, errCode: sendResult.ErrCode == 0 ? null : sendResult.ErrCode, errMsg: sendResult.Success ? null : sendResult.ErrMsg, wxMsgId: sendResult.MsgId, @@ -220,6 +273,62 @@ public class WechatOrderNotifyDispatcher( sendResult.ErrCode, sendResult.ErrMsg); } + + return result; + } + + private static object BuildWechatRequestBody( + string openId, + string templateId, + string? url, + IReadOnlyDictionary data) + { + var dataPayload = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (key, item) in data) + { + if (string.IsNullOrWhiteSpace(key)) + { + continue; + } + + dataPayload[key] = string.IsNullOrWhiteSpace(item.Color) + ? new { value = item.Value ?? string.Empty } + : new { value = item.Value ?? string.Empty, color = item.Color }; + } + + return string.IsNullOrWhiteSpace(url) + ? new + { + touser = openId, + template_id = templateId, + data = dataPayload + } + : new + { + touser = openId, + template_id = templateId, + url, + data = dataPayload + }; + } + + private static string BuildWechatResponseBody(WeChatMpTemplateSendResult sendResult) + { + if (sendResult.Success) + { + return OmsDocHelper.SerializeJson(new + { + errcode = 0, + errmsg = "ok", + msgid = sendResult.MsgId + }) ?? "{}"; + } + + return OmsDocHelper.SerializeJson(new + { + errcode = sendResult.ErrCode, + errmsg = sendResult.ErrMsg ?? "failed" + }) ?? "{}"; } private static Dictionary BuildPlaceholders( @@ -229,6 +338,7 @@ public class WechatOrderNotifyDispatcher( string? customerName) { var statusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus) ?? order.OrderStatus; + var issueContent = FirstNonEmpty(order.IssueContent, order.IssueTitle, remark); return new Dictionary(StringComparer.OrdinalIgnoreCase) { ["serviceNo"] = order.ServiceNo ?? string.Empty, @@ -239,11 +349,41 @@ public class WechatOrderNotifyDispatcher( ["eventName"] = eventName, ["eventTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ["remark"] = string.IsNullOrWhiteSpace(remark) ? eventName : remark.Trim(), - ["customerName"] = customerName ?? string.Empty, // 客户名称,可空 + ["customerName"] = customerName ?? string.Empty, ["consigneeCountry"] = order.ConsigneeCountry ?? string.Empty, + // 待支付:客户应付金额(两位小数) + ["payableAmount"] = FormatAmount(order.PayableAmount), + // 问题件:内容 / 标题 + ["issueContent"] = issueContent, + ["issueTitle"] = order.IssueTitle?.Trim() ?? string.Empty, + ["issueRemark"] = order.IssueRemark?.Trim() ?? string.Empty, + // 关键节点时间(订单字段:ReceiveTime / ShipTime / SignTime) + ["inboundTime"] = FormatDateTime(order.ReceiveTime), + ["outboundTime"] = FormatDateTime(order.ShipTime), + ["signTime"] = FormatDateTime(order.SignTime), + ["payTime"] = FormatDateTime(order.PayTime), }; } + private static string FormatAmount(decimal? amount) => + amount.HasValue ? amount.Value.ToString("0.00") : string.Empty; + + private static string FormatDateTime(DateTime? value) => + value.HasValue ? value.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty; + + private static string FirstNonEmpty(params string?[] values) + { + foreach (var value in values) + { + if (!string.IsNullOrWhiteSpace(value)) + { + return value.Trim(); + } + } + + return string.Empty; + } + private static Dictionary BuildTemplateData( string? fieldMappingJson, IReadOnlyDictionary placeholders) @@ -251,7 +391,6 @@ public class WechatOrderNotifyDispatcher( var result = new Dictionary(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrWhiteSpace(fieldMappingJson)) { - // 缺省映射:兼容常见 first/keyword/remark 模板 result["first"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("eventName") ?? ""); result["keyword1"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("serviceNo") ?? ""); result["keyword2"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("orderStatusName") ?? "");