调用 API 发送消息
业务系统对接 Herald 只需要记住两件事:
POST /v1/notify发消息,GET /v1/messages/{id}查结果。 这一页给出全部字段的可复制示例(带注释)、每种返回值的含义,以及五种语言的完整客户端代码。
端点与鉴权
text
POST {BASE}/v1/notify
Authorization: Bearer <token> # 会话 token 或 API Key
Content-Type: application/json
Idempotency-Key: <业务唯一键> # 可选,与 body 里的 idempotency_key 等价先拿 token(控制台账号或 API Key,见接入概览):
bash
BASE=http://127.0.0.1:8080
TOKEN=$(curl -sS -X POST "$BASE/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"123456"}' \
| sed -n 's/.*"token":"\([^"]*\)".*/\1/p')最小可用请求
bash
curl -sS -X POST "$BASE/v1/notify" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"route_id":"r-demo","payload":{"title":"hello","content":"world"}}'json
{ "message_id": "msg_01J…", "status": "queued", "created": true }三行就够了。下面从"每个字段能干什么"讲到"每种返回值意味着什么"。
全部字段(带注释)
把这段保存为 notify.json,删掉用不上的行就是你的请求体。
jsonc
{
// ── 必填 ──────────────────────────────────────────────
"route_id": "ops-alert", // 路由 ID:决定发给谁、走什么策略/工作流
// ── 幂等(强烈建议)────────────────────────────────────
"app_id": "billing", // 幂等作用域,缺省 "_";多业务方各自传,互不干扰
"idempotency_key": "order-1001", // 同一 (app_id, key) 重复提交:返回原消息,不重复发
// ── 消息内容 ──────────────────────────────────────────
"format": "markdown", // text(默认) | markdown | card | custom
"payload": {
"title": "支付超时率异常", // 短标题,短信/QQ 只剩它和 content
"content": "支付超时率 5.2%,请关注", // 纯文本正文,所有降级的最终兜底
"markdown": "**5.2%** 超时,持续 3 分钟。", // 富文本正文(format=markdown 时生效)
"card": { // 图文装饰:图片 + 按钮
"image": "https://example.com/chart.png",
"link": "https://grafana.example.com/d/abc",
"link_text": "打开看板"
},
"extras": { // 渠道私有富数据,按插件 id 分桶,换渠道不影响主结构
"dingtalk-robot": { "buttons": [{ "title": "认领", "url": "https://ops.example.com/t/1" }] }
}
},
// ── 接收方 ────────────────────────────────────────────
"targets": [ // 不传则用渠道配置的 default_target
{ "kind": "phone", "id": "13800000000" },
{ "kind": "email", "id": "ops@example.com" }
],
// ── 附件(只传引用,不传二进制)──────────────────────────
"attachments": [
{ "type": "image", "url": "https://push.example.com/v1/assets/ast_3fa2", "name": "lag.png" }
],
// ── 投递控制 ──────────────────────────────────────────
"priority": "urgent", // low | normal(默认) | high | urgent
"ttl": "2h", // 过期未投递的任务按失败落账(Go 时长)
"schedule_at": "2026-12-01T09:00:00+08:00", // 定时发送;与策略 delay/quiet_hours 取较晚者
// ── 模板/策略变量(字符串键值对)──────────────────────────
"variables": { "env": "prod", "team": "payments" }, // 供 conditional 表达式、dedup_key_expr、模板使用
"params": { "region": "cn-north" }, // 工作流入参:覆盖同名 payload 派生值,再补 spec.params 默认值
"metadata": { "ticket": "OPS-42" }, // 追踪/计费标签,不参与渲染,原样存档
// ── 结果回调 ──────────────────────────────────────────
"callback_url": "https://billing.example.com/hooks/herald", // 每条投递到终态时 POST
"callback_events": ["delivery.succeeded", "delivery.dead"], // 缺省订阅全部;也可传 ["all"]
// ── 聚合降噪(可选,仅策略路由)───────────────────────────
"digest": {
"window": "5m", // 窗口:>0 且 ≤1h,缺省 5m
"key": "payload.alert_name", // 分组表达式;空 = 按路由分组
"template": "「{{.key}}」5 分钟 {{.count}} 条:{{.summary}}" // 摘要文案(Go 模板)
},
// ── 预演 ──────────────────────────────────────────────
"dry_run": false // true = 只预演、零写入,返回将投递的渠道与备注
}字段冲突规则
dry_run: true时不写库、不发送、不占用去重键;digest与工作流路由互斥(工作流路由传digest返回 400);schedule_at/ 策略delay/quiet_hours三者取最晚的时刻生效;ttl从消息创建时刻算起,过期后投递按不可重试失败落账。
返回值:五种情况
1. 新消息入队(202)
jsonc
{
"message_id": "msg_01J9Z…", // 后续查回执、重放都用它
"status": "queued", // 初始状态;终态由投递推进
"created": true // true = 本次真的创建了新消息
}2. 幂等键命中(200)
jsonc
{
"message_id": "msg_01J9Z…", // 与首次相同
"created": false // 没有创建新消息,也没有新投递
}3. 策略去重窗口命中(200)
jsonc
{
"message_id": "msg_01J9Y…", // 窗口内首条消息的 ID
"created": false,
"deduped": true // 被路由的 dedup_window 判定为重复
}4. 干跑预演(200,零写入)
jsonc
{
"dry_run": true,
"preview": {
"route_id": "r-demo",
"strategy_type": "failover", // 策略类型;工作流路由为 workflow: true
"workflow": false,
"channels": [ // 将要投递的渠道与接收方
{ "id": "ch-sms", "provider_id": "sms-generic", "target": "13800000000" },
{ "id": "ch-mail", "provider_id": "email", "target": "ops@example.com" }
],
"scheduled_at": "2026-12-01T09:00:00+08:00",
"notes": [
"去重窗口 5m0s(同键窗口内只放行首条,dry-run 不占用去重键)",
"TTL 2h0m0s:到期未投递的任务按失败落账"
]
}
}5. 校验失败(400)
jsonc
{ "error": "route_id 必填" } // 也可能:路由不存在 / 已禁用 / 未绑渠道 / 插件未安装 / 字段非法4xx 不要重试(改请求);5xx 与连接错误按指数退避重试,且沿用同一个幂等键。详见错误与重试。
多语言客户端
四个客户端示例行为一致:环境变量取 BASE / TOKEN,带幂等键,打印状态码与响应体,只在 5xx/网络错误时重试;curl 那条只演示一次请求。
curl
bash
curl -sS -X POST "$BASE/v1/notify" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1001" \
-d '{
"app_id": "billing",
"route_id": "r-order",
"priority": "high",
"payload": { "title": "支付超时", "content": "订单 A1024 支付超时" }
}'Python(requests)
python
import os, time, requests
BASE = os.environ["BASE"]
TOKEN = os.environ["TOKEN"]
payload = {
"app_id": "billing",
"route_id": "r-order",
"idempotency_key": "order-1001", # 重试时保持不变
"priority": "high",
"payload": {"title": "支付超时", "content": "订单 A1024 支付超时"},
}
for attempt in range(4):
try:
resp = requests.post(
f"{BASE}/v1/notify",
headers={
"Authorization": f"Bearer {TOKEN}",
"Idempotency-Key": payload["idempotency_key"],
},
json=payload,
timeout=10,
)
except requests.RequestException as e:
last_err = e
else:
if resp.status_code in (200, 202):
print(resp.status_code, resp.json()) # 202=已入队;200=幂等命中/去重/预演
break
if resp.status_code < 500:
raise RuntimeError(f"{resp.status_code} {resp.text}") # 4xx 改请求,别重试
last_err = RuntimeError(f"{resp.status_code} {resp.text}")
time.sleep(0.2 * (2 ** attempt))
else:
raise RuntimeError(f"发送失败: {last_err}")Go(net/http)
go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type Target struct {
Kind string `json:"kind"`
ID string `json:"id"`
}
type NotifyRequest struct {
AppID string `json:"app_id,omitempty"`
RouteID string `json:"route_id"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
Format string `json:"format,omitempty"`
Priority string `json:"priority,omitempty"`
TTL string `json:"ttl,omitempty"`
Targets []Target `json:"targets,omitempty"`
Payload map[string]any `json:"payload,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
func main() {
base, token := os.Getenv("BASE"), os.Getenv("TOKEN")
reqBody := NotifyRequest{
AppID: "billing",
RouteID: "r-order",
IdempotencyKey: "order-1001",
Priority: "high",
Payload: map[string]any{"title": "支付超时", "content": "订单 A1024 支付超时"},
}
body, _ := json.Marshal(reqBody)
client := &http.Client{Timeout: 10 * time.Second}
var lastErr error
for attempt := 0; attempt < 4; attempt++ {
req, _ := http.NewRequest(http.MethodPost, base+"/v1/notify", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", reqBody.IdempotencyKey) // 重试沿用同一个键
resp, err := client.Do(req)
if err != nil {
lastErr = err
} else {
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
switch {
case resp.StatusCode == http.StatusAccepted || resp.StatusCode == http.StatusOK:
fmt.Println(resp.StatusCode, string(raw))
return
case resp.StatusCode < 500:
panic(fmt.Sprintf("%d %s", resp.StatusCode, raw)) // 4xx 不重试
default:
lastErr = fmt.Errorf("%d %s", resp.StatusCode, raw)
}
}
time.Sleep(time.Duration(200*(1<<attempt)) * time.Millisecond)
}
panic(lastErr)
}Java(Java 11+,无第三方依赖)
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Notify {
public static void main(String[] args) throws Exception {
String base = System.getenv("BASE");
String token = System.getenv("TOKEN");
String body = "{"
+ "\"app_id\":\"billing\","
+ "\"route_id\":\"r-order\","
+ "\"idempotency_key\":\"order-1001\","
+ "\"priority\":\"high\","
+ "\"payload\":{\"title\":\"支付超时\",\"content\":\"订单 A1024 支付超时\"}"
+ "}";
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
RuntimeException lastErr = null;
for (int attempt = 0; attempt < 4; attempt++) {
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(base + "/v1/notify"))
.timeout(Duration.ofSeconds(10))
.header("Authorization", "Bearer " + token)
.header("Content-Type", "application/json")
.header("Idempotency-Key", "order-1001") // 重试沿用同一个键
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
try {
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
int code = resp.statusCode();
if (code == 200 || code == 202) {
System.out.println(code + " " + resp.body());
return;
}
if (code < 500) {
throw new IllegalStateException(code + " " + resp.body()); // 4xx 不重试
}
lastErr = new RuntimeException(code + " " + resp.body());
} catch (java.io.IOException e) {
lastErr = new RuntimeException(e);
}
Thread.sleep(200L * (1L << attempt)); // 200/400/800/1600ms
}
throw lastErr;
}
}JavaScript(Node 18+ / 浏览器)
javascript
const BASE = process.env.BASE;
const TOKEN = process.env.TOKEN;
const payload = {
app_id: 'billing',
route_id: 'r-order',
idempotency_key: 'order-1001', // 重试时保持不变
priority: 'high',
payload: { title: '支付超时', content: '订单 A1024 支付超时' },
};
let lastErr;
for (let attempt = 0; attempt < 4; attempt++) {
try {
const res = await fetch(`${BASE}/v1/notify`, {
method: 'POST',
headers: {
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
'Idempotency-Key': payload.idempotency_key,
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10_000),
});
if (res.ok) {
console.log(res.status, await res.json()); // 202=已入队;200=幂等命中/去重/预演
return;
}
const text = await res.text();
if (res.status < 500) throw new Error(`${res.status} ${text}`); // 4xx 不重试
lastErr = new Error(`${res.status} ${text}`);
} catch (err) {
lastErr = err; // 网络错误可重试
}
await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
}
throw lastErr;发完之后:确认送达
202 只是"已入队"。确认送达有三条路:
bash
# 1) 主动查(排障首选,能看到每次尝试)
curl -sS "$BASE/v1/messages/msg_01J…" -H "Authorization: Bearer $TOKEN"jsonc
{
"id": "msg_01J…",
"status": "partially_sent", // queued | sending | sent | partially_sent | failed
"deliveries": [
{ "id": "out_…", "channel_id": "ch-sms", "provider_id": "sms-generic",
"status": "succeeded", "attempts": 1, "external_id": "sms-8891", "last_error": "" },
{ "id": "out_…", "channel_id": "ch-mail", "provider_id": "email",
"status": "dead", "attempts": 5, "last_error": "535 authentication failed" }
]
}- 配
callback_url:每条投递到终态时 POST 一次,带delivery.succeeded/delivery.dead事件与完整重试轨迹; - 控制台
/#/runs或/#/history直接看。
批量发送
bash
curl -sS -X POST "$BASE/v1/notify/batch" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"messages":[
{"route_id":"r-demo","payload":{"title":"A"}},
{"route_id":"r-demo","idempotency_key":"job-42","payload":{"title":"B"}}
]}'jsonc
{
"results": [
{ "index": 0, "message_id": "msg_…", "created": true, "deduped": false, "error": null },
{ "index": 1, "message_id": "msg_…", "created": true, "deduped": false, "error": null }
]
}批量接口逐条独立:某一条失败(比如 route_id 缺失)只影响该条的 error,不会整批回滚。
常见错误与处理
| 现象 | 原因 | 处理 |
|---|---|---|
400 route_id 必填 | 请求体缺路由 | 补 route_id |
400 路由 xxx 不存在 / 已禁用 | 路由 ID 错,或 enabled=false | GET /v1/admin/routes 核对 |
400 策略未选中渠道 | conditional 全假且没配 default_channels | 补兜底渠道 |
400 插件 xxx 未安装 | 渠道引用的插件被卸载 | 装回插件或换渠道 |
返回 created:false 且没有 deduped | 幂等键命中 | 正常行为,复用返回的 message_id |
投递 dead | 对端持续失败或不可重试错误 | 修渠道后 POST /v1/messages/{id}/replay |
消息一直 waiting | 命中了 quiet_hours 或 digest 窗口 | 看策略配置,或等窗口结束 |