feat: 微信订单通知试发返回请求响应明细并扩展模板占位符
All checks were successful
Build and Deploy / deploy (push) Successful in 1m21s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-11-21 10:01:30 +08:00
parent 63642dd13e
commit 569efca710
3 changed files with 214 additions and 23 deletions

View File

@ -61,3 +61,55 @@ public class TrialWechatOrderNotifyInput
/// <summary>运单号(OrderId 为空时使用)。</summary>
public string? ServiceNo { get; set; }
}
/// <summary>试发结果(含请求/响应明细,供运营排查)。</summary>
public class TrialWechatOrderNotifyResultOutput
{
/// <summary>是否最终发送成功。</summary>
public bool Success { get; set; }
/// <summary>是否跳过发送(未启用/未绑 OpenId 等)。</summary>
public bool Skipped { get; set; }
/// <summary>状态:sent / failed / skipped。</summary>
public string Status { get; set; } = "skipped";
/// <summary>说明或错误信息。</summary>
public string? Message { get; set; }
/// <summary>订单 Id。</summary>
public int OrderId { get; set; }
/// <summary>运单号。</summary>
public string? ServiceNo { get; set; }
/// <summary>事件码。</summary>
public string EventCode { get; set; } = string.Empty;
/// <summary>事件名。</summary>
public string? EventName { get; set; }
/// <summary>接收 OpenId。</summary>
public string? OpenId { get; set; }
/// <summary>微信模板 ID。</summary>
public string? TemplateId { get; set; }
/// <summary>跳转 URL。</summary>
public string? Url { get; set; }
/// <summary>微信接口地址(不含 access_token)。</summary>
public string? RequestUrl { get; set; }
/// <summary>发给微信的请求体 JSON。</summary>
public string? RequestBody { get; set; }
/// <summary>微信返回 JSON(或合成摘要)。</summary>
public string? ResponseBody { get; set; }
/// <summary>微信 msgid。</summary>
public string? WxMsgId { get; set; }
/// <summary>微信 errcode。</summary>
public int? ErrCode { get; set; }
}

View File

@ -84,10 +84,10 @@ public class WechatOrderNotifyConfigService : ApplicationService
}
/// <summary>
/// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId)。
/// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId);返回请求/响应明细。
/// </summary>
[HttpPost("/system/wechat-order-notify/trial-send")]
public async Task TrialSendAsync(
public async Task<TrialWechatOrderNotifyResultOutput> 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: "运营试发",

View File

@ -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<WechatOrderNotifyDispatcher> 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(
/// <summary>
/// 运营试发:返回请求/响应明细;业务跳过/失败不抛,异常仍向上抛。
/// </summary>
public Task<TrialWechatOrderNotifyResultOutput> NotifyDetailedAsync(
Order order,
string eventCode,
string? remark = null,
bool force = false,
CancellationToken cancellationToken = default) =>
NotifyCoreAsync(order, eventCode, remark, force, cancellationToken);
private async Task<TrialWechatOrderNotifyResultOutput> 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<string, WeChatMpTemplateDataItem> data)
{
var dataPayload = new Dictionary<string, object>(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<string, string> 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<string, string>(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<string, WeChatMpTemplateDataItem> BuildTemplateData(
string? fieldMappingJson,
IReadOnlyDictionary<string, string> placeholders)
@ -251,7 +391,6 @@ public class WechatOrderNotifyDispatcher(
var result = new Dictionary<string, WeChatMpTemplateDataItem>(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") ?? "");