# 商户通知与 Webhook

接收购买与用量的签名通知、验证签名，并处理 Funnel 外部任务回调。

[网页版本](https://www.longplayai.com/zh-hans/docs/guides/notifications)

<a id="setup"></a>

## 配置接收地址

本页配置 Longplay 向你的后端发送的商户通知。Stripe 向 Longplay 发送的支付 webhook 使用独立端点和签名密钥，按 Stripe 接入指南配置。

- [Stripe 接入](https://www.longplayai.com/zh-hans/docs/guides/stripe.md#webhook)

- 打开 Console 的 接入 → App 通知（`/workspace/developers?tab=notifications`），选择 App 和 Sandbox 环境。
- 填写 HTTPS 接收地址，点击 Generate signing key 生成签名密钥，保存到后端（如 `LONGPLAY_NOTIFICATION_KEY`）。
- 需要 `billing.*` 通知时打开 Billing events，然后启用接收地址并保存。

> 接收地址目前只能为 Sandbox 环境配置；开启前的历史事件不会补发。

<a id="events"></a>

## 事件类型

**通知类型**

| type | 何时发送 |
| --- | --- |
| `billing.purchase` | 一笔购买已支付并验证。 |
| `billing.updated` | Customer 的订阅或计费状态变化，例如付款后生效、变更套餐、续期、席位或额度调整。 |
| `billing.conflict` | 收到了付款，但这次购买与 Customer 现有的订阅冲突，没有授予权益。需要你处理，例如退款。 |
| `usage.consume` | 一次用量被记录。 |
| `usage.confirm` | 一笔预留被确认。 |
| `usage.refund` | 一笔用量被退回。 |
| `usage.limit` | 用量达到上限的设定比例（`manageBillingLimits` 的 `thresholds`）。 |
| `usage.allowance` | 用量达到套餐内额度的设定比例（`includedThresholds`）。 |
| `usage.alert` | 用量达到设定的数量（`absoluteThresholds`）。 |

- `billing.*` 事件只在开启 Billing events 后发送。
- 收到 `billing.updated` 或 `billing.conflict` 后，用 `readHoldings` 读取 Customer 的当前状态，不要只根据通知内容推断。
- 以后可能增加新的类型：对不处理的类型同样返回 2xx 并忽略。

<a id="delivery"></a>

## 请求格式

**notification.json**

```json
{
  "id": "<DELIVERY_UUID>",
  "type": "billing.purchase",
  "projectId": "<APP_UUID>",
  "environment": "sandbox",
  "customerId": "<CUSTOMER_UUID>",
  "occurredAt": "2026-10-22T08:00:00.000Z",
  "data": {}
}
```

**请求头**

| 请求头 | 内容 |
| --- | --- |
| `X-Indiana-Event-Id` | 事件 ID，等于请求体的 `id`，重试时不变。 |
| `X-Indiana-Signature` | `t=<Unix seconds>,v1=<HMAC-SHA256 hex>` |
| `X-Indiana-Key-Id` | 签名密钥 ID，轮换密钥时使用。 |

- 8 秒内返回 2xx；先保存事件，再异步处理。
- 同一事件可能收到多次，按事件 ID 去重。非 2xx 或超时会重新投递，包括第一次在内最多 10 次。
- 请求体不超过 64 KiB，金额与数量是十进制字符串。

<a id="verify"></a>

## 验证签名

用 Base64URL 解码后的密钥，对 `<时间戳>.<原始请求体>` 计算 HMAC-SHA256，与 `v1` 比较，并拒绝超过 5 分钟的时间戳。必须使用原始请求字节。

**TypeScript: app/api/indiana/route.ts**

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

const key = Buffer.from(process.env.LONGPLAY_NOTIFICATION_KEY!, "base64url");
const toleranceSeconds = 300;

/** rawBody must be the exact request bytes, read before any JSON parsing. */
export function verifyLongplaySignature(rawBody: Buffer, header: string | null) {
  const parts = Object.fromEntries(
    (header ?? "").split(",").map((part) => part.split("=", 2)),
  );
  const timestamp = Number(parts.t);
  if (!Number.isSafeInteger(timestamp) || !parts.v1) return false;
  if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false;
  const expected = createHmac("sha256", key)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest();
  const received = Buffer.from(parts.v1, "hex");
  return received.length === expected.length && timingSafeEqual(received, expected);
}

// Your own storage: returns false when this event ID was already recorded.
declare function recordOnce(eventId: string, event: unknown): Promise<boolean>;

export async function POST(request: Request) {
  const rawBody = Buffer.from(await request.arrayBuffer());
  if (!verifyLongplaySignature(rawBody, request.headers.get("X-Indiana-Signature")))
    return new Response("invalid signature", { status: 401 });
  const event = JSON.parse(rawBody.toString("utf8")) as { id: string; type: string };
  await recordOnce(event.id, event); // persist first, process asynchronously
  return new Response(null, { status: 200 });
}
```

**Python: webhooks.py**

```python
import base64
import hashlib
import hmac
import os
import time

KEY = base64.urlsafe_b64decode(os.environ["LONGPLAY_NOTIFICATION_KEY"] + "=")
TOLERANCE_SECONDS = 300


def verify_longplay_signature(raw_body: bytes, header: str | None) -> bool:
    """raw_body must be the exact request bytes, read before JSON parsing."""
    parts = dict(p.split("=", 1) for p in (header or "").split(",") if "=" in p)
    try:
        timestamp = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - timestamp) > TOLERANCE_SECONDS:
        return False
    message = f"{timestamp}.".encode() + raw_body
    expected = hmac.new(KEY, message, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))
```

**Go: webhooks.go**

```go
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

const toleranceSeconds = 300

// DecodeKey decodes the 32-byte Base64URL signing key generated in Console.
func DecodeKey(value string) ([]byte, error) {
	return base64.RawURLEncoding.DecodeString(value)
}

// VerifyLongplaySignature checks X-Indiana-Signature over the exact request body.
func VerifyLongplaySignature(rawBody []byte, header string, key []byte, now time.Time) bool {
	var timestamp int64
	var signature []byte
	for _, part := range strings.Split(header, ",") {
		name, value, _ := strings.Cut(part, "=")
		switch name {
		case "t":
			timestamp, _ = strconv.ParseInt(value, 10, 64)
		case "v1":
			signature, _ = hex.DecodeString(value)
		}
	}
	age := now.Unix() - timestamp
	if timestamp == 0 || signature == nil || age > toleranceSeconds || age < -toleranceSeconds {
		return false
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(strconv.FormatInt(timestamp, 10) + "."))
	mac.Write(rawBody)
	return hmac.Equal(mac.Sum(nil), signature)
}
```

<a id="funnel-tasks"></a>

## 回应 Funnel 外部任务

Funnel 的外部任务节点会向同一接收地址发送 `funnel.task` 请求，签名方式相同。在 2xx 响应中返回 `outcome` 和 `data`；`data` 的字段必须与节点声明的输出一致，不超过 8 KiB。

**请求: task.request.json**

```json
{
  "type": "funnel.task",
  "eventId": "<RECEIPT_UUID>",
  "runId": "<RUN_UUID>",
  "nodeId": "<NODE_ID>",
  "visit": 1,
  "projectId": "<APP_UUID>",
  "environmentId": "<ENVIRONMENT_UUID>",
  "customerId": "<CUSTOMER_UUID>",
  "taskKey": "check_eligibility",
  "input": { "plan": "pro" }
}
```

**响应: task.response.json**

```json
{
  "outcome": "success",
  "data": { "eligible": true, "tier": "gold" }
}
```

429 和 5xx 会按节点设置重试（默认最多 4 次）；其他错误直接失败。按 `eventId` 去重。
