Webhook で NIHO のイベントを受け取る
会員登録や決済など、NIHO で起きたことを署名付き JSON で受け取れます。
はじめ方
- サーバーに HTTPS POST の受け口を用意します。実装言語とホスティングは自由です。
- ホスト管理のイベント連携、MCP、または管理 API から、送信先 URL・表示名・購読イベントを登録します。署名用の secret は発行・再発行時に一度だけ表示されるため、受け口の秘密管理に保存します。
- 生の本文で署名を検証し、イベント ID で重複を除きます。実際の受信と 2xx の応答を、受け口のログと NIHO の配信履歴で確認します。
MCP で登録・変更するときは、niho.outbound_connector_read で現在の設定を読み、niho.outbound_connector_upsert で変更を提案します。対象と送信データの範囲を確認して承認します。一時停止などの操作は MCP の一覧 から探せます。
イベント一覧
購読できるのは状態が「提供中」のイベントです。配信は発生時点の事実(FACT_EVENT)で、順序キーは subject 単位です。v1 に手動リプレイはありません。予約イベントは、連携先での配信が有効な場合に届きます。カタログの「提供中」と、配信する環境の設定は両方を確認してください。
| イベント | 状態 | subject | data の項目 |
|---|---|---|---|
会員が登録された(membership.member.created) |
提供中 | spot_member |
userId、spotMemberId |
リビングがフォローされた(membership.follower.created) |
提供中 | spot_member |
userId、spotMemberId |
予約が変化した(booking.state_changed) |
提供中 | booking |
bookingId、spotId、source、changeKind、aggregateVersion、bookingType、spaceScope、eventAudience、reservationStatus、startAt、endAt、headCount、organizerType、organizerUserId |
プラン契約が開始された(billing.contract.started) |
提供中 | spot_member |
userId、spotMemberId、membershipPlanId、contractId、amount、currency |
請求の支払いが成功した(billing.invoice.payment_succeeded) |
提供中 | user |
userId、stripeInvoiceId、attemptCount、amountPaid、currency |
請求の支払いが失敗した(billing.invoice.payment_failed) |
提供中 | user |
userId、stripeInvoiceId、attemptCount、amountDue、currency |
超過利用の支払いが失敗した(billing.usage_overage.payment_failed) |
提供中 | user |
userId、stripeInvoiceId、attemptCount、amountDue、currency |
契約状態が変更された(billing.contract.status_changed) |
提供中 | user |
userId、contractId、previousStatus、status、amount、currency |
支払いが返金された(billing.payment.refunded) |
提供中 | user |
userId、refundId、paymentIntentId、amountRefunded、currency |
お手伝い実行が記録された(help_task.execution.recorded) |
提供中 | task_execution |
taskDefinitionId、taskExecutionId、userId、executionMonth、recurrence、rewardMode、source |
会員がチェックインした(checkin.member.checked_in) |
提供中 | checkin_record |
checkinRecordId、userId、usageIntent、checkinMethod、checkinAt |
スタンプが押された(stampcard.press.recorded) |
提供中 | user |
cardId、userId、pressCount、goalCount、sourceType |
請求イベントは amountPaid、amountDue、amountRefunded または amount で、イベント発生時点の金額を表します。金額は最小通貨単位(JPY は円)、通貨は小文字の ISO 4217 です。member.billing.recurringAmount は配信時点の現行契約の継続請求額です。
送信データの範囲
identifiers_onlyは既定です。イベントの識別子と事実を送ります。予約イベントはこの範囲だけです。member_dataは対応する会員イベントで利用できます。オーナーの明示確認後にdata.memberを追加し、nihodataclassesがINTERNAL,CONFIDENTIALになります。
member は配信時点の状態なので、再送時に変わることがあります。会員行が見つからないか、ユーザーに deletedAt または purgedAt があるときは member: null です。会員状態が CANCELED でも会員行とユーザーがあれば状態付きで返ります。現行契約がなければ member.billing は null です。イベントの識別子と time は再送でも変わりません。受信したデータは受信側で管理し、削除する手順を用意してください。
届く形とヘッダー
CloudEvents 1.0 の structured JSON(application/cloudevents+json)です。イベントの中身は data、NIHO 固有のメタデータは niho* 拡張属性に入ります。
| ヘッダー | 用途 |
|---|---|
X-NIHO-Signature |
t=<Unix 秒>,v1=<HMAC-SHA256 の16進数> |
X-NIHO-Event-Id |
CloudEvents の id。重複排除に使う |
X-NIHO-Event-Type |
イベント種別 |
X-NIHO-Delivery-Id と X-NIHO-Attempt |
Delivery ID は再送中も同じ。Attempt は試行ごとに変わる |
配信リクエストの例
POST <あなたのURL>
Content-Type: application/cloudevents+json; charset=utf-8
{
"specversion": "1.0",
"id": "clv8x2p9k0000ab12cd34ef56", // イベントの安定ID(冪等キー)
"source": "urn:niho:spot:spot_xxxxxxxx",
"type": "billing.invoice.payment_failed",
"subject": "user_xxxxxxxx",
"time": "2026-07-15T09:12:03.000Z", // 発生時刻(UTC / ISO 8601)
"datacontenttype": "application/json",
"dataschema": "urn:niho:integration-event:billing.invoice.payment_failed:v1",
"nihoschemaversion": 1,
"nihodataclasses": "INTERNAL", // member_data 購読では "INTERNAL,CONFIDENTIAL"
"nihodeliveryid": "dlv_xxxxxxxx", // 同じ配信の再送中は安定
"nihoattemptid": "att_xxxxxxxx", // 再送の試行ごとに変わる
"data": {
"userId": "user_xxxxxxxx",
"stripeInvoiceId": "in_xxxxxxxx",
"attemptCount": 2,
"amountDue": 9800,
"currency": "jpy"
}
}
会員情報を含むデータ例(値はダミー)
// 会員イベント(spotMemberId を含むイベント)の member_data 例
// member_data profile が追加するのは member ブロックだけです。
// userId / spotMemberId などの識別子はイベントごとの契約に従います。
"data": {
"userId": "user_xxxxxxxx",
"spotMemberId": "member_xxxxxxxx",
"member": {
"displayName": "にほ たろう",
"fullName": "二歩 太郎",
"email": "taro@example.com",
"handle": "niho-taro",
"memberSince": "2026-01-15T03:04:05.000Z",
"joinChannel": "MEMBER_REFERRAL",
"memberLabel": "SUPPORTER",
"status": "ACTIVE", // PENDING / ACTIVE / CANCELED
"billingStatus": "CURRENT", // CURRENT / PAST_DUE / UNPAID / REQUIRES_ACTION
"membershipPlan": { "id": "plan_xxxxxxxx", "name": "月額メンバー" },
"billing": {
"stripeCustomerId": "cus_xxxxxxxx",
"stripeSubscriptionId": "sub_xxxxxxxx",
"contractStartedAt": "2026-02-01T00:00:00.000Z",
"billingMode": "CONNECT_DIRECT",
"recurringAmount": 9800,
"currency": "jpy"
}
}
}
// 会員行が見つからない、またはユーザーが deletedAt / purgedAt で消去済みのとき
"data": {
"userId": "user_xxxxxxxx",
"spotMemberId": "member_xxxxxxxx",
"member": null
}
署名を検証する
<t>.<JSON パース前の本文そのまま> を、base64url で配布された256 bit の secret で HMAC-SHA256 にかけます。署名の16進表記を定数時間比較し、時刻差が5分を超える要求を拒否します。secret の切り替え中は複数の v1= に対し、保持する secret で照合します。
TypeScript
// 生body(string)とヘッダを渡す。secretはNIHO発行のbase64url(256bit)
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyNihoWebhook(p: {
rawBody: string; signatureHeader: string;
secret: string; toleranceSeconds?: number;
}): boolean {
const parts = p.signatureHeader.split(",").map((s) => s.trim());
const t = Number(parts.find((s) => s.startsWith("t="))?.slice(2));
if (!Number.isSafeInteger(t)) return false;
const tol = p.toleranceSeconds ?? 300;
if (Math.abs(Math.floor(Date.now() / 1000) - t) > tol) return false;
const expected = createHmac("sha256", Buffer.from(p.secret, "base64url"))
.update(`${t}.${p.rawBody}`, "utf8").digest("hex");
return parts.filter((s) => s.startsWith("v1=")).map((s) => s.slice(3))
.some((sig) => /^[a-f0-9]{64}$/.test(sig) &&
timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex")));
}
Python
import hmac, hashlib, time, base64
def verify_niho_webhook(raw_body: bytes, signature_header: str,
secret_b64url: str, tolerance: int = 300) -> bool:
parts = [s.strip() for s in signature_header.split(",")]
t_part = next((s for s in parts if s.startswith("t=")), None)
if t_part is None: return False
try: t = int(t_part[2:])
except ValueError: return False
if abs(int(time.time()) - t) > tolerance: return False
secret = base64.urlsafe_b64decode(secret_b64url + "=" * (-len(secret_b64url) % 4))
signed = f"{t}.".encode() + raw_body # 生バイトで検証
expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
supplied = [s[3:] for s in parts if s.startswith("v1=")]
return any(hmac.compare_digest(sig, expected) for sig in supplied)
配信と再送
- at-least-once で配信します。記録した
X-NIHO-Event-Idと同じ ID は冪等にスキップします。 - 受理後は速やかに 2xx を返し、時間のかかる処理は非同期で行います。接続は5秒、全体は15秒でタイムアウトします。
- 408、429、5xx、接続失敗・タイムアウトは最大6時間まで指数バックオフで再送します。指定された
Retry-Afterを考慮します。 - 3xx と 408・429 以外の4xx は恒久失敗です。非2xxの応答本文が64 KiBを超えた場合も恒久失敗です。NIHO は応答本文を保存・解釈しません。
- 再送で同じ subject の配信順が前後することがあります。
booking.state_changedはbookingIdごとに受理したaggregateVersionの最大値を保持し、それ以下は破棄します。DELETEDとREJECTEDを tombstone として扱います。
バージョンと互換性
nihoschemaversion と dataschema の URN でイベントの schema 版を確認します。互換性のある追加は同じ版で行うので、受け口では未知のフィールドを無視してください。互換性を壊す変更は新しい版で案内し、旧版の移行期間と後継を示します。