0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Stripeサブスクの状態がズレる問題を潰す:Webhookの冪等化・順序逆転・定期突き合わせの実装

0
Posted at

はじめに:「決済できたのに有料機能が使えない」

当社(合同会社ジョインクラス)は社員ゼロで、launchd の定期ジョブ17本とAIエージェントで会社を回しています。そのぶん「失敗が静かに積み上がる」怖さはよく知っています。macOS の cron がフルディスクアクセスの制限で全部止まっていたのに、しばらく誰も気づかなかったことがありました。

Stripe のサブスクリプションも同じ壊れ方をします。Webhook が1本落ちる、届く順番が入れ替わる、同じイベントが2回届く。どれもエラー画面は出ません。DB の plan 列が黙ってズレるだけです。

この記事では、僕が Next.js(App Router)+ Supabase 構成で Stripe サブスクを組むときに必ず入れている3つの防御策を、そのまま使えるコードで紹介します。

  1. 署名検証 + 冪等化(二重処理を防ぐ)
  2. ペイロードを信用せず API から取り直す(順序逆転を防ぐ)
  3. 定期的な突き合わせ(reconciliation)(取りこぼしを拾う)

注記:当社の .company/scripts/ にある運用スクリプトは bash/Python 製で、Stripe 連携は含まれていません。下の Stripe のコードは、Stripe 公式の API 仕様に沿って書いたリファレンス実装です。後半の「自動修復の上限」だけは、当社で実際に動いているスクリプトから引用しています。

前提スタック

  • Next.js 15(App Router, Node.js runtime)
  • stripe Node SDK
  • Supabase(Postgres)
  • Stripe CLI(ローカル検証用)

落とし穴1:署名検証で body をパースしてしまう

stripe.webhooks.constructEvent は 生の body 文字列 を前提にしています。先に req.json() を呼ぶと、JSON の再シリアライズで1バイトでも変われば署名検証が必ず失敗します。

落とし穴2:同じイベントが複数回届く

Stripe の配信は at-least-once です。2xx を返すのが遅いだけでも再送されます。event.id を一意キーにして、「処理済みなら何もしない」を DB 側で保証します。

-- supabase/migrations/20261111_stripe_events.sql
create table if not exists stripe_events (
  id text primary key,            -- Stripe の event.id (evt_...)
  type text not null,
  received_at timestamptz not null default now()
);

create table if not exists subscriptions (
  user_id uuid primary key references auth.users(id),
  stripe_customer_id text unique not null,
  stripe_subscription_id text unique,
  status text not null,           -- active / past_due / canceled ...
  price_id text,
  current_period_end timestamptz,
  updated_at timestamptz not null default now()
);

落とし穴3:イベントの順序は保証されない

customer.subscription.updated が created より先に届くことは普通にあります。ペイロードの data.object をそのまま書き込むと、古い状態で新しい状態を上書き してしまいます。

対策はシンプルです。Webhook は「何か変わった」という通知として扱い、最新状態は毎回 Stripe API から取り直します。 順序を気にする必要自体がなくなります。

Webhook ハンドラ(完成形)

// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { createClient } from "@supabase/supabase-js";

export const runtime = "nodejs"; // Edge では raw body の扱いが異なるため Node 固定

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const supabase = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!,
);

const HANDLED = new Set([
  "checkout.session.completed",
  "customer.subscription.created",
  "customer.subscription.updated",
  "customer.subscription.deleted",
  "invoice.payment_failed",
]);

export async function POST(req: Request) {
  const body = await req.text(); // json() にしない
  const signature = req.headers.get("stripe-signature");
  if (!signature) return new Response("missing signature", { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return new Response("invalid signature", { status: 400 });
  }

  if (!HANDLED.has(event.type)) return new Response("ignored", { status: 200 });

  // 冪等化:主キー衝突なら処理済み
  const { error: dupError } = await supabase
    .from("stripe_events")
    .insert({ id: event.id, type: event.type });
  if (dupError?.code === "23505") return new Response("duplicate", { status: 200 });
  if (dupError) return new Response("db error", { status: 500 });

  try {
    const subscriptionId = extractSubscriptionId(event);
    if (subscriptionId) await syncSubscription(subscriptionId);
  } catch (e) {
    // 失敗したら記録を消して Stripe に再送させる
    await supabase.from("stripe_events").delete().eq("id", event.id);
    console.error("[stripe-webhook]", event.id, e);
    return new Response("retry", { status: 500 });
  }
  return new Response("ok", { status: 200 });
}

function extractSubscriptionId(event: Stripe.Event): string | null {
  const obj = event.data.object as any;
  if (event.type === "checkout.session.completed") return obj.subscription ?? null;
  if (event.type.startsWith("customer.subscription.")) return obj.id;
  if (event.type === "invoice.payment_failed") return obj.subscription ?? null;
  return null;
}

// ペイロードは使わず、常に最新状態を API から取得して upsert
export async function syncSubscription(subscriptionId: string) {
  const sub = await stripe.subscriptions.retrieve(subscriptionId);
  const userId = sub.metadata.user_id; // Checkout 作成時に subscription_data.metadata で渡す
  if (!userId) throw new Error(`metadata.user_id missing: ${sub.id}`);

  const item = sub.items.data[0];
  const { error } = await supabase.from("subscriptions").upsert({
    user_id: userId,
    stripe_customer_id: sub.customer as string,
    stripe_subscription_id: sub.id,
    status: sub.status,
    price_id: item?.price.id ?? null,
    current_period_end: item?.current_period_end
      ? new Date(item.current_period_end * 1000).toISOString()
      : null,
    updated_at: new Date().toISOString(),
  });
  if (error) throw error;
}

設計上のポイントを3つ挙げます。

  • 処理に失敗したら stripe_events の行を消して 500 を返します。 冪等キーだけ残して処理が失敗すると、その後の再送が全部 duplicate 扱いになって永久に同期されません。これが一番ハマりやすい箇所です。
  • user_id は Checkout Session 作成時に subscription_data: { metadata: { user_id } } で埋め込みます。Session の metadata だけに入れると、Subscription 側には引き継がれません。
  • current_period_end は、新しめの API バージョンでは Subscription 直下ではなく subscription item 側にあります。使っている API バージョンのレスポンスを一度ダンプして確認してください。

有料判定は status で行う

// lib/billing.ts
const PAID = new Set(["active", "trialing"]);

export function isPaid(row: { status: string; current_period_end: string | null }) {
  if (PAID.has(row.status)) return true;
  // past_due は猶予期間中だけ使わせる(Smart Retries の期間に合わせる)
  if (row.status === "past_due" && row.current_period_end) {
    return new Date(row.current_period_end) > new Date();
  }
  return false;
}

canceled だけを見て「解約したかどうか」を判定するのは危険です。cancel_at_period_end: true の間は status が active のままで、期間が終わってから deleted イベントが届きます。

落とし穴4:Webhook が落ちたら誰も気づかない

デプロイ失敗やシークレットの入れ替えミスで、エンドポイントが数時間 4xx を返し続けることがあります。Stripe は最大3日間再送してくれますが、それを過ぎると取りこぼしは確定します。

そこで、Webhook とは独立した突き合わせジョブ を毎時回します。

// scripts/reconcile-subscriptions.ts
// 実行: npx tsx scripts/reconcile-subscriptions.ts
import Stripe from "stripe";
import { syncSubscription } from "../app/api/stripe/webhook/route";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

async function main() {
  // 直近2時間に更新されたイベントだけを見る(毎時実行で重複して窓を取る)
  const since = Math.floor(Date.now() / 1000) - 2 * 60 * 60;
  const ids = new Set<string>();

  for await (const event of stripe.events.list({
    created: { gte: since },
    types: ["customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted"],
    limit: 100,
  })) {
    ids.add((event.data.object as Stripe.Subscription).id);
  }

  let failed = 0;
  for (const id of ids) {
    try {
      await syncSubscription(id); // upsert なので何度流しても安全
    } catch (e) {
      failed++;
      console.error("[reconcile]", id, e);
    }
  }
  console.log(`[reconcile] synced=${ids.size - failed} failed=${failed}`);
  if (failed > 0) process.exit(1);
}

main();

syncSubscription が「API から取り直して upsert」なので、Webhook と突き合わせジョブが同時に走っても結果は同じになります。冪等性を最初に作っておくと、こういうところで効いてきます。

自動リトライには上限を付ける

突き合わせジョブ自体が失敗し続けるケースもあります。当社の監視スクリプト auto-monitor.sh では、自動修復を「連続失敗回数」と「1日1回」で打ち切り、人間に回すようにしています。実際のコードから抜粋します。

# .company/scripts/auto-monitor.sh より抜粋
# 修復してよいか判定する。不可なら理由を REPAIR_BLOCK_REASON に入れて1を返す
  REPAIR_BLOCK_REASON="自動修復が${failures}回続けて失敗したため修復を停止中。手動対応が必要"
  ...
  REPAIR_BLOCK_REASON="本日は修復済み(1日1回まで)。手動対応が必要"
  ...
  if ! can_repair "$1"; then add_job_issue "$1" "$REPAIR_BLOCK_REASON"; return; fi

決済も考え方は同じです。突き合わせで failed > 0 が N 回続いたら、自動で再試行するのはやめて通知だけにします。上限のない自動リトライは、障害を隠すだけになりがちです。

検証手順(その日のうちに試せます)

# 1. ローカルに Webhook を転送(表示される whsec_... を .env.local に設定)
stripe listen --forward-to localhost:3000/api/stripe/webhook

# 2. イベントを発火
stripe trigger customer.subscription.updated

# 3. 二重配信テスト:同じイベントを再送して duplicate が返ることを確認
stripe events resend evt_xxxxxxxxx

# 4. 順序逆転テスト:updated → created の順に手動 resend しても
#    subscriptions.status が最新値のままであることを確認

確認するポイントは次の4つです。

  • 同じ evt_ を2回送ったとき、2回目が duplicate になる
  • syncSubscription 内で例外を起こしたとき、stripe_events に行が残らず、再送で回復する
  • Stripe ダッシュボードでサブスクをキャンセルしたとき、status が canceled になる
  • Webhook エンドポイントを止めた状態で状態を変えても、突き合わせジョブを流せば DB が追いつく

まとめ

落とし穴 対策
署名検証が通らない req.text() で生 body を渡す
二重配信 event.id を主キーにして冪等化。失敗時は行を消す
順序逆転 ペイロードを使わず API から取り直す
取りこぼし 毎時の突き合わせジョブ + リトライ上限

当社が10事業を同時に回して9事業の売上がゼロだったとき、学んだのは「プロダクトの完成と売上は別物」ということでした。それでも、いざ売れ始めたときに課金状態がズレていたら信頼は一瞬でなくなります。決済まわりは地味な部分ですが、最初に固めておく価値があります。

関連書籍

今回の突き合わせジョブや自動修復の上限のように、「定期ジョブを壊れても自分で直る形で回す」設計は、『Claude Code 全自動化バイブル』で launchd・Hooks と組み合わせて詳しく解説しています。

書籍一覧はこちら → https://zenn.dev/joinclass?tab=books

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?