# Notifications and webhooks

Receive signed purchase and usage notifications, verify signatures, and answer Funnel external task callbacks.

[Web version](https://www.longplayai.com/docs/guides/notifications)

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

## Set up a receiver

This page configures merchant notifications from Longplay to your backend. Payment webhooks from Stripe to Longplay use a separate endpoint and signing secret; configure them with the Stripe integration guide.

- [Connect Stripe](https://www.longplayai.com/docs/guides/stripe.md#webhook)

- Open Integrations → App notifications in Console (`/workspace/developers?tab=notifications`) and select the App and Sandbox environment.
- Enter an HTTPS receiver URL, click Generate signing key and store the key in your backend, for example as `LONGPLAY_NOTIFICATION_KEY`.
- Turn on Billing events if you need `billing.*` notifications, then enable the receiver and save.

> Receivers can currently be configured for Sandbox only; events from before enabling are not backfilled.

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

## Event types

**Notification types**

| type | Sent when |
| --- | --- |
| `billing.purchase` | A purchase is paid and verified. |
| `billing.updated` | A Customer's subscription or billing state changed, for example activation after payment, a plan change, renewal, or a seat or credit adjustment. |
| `billing.conflict` | A payment was received, but the purchase conflicts with the Customer's existing subscription and no access was granted. Handle it, for example with a refund. |
| `usage.consume` | Usage is recorded. |
| `usage.confirm` | A reservation is confirmed. |
| `usage.refund` | Usage is refunded. |
| `usage.limit` | Usage reaches a set share of its limit (`thresholds` in `manageBillingLimits`). |
| `usage.allowance` | Usage reaches a set share of the included allowance (`includedThresholds`). |
| `usage.alert` | Usage reaches a set quantity (`absoluteThresholds`). |

- `billing.*` events are sent only when Billing events is on.
- After `billing.updated` or `billing.conflict`, read the Customer's current state with `readHoldings` instead of inferring it from the notification.
- New types may be added: return 2xx for types you don't handle and ignore them.

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

## Request format

**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": {}
}
```

**Headers**

| Header | Content |
| --- | --- |
| `X-Indiana-Event-Id` | The event ID, equal to the body `id` and unchanged on retries. |
| `X-Indiana-Signature` | `t=<Unix seconds>,v1=<HMAC-SHA256 hex>` |
| `X-Indiana-Key-Id` | The signing key ID, used during key rotation. |

- Return 2xx within 8 seconds; store the event first and process it asynchronously.
- The same event can arrive more than once; deduplicate by event ID. Non-2xx responses and timeouts are redelivered, up to 10 attempts including the first.
- Bodies are at most 64 KiB; amounts and quantities are decimal strings.

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

## Verify the signature

Compute HMAC-SHA256 over `<timestamp>.<raw body>` with the Base64URL-decoded key, compare it with `v1`, and reject timestamps older than five minutes. Use the raw request bytes.

**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>

## Answer Funnel external tasks

A Funnel external task node sends a `funnel.task` request to the same receiver with the same signature. Return `outcome` and `data` in a 2xx response; `data` must match the node's declared outputs and stay within 8 KiB.

**Request: 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" }
}
```

**Response: task.response.json**

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

429 and 5xx are retried under the node settings (by default up to 4 attempts); other errors fail. Deduplicate by `eventId`.
