发送服务器端事件

使用 Umami API 跟踪来自后端服务的事件。这对于记录发生在浏览器之外的操作非常有用,例如 webhook 事件、支付完成或后台作业结果。

何时使用服务器端跟踪

  • 支付 webhook:记录由 Stripe、PayPal 或其他支付处理器确认的购买。
  • API 操作:跟踪用户通过您的 API 执行操作时(例如移动应用事件)。
  • 后台作业:记录来自 cron 作业、电子邮件发送或数据处理管道的事件。
  • 导入历史数据:从另一个分析平台回填事件。

Using the Node Client

For Node.js backends, the easiest way is to use the Umami Node Client:

npm install @umami/node
import umami from '@umami/node';

umami.init({
  websiteId: 'your-website-id',
  hostUrl: 'https://your-umami.example.com',
});

// Track page views
await umami.track({ url: '/api/checkout', title: 'Checkout API' });

// 跟踪自定义事件
await umami.track({
  name: 'payment-received',
  data: {
    revenue: 49.99,
    currency: 'USD',
    plan: 'pro',
  },
});

直接使用 API

/api/send 发送带有事件负载的 POST 请求:

curl -X POST https://your-umami.example.com/api/send \
  -H "Content-Type: application/json" \
  -H "User-Agent: Mozilla/5.0 (Server)" \
  -d '{
    "payload": {
      "hostname": "example.com",
      "language": "en-US",
      "url": "/checkout",
      "website": "your-website-id",
      "name": "payment-received",
      "data": {
        "revenue": 49.99,
        "currency": "USD"
      }
    },
    "type": "event"
  }'

重要:需要有效的 User-Agent 头。没有该头的请求将被拒绝。

Python 示例

import requests

requests.post('https://your-umami.example.com/api/send', json={
    'payload': {
        'hostname': 'example.com',
        'language': 'en-US',
        'url': '/checkout',
        'website': 'your-website-id',
        'name': 'payment-received',
        'data': {
            'revenue': 49.99,
            'currency': 'USD',
        },
    },
    'type': 'event',
}, headers={
    'User-Agent': 'MyApp/1.0',
})

批量发送

要在单个请求中发送多个事件,请向 /api/batch 端点 POST 一个 JSON 数组。数组中的每个元素都与 /api/send 请求体的结构相同:

curl -X POST https://your-umami.example.com/api/batch \
  -H "Content-Type: application/json" \
  -H "User-Agent: Mozilla/5.0 (Server)" \
  -d '[
    {
      "type": "event",
      "payload": {
        "website": "your-website-id",
        "hostname": "example.com",
        "url": "/page-1",
        "name": "page-view"
      }
    },
    {
      "type": "event",
      "payload": {
        "website": "your-website-id",
        "hostname": "example.com",
        "url": "/page-2",
        "name": "page-view"
      }
    }
  ]'

每一项都会转发到 /api/send,因此支持相同的 type 值(eventidentifyperformance)和负载字段。响应会汇总该批次:

{
  "size": 2,
  "processed": 2,
  "errors": 0,
  "details": [],
  "cache": "..."
}

如果有任何项失败,errors 表示失败数量,details 会按数组中的 index 列出每个失败项。

提示

  • 服务端事件会显示在与客户端事件相同的仪表板中。如有需要,可使用事件名称或属性来区分它们。
  • 在通过支付 webhook 跟踪收入时,请使用 revenuecurrency 属性,这样数据就会显示在 收入 洞察中。
  • 对于高流量后端,建议对事件进行排队,并在发送时设置并发限制,以避免压垮你的实例。