MENU

問い合わせ


    【Next.jsで作るオンライン予約サービス 第8回】予約確認メールとキャンセル・返金(キャンセル規定・Stripeの返金・メール送信)

    (2026年10月29日 追記:記事どおりに再現できるよう、必要なコードと手順を追加しました)

    オンライン予約サービスで「予約したのに確認メールが届かない」「キャンセルしたのに返金がいつ戻るのか分からない」という問い合わせは、運営の負担になりやすい代表例です。この回では、予約が確定したら確認メールを送り、利用者がキャンセルしたときはキャンセル規定にもとづいて金額を決め、Stripe(ストライプ。クレジットカード決済などを提供する海外の決済サービス)で返金するところまでを作ります。

    「キャンセルされたら、返金は手作業になるの? 二重に返金してしまったり、返金に失敗したりしないか心配…」

    先に結論です。返金は「予約の状態を先に更新し、そのあと決済サービスに返金を頼む」順番で行い、失敗したときは記録を残して人が対応できるようにしておくのが堅実です。さらに、返金額は画面ではなくサーバーが規定から計算し、確認メールは「送った印を先に付けてから送る」ことで二重送信を防ぎます。

    前回の第7回(Webhookで予約を確定する)では、Stripe からの通知で仮予約を確定させ、支払い済みの事実を記録しました。今回はその続きで、確定した予約の「その後」を作ります。

    目次

    この回で作るもの:確認メールとキャンセル・返金の流れ

    作る機能は3つです。使ったバージョンは Next.js 16・Stripe の Node.js ライブラリ 23 で、この回で足すファイルの全文と、既存のファイルへの変更点は、各項目に載せています。

    機能内容主なファイル
    予約確認メール予約が確定した直後に1通だけ送る。送れなかった分は定期実行で送り直すlib/mailer.ts、lib/notify.ts
    キャンセル規定利用開始までの残り時間で返金の割合を決めるlib/cancellation.ts
    キャンセルと返金会員本人の確定済み予約だけを取り消し、Stripe に返金を頼むlib/cancel.ts、app/reservations/actions.ts

    あわせて、データベースに5つの列を足しました(drizzle/0007_cancel_refund.sql)。返金の宛先になる支払いのID、確認メールを送った日時、キャンセルした日時、返金額、返金の状況です。

    lib/schema.ts の reservations に次の5列を足します(+ が追加、- が削除)

    --- a/lib/schema.ts
    +++ b/lib/schema.ts
    @@ -70,6 +70,12 @@ export const reservations = pgTable(
         holdExpiresAt: timestamp("hold_expires_at", { withTimezone: true }), // 仮予約で枠を押さえておく期限
         stripeSessionId: text("stripe_session_id").unique(), // Stripe の決済ページ(Checkout Session)の ID
         paidAt: timestamp("paid_at", { withTimezone: true }), // 支払いを確認した日時(第7回)。確定の有無とは別に「お金が入った事実」を残す
    +    stripePaymentIntentId: text("stripe_payment_intent_id"), // 返金の宛先になる支払い(PaymentIntent)の ID(第8回)。支払い確認時に残す
    +    confirmationSentAt: timestamp("confirmation_sent_at", { withTimezone: true }), // 予約確認メールを送れた日時。null なら未送信(第8回)
    +    cancelledAt: timestamp("cancelled_at", { withTimezone: true }), // 利用者がキャンセルした日時(第8回)
    +    refundYen: integer("refund_yen"), // キャンセル規定で決まった返金額(円)。0 なら返金なし
    +    // 返金の状況。none=返金なし/requested=返金を依頼した(Stripe の応答待ち)/succeeded=返金できた/failed=返金に失敗した(人が対応する)
    +    refundStatus: text("refund_status", { enum: ["none", "requested", "succeeded", "failed"] }).notNull().default("none"),
         createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
       },
       // 「このスペースの、この日の予約」を速く探すための索引
    npm run db:generate -- --name=cancel_refund   # drizzle/0007_cancel_refund.sql が作られる
    npm run db:migrate

    📰 出典:Stripe ドキュメント「Create a refund」

    Stripe の返金は、支払い(PaymentIntent)または請求(Charge)を指定して作ります。一部だけを返金することもでき、すでに全額返金した支払いを再び返金しようとするとエラーになります(執筆時点:2026年10月)。

    キャンセル規定をコードで表す

    キャンセル規定は、「利用開始の7日前までは全額、3日前までは半額、それ以降は返金なし」というサンプルの決まりにしました。割合は事業者が決めることなので、数字は例です。大切なのは、規定を1か所のコードに集め、画面の表示・メール・返金のすべてが同じ関数を使うことです。画面とサーバーで計算が食い違うと、「画面では全額返金と出ていたのに半額だった」というトラブルになります。

    // lib/cancellation.ts
    // キャンセル規定。利用開始までの残り時間で、返金する割合が決まる。
    // 数字はサンプル用。実際の割合は事業者が決め、予約画面と利用規約に書いておく(特定商取引法に基づく表記も確認する)
    export const CANCELLATION_TIERS = [
      { hoursBefore: 7 * 24, percent: 100 }, // 利用開始の7日前まで: 全額
      { hoursBefore: 3 * 24, percent: 50 }, // 3日前まで: 半額
    ] as const;
    
    export type CancellationQuote = { allowed: boolean; refundYen: number; percent: number };
    
    // 返金額を決める。通信も DB も使わない純粋な関数なので、そのままテストできる。
    // 利用開始後のキャンセルは受け付けない。端数は切り捨て(事業者に不利にならない側)
    export function quoteCancellation(startsAt: Date, totalYen: number, now: Date = new Date()): CancellationQuote {
      const hoursLeft = (startsAt.getTime() - now.getTime()) / 3_600_000;
      if (hoursLeft <= 0) return { allowed: false, refundYen: 0, percent: 0 };
      const tier = CANCELLATION_TIERS.find((t) => hoursLeft >= t.hoursBefore);
      const percent = tier?.percent ?? 0;
      return { allowed: true, refundYen: Math.floor((totalYen * percent) / 100), percent };
    }

    通信もデータベースも使わない関数なので、そのままテストできます。端数は切り捨てにして、境界(ちょうど7日前、ちょうど3日前、利用開始の直前と直後)をテストで確かめています。

    返金は「先に記録、あとで返金」の順で行う

    キャンセルの処理で一番気をつけるのは順番です。

    1. 予約を「取消」にして、返金額と「返金を依頼中」を記録する(データベース)
    2. Stripe に返金を頼む(外部サービス)
    3. 成功したら「返金済み」、失敗したら「失敗」に更新する

    先に返金してからデータベースを更新すると、返金は済んだのに予約が確定のまま残り、同じ枠を使う人と二重になる恐れがあります。逆に、データベースの処理を開いたまま外部の通信を待つと、通信が遅いときに他の処理を巻き込みます。そこで、取消の記録は1つの更新文で済ませ、返金の通信はその外で行います。

    // lib/cancel.ts(抜粋)
      // 「確定のまま」の行だけを取消にする。条件に status を入れているので、2回目以降は 0 行になって失敗する
      const updated = await db
        .update(reservations)
        .set({ status: "cancelled", cancelledAt: now, refundYen: quote.refundYen, refundStatus: quote.refundYen > 0 ? "requested" : "none" })
        .where(and(eq(reservations.id, r.id), eq(reservations.userId, input.userId), eq(reservations.status, "confirmed")))
        .returning({ id: reservations.id });
      if (updated.length === 0) return { ok: false, reason: "not_cancellable" };
    
      if (quote.refundYen === 0)

    更新の条件に「いま確定している行」を入れているのがポイントです。ボタンを2回押された場合や、2つのタブから同時に送られた場合でも、取消に変えられるのは最初の1回だけで、返金も1回しか頼まれません(テストで同時に2回呼んで確かめています)。

    返金の通信と、失敗したときの扱いは次のとおりです。

    // lib/cancel.ts(抜粋)
      try {
        if (!r.paymentIntentId) throw new Error("支払い情報(PaymentIntent)が記録されていません");
        await refund({ reservationId: r.id, paymentIntentId: r.paymentIntentId, amountYen: quote.refundYen });
        await db.update(reservations).set({ refundStatus: "succeeded" }).where(eq(reservations.id, r.id));
        return { ok: true, reservationId: r.id, refundYen: quote.refundYen, refundStatus: "succeeded" };
      } catch (error) {
        await db.update(reservations).set({ refundStatus: "failed" }).where(eq(reservations.id, r.id));
        console.error(`要確認: 予約 ${r.id} の返金に失敗しました`, error instanceof Error ? error.message : error);
        return { ok: true, reservationId: r.id, refundYen: quote.refundYen, refundStatus: "failed" };
      }

    返金に失敗しても、取消は元に戻しません。利用者には「キャンセルは受け付けた。返金は運営が確認して連絡する」と伝え、運営側は返金の状況が「失敗」の予約を調べて対応します。Stripe への依頼そのものには、予約ごとの合言葉(Idempotency-Key)を付けています。通信が途中で切れて再送しても、同じ返金が二重に作られないようにするためです。

    取消と返金の処理をまとめた lib/cancel.ts の全文です(新しく作るファイル)。

    lib/cancel.ts の全文(63行)
    // lib/cancel.ts
    import { and, eq } from "drizzle-orm";
    import { quoteCancellation } from "./cancellation";
    import { getDb } from "./db";
    import { reservations, spaces } from "./schema";
    
    export type RefundFn = (input: { reservationId: number; paymentIntentId: string; amountYen: number }) => Promise<unknown>;
    
    export type CancelResult =
      | { ok: true; refundYen: number; refundStatus: "none" | "succeeded" | "failed"; reservationId: number }
      | { ok: false; reason: "not_found" | "not_cancellable" | "past" };
    
    // 会員本人の確定済みの予約をキャンセルする。
    // 1) 予約を「取消」にして返金額を記録する(ここまでを1つの SQL 文で行う。同時に2回押されても1回目だけが通る)
    // 2) そのあと Stripe に返金を頼む。失敗しても取消は戻さず、refund_status を failed にして人の対応を待つ
    //    (返金の通信中に DB のトランザクションを開いたままにしないため。返金の二重実行は Idempotency-Key で防ぐ)
    export async function cancelReservation(
      input: { id: number; userId: number },
      refund: RefundFn,
      now: Date = new Date(),
    ): Promise<CancelResult> {
      const db = getDb();
      const [r] = await db
        .select({ id: reservations.id, status: reservations.status, startsAt: reservations.startsAt, totalYen: reservations.totalYen, paymentIntentId: reservations.stripePaymentIntentId })
        .from(reservations)
        .where(and(eq(reservations.id, input.id), eq(reservations.userId, input.userId))) // 本人の予約だけ。他人の ID を指定しても「見つからない」になる
        .limit(1);
      if (!r) return { ok: false, reason: "not_found" };
      if (r.status !== "confirmed") return { ok: false, reason: "not_cancellable" };
    
      const quote = quoteCancellation(r.startsAt, r.totalYen ?? 0, now);
      if (!quote.allowed) return { ok: false, reason: "past" };
    
      // 「確定のまま」の行だけを取消にする。条件に status を入れているので、2回目以降は 0 行になって失敗する
      const updated = await db
        .update(reservations)
        .set({ status: "cancelled", cancelledAt: now, refundYen: quote.refundYen, refundStatus: quote.refundYen > 0 ? "requested" : "none" })
        .where(and(eq(reservations.id, r.id), eq(reservations.userId, input.userId), eq(reservations.status, "confirmed")))
        .returning({ id: reservations.id });
      if (updated.length === 0) return { ok: false, reason: "not_cancellable" };
    
      if (quote.refundYen === 0) return { ok: true, reservationId: r.id, refundYen: 0, refundStatus: "none" };
    
      try {
        if (!r.paymentIntentId) throw new Error("支払い情報(PaymentIntent)が記録されていません");
        await refund({ reservationId: r.id, paymentIntentId: r.paymentIntentId, amountYen: quote.refundYen });
        await db.update(reservations).set({ refundStatus: "succeeded" }).where(eq(reservations.id, r.id));
        return { ok: true, reservationId: r.id, refundYen: quote.refundYen, refundStatus: "succeeded" };
      } catch (error) {
        await db.update(reservations).set({ refundStatus: "failed" }).where(eq(reservations.id, r.id));
        console.error(`要確認: 予約 ${r.id} の返金に失敗しました`, error instanceof Error ? error.message : error);
        return { ok: true, reservationId: r.id, refundYen: quote.refundYen, refundStatus: "failed" };
      }
    }
    
    // 返金が済んでいない(依頼中・失敗)予約の数。運用の確認用
    export async function listRefundsToCheck() {
      const rows = await getDb()
        .select({ id: reservations.id, refundYen: reservations.refundYen, refundStatus: reservations.refundStatus, spaceName: spaces.name })
        .from(reservations)
        .innerJoin(spaces, eq(spaces.id, reservations.spaceId))
        .where(and(eq(reservations.status, "cancelled")));
      return rows.filter((r) => r.refundStatus === "requested" || r.refundStatus === "failed");
    }

    lib/payment.ts に、返金の関数を足します(+ が追加、- が削除)

    --- a/lib/payment.ts
    +++ b/lib/payment.ts
    @@ -74,3 +74,13 @@ export async function createCheckout(stripe: Pick<Stripe, "checkout">, input: Ch
       if (!session.url) throw new Error("Stripe から決済ページの URL が返りませんでした");
       return { sessionId: session.id, url: session.url };
     }
    +
    +// 返金する。返金先は「支払い(PaymentIntent)」で指定する。
    +// 同じ予約で通信を再送しても二重に返金されないよう、予約ごとの合言葉(Idempotency-Key)を付ける
    +export async function refundPayment(stripe: Pick<Stripe, "refunds">, input: { reservationId: number; paymentIntentId: string; amountYen: number }) {
    +  const refund = await stripe.refunds.create(
    +    { payment_intent: input.paymentIntentId, amount: input.amountYen, metadata: { reservationId: String(input.reservationId) } },
    +    { idempotencyKey: `refund-reservation-${input.reservationId}` },
    +  );
    +  return { refundId: refund.id, status: refund.status };
    +}

    📰 出典:Stripe ドキュメント「Idempotent requests」

    返金の宛先になる支払いのIDは、第7回の Webhook で支払いを確認するときに予約へ記録するよう足しました。会員が他人の予約IDを指定しても、検索の条件に「ログイン中の本人のID」が入っているので、「見つからない」と同じ扱いになります。

    lib/webhook.ts に次の変更を加えます(+ が追加、- が削除)。

    --- a/lib/webhook.ts
    +++ b/lib/webhook.ts
    @@ -53,6 +53,12 @@ export async function handleStripeEvent(event: Stripe.Event, now: Date = new Dat
       });
     }
     
    +// 返金の宛先になる支払い(PaymentIntent)の ID。Checkout Session では文字列、展開されていればオブジェクトで届く
    +function paymentIntentId(session: Stripe.Checkout.Session): string | null {
    +  const pi = session.payment_intent;
    +  return typeof pi === "string" ? pi : (pi?.id ?? null);
    +}
    +
     async function confirmPaidSession(tx: Tx, session: Stripe.Checkout.Session, now: Date): Promise<WebhookOutcome> {
       // 画面に戻ってきた時点ではなく、Stripe が「支払い済み」と伝えたときだけ確定する
       if (session.payment_status !== "paid") return "unpaid";
    @@ -68,7 +74,7 @@ async function confirmPaidSession(tx: Tx, session: Stripe.Checkout.Session, now:
       if (r.status === "confirmed") return "already_confirmed";
     
       if (r.status === "pending") {
    -    await tx.update(reservations).set({ status: "confirmed", paidAt: now }).where(and(eq(reservations.id, id), eq(reservations.status, "pending")));
    +    await tx.update(reservations).set({ status: "confirmed", paidAt: now, stripePaymentIntentId: paymentIntentId(session) }).where(and(eq(reservations.id, id), eq(reservations.status, "pending")));
         return "confirmed";
       }
     
    @@ -77,12 +83,12 @@ async function confirmPaidSession(tx: Tx, session: Stripe.Checkout.Session, now:
         // 失敗しても外側のトランザクション全体を壊さないよう、SAVEPOINT(入れ子のトランザクション)の中で試す
         try {
           await tx.transaction(async (inner) => {
    -        await inner.update(reservations).set({ status: "confirmed", paidAt: now }).where(eq(reservations.id, id));
    +        await inner.update(reservations).set({ status: "confirmed", paidAt: now, stripePaymentIntentId: paymentIntentId(session) }).where(eq(reservations.id, id));
           });
           return "revived";
         } catch (error) {
           if (!isExclusionViolation(error)) throw error;
    -      await tx.update(reservations).set({ paidAt: now }).where(eq(reservations.id, id)); // 支払いの事実だけ残す(返金対象の目印)
    +      await tx.update(reservations).set({ paidAt: now, stripePaymentIntentId: paymentIntentId(session) }).where(eq(reservations.id, id)); // 支払いの事実だけ残す(返金対象の目印)
           return "slot_lost";
         }
       }

    会員がキャンセルボタンを押したときの Server Action です。誰の予約かは、ログイン中の会員から決めます。

    // app/reservations/actions.ts
    "use server";
    
    import { revalidatePath } from "next/cache";
    import { redirect } from "next/navigation";
    import { getCurrentUser } from "@/lib/auth";
    import { cancelReservation } from "@/lib/cancel";
    import { sendCancellationMail } from "@/lib/notify";
    import { getStripe, refundPayment } from "@/lib/payment";
    
    // 予約のキャンセル。誰の予約かは URL や入力ではなく、ログイン中の会員から決める
    export async function cancelReservationAction(formData: FormData) {
      const user = await getCurrentUser();
      if (!user) redirect("/login");
    
      const id = Number(formData.get("id"));
      if (!Number.isInteger(id)) redirect("/reservations");
    
      const result = await cancelReservation({ id, userId: user.id }, (input) => refundPayment(getStripe(), input));
      if (!result.ok) redirect(`/reservations?cancel=${result.reason}`);
    
      await sendCancellationMail(result.reservationId, result.refundYen);
      revalidatePath("/reservations");
      redirect(`/reservations?cancel=done&refund=${result.refundStatus}`);
    }

    予約履歴の画面に、返金額を示したキャンセルボタンと結果の表示を足します。app/reservations/page.tsx に次の変更を加えます(+ が追加、- が削除)

    --- a/app/reservations/page.tsx
    +++ b/app/reservations/page.tsx
    @@ -2,7 +2,10 @@ import type { Metadata } from "next";
     import Link from "next/link";
     import { redirect } from "next/navigation";
     import { logout } from "@/app/login/actions";
    +import { cancelReservationAction } from "@/app/reservations/actions";
     import { getCurrentUser } from "@/lib/auth";
    +import { quoteCancellation } from "@/lib/cancellation";
    +import { formatYen } from "@/lib/format";
     import { listReservationsForUser } from "@/lib/reservations";
     
     export const dynamic = "force-dynamic";
    @@ -12,7 +15,20 @@ const statusLabel = { pending: "支払い待ち", confirmed: "確定", cancelled
     
     const jst = new Intl.DateTimeFormat("ja-JP", { dateStyle: "medium", timeStyle: "short", timeZone: "Asia/Tokyo" });
     
    -export default async function ReservationsPage() {
    +const cancelMessage: Record<string, string> = {
    +  done: "キャンセルを受け付けました。確認のメールをお送りしています。",
    +  not_found: "予約が見つかりませんでした。",
    +  not_cancellable: "この予約はキャンセルできません(すでにキャンセル済み、または確定していません)。",
    +  past: "利用開始後の予約はキャンセルできません。",
    +};
    +const refundMessage: Record<string, string> = {
    +  none: "返金はありません(キャンセル規定による)。",
    +  succeeded: "返金の手続きをしました。カードへの反映時期はカード会社によって異なります。",
    +  failed: "返金の手続きを完了できませんでした。運営側で確認し、改めてご連絡します。",
    +};
    +
    +export default async function ReservationsPage({ searchParams }: { searchParams: Promise<{ cancel?: string; refund?: string }> }) {
    +  const { cancel, refund } = await searchParams;
       const user = await getCurrentUser();
       if (!user) redirect("/login"); // 未ログインは入れない。画面ごとに必ずここで確認する
     
    @@ -21,15 +37,32 @@ export default async function ReservationsPage() {
         <main>
           <h1>予約履歴</h1>
           <p>{user.email} でログイン中</p>
    +      {cancel && cancelMessage[cancel] && (
    +        <p role="status">
    +          {cancelMessage[cancel]}
    +          {cancel === "done" && refund && refundMessage[refund] ? refundMessage[refund] : ""}
    +        </p>
    +      )}
           {rows.length === 0 ? (
             <p>予約はまだありません。</p>
           ) : (
             <ul>
    -          {rows.map((r) => (
    -            <li key={r.id}>
    -              {r.spaceName}/{jst.format(r.startsAt)} 〜 {jst.format(r.endsAt)}({statusLabel[r.status]})
    -            </li>
    -          ))}
    +          {rows.map((r) => {
    +            // 確定済みで、まだ始まっていない予約だけキャンセルできる。返金額は画面に出す前にサーバーで計算する
    +            const quote = r.status === "confirmed" ? quoteCancellation(r.startsAt, r.totalYen ?? 0) : undefined;
    +            return (
    +              <li key={r.id}>
    +                {r.spaceName}/{jst.format(r.startsAt)} 〜 {jst.format(r.endsAt)}({statusLabel[r.status]})
    +                {r.status === "cancelled" && r.refundYen ? `/返金 ${formatYen(r.refundYen)}` : ""}
    +                {quote?.allowed && (
    +                  <form action={cancelReservationAction}>
    +                    <input type="hidden" name="id" value={r.id} />
    +                    <button type="submit">キャンセルする(返金 {formatYen(quote.refundYen)}/{quote.percent}%)</button>
    +                  </form>
    +                )}
    +              </li>
    +            );
    +          })}
             </ul>
           )}
           <p>

    履歴に返金の状況を出すため、lib/reservations.ts に次の変更を加えます(+ が追加、- が削除)

    --- a/lib/reservations.ts
    +++ b/lib/reservations.ts
    @@ -111,6 +111,8 @@ export async function listReservationsForUser(userId: number) {
           endsAt: reservations.endsAt,
           status: reservations.status,
           totalYen: reservations.totalYen,
    +      refundYen: reservations.refundYen,
    +      refundStatus: reservations.refundStatus,
           spaceName: spaces.name,
         })
         .from(reservations)

    確認メールを1回だけ送る

    メールは、決済サービスの通知に比べて「送れなかった」が起きやすい処理です。送信サービスの一時的な不調、宛先の誤り、送信元の認証設定の不備などが原因です。そこで次の方針にしました。

    • 予約が確定した直後(Webhook の処理の後)に1通送る
    • 送信に失敗しても、Webhook は成功として返す(失敗で 500 を返すと、Stripe の再送は「処理済み」と判断されて送り直せないため)
    • 送れなかった予約は「未送信」のまま残し、定期実行(第7回で作った入口)で送り直す

    app/api/stripe/webhook/route.ts に次の変更を加えます(+ が追加、- が削除)。

    --- a/app/api/stripe/webhook/route.ts
    +++ b/app/api/stripe/webhook/route.ts
    @@ -1,8 +1,13 @@
    +import { sendConfirmationMail } from "@/lib/notify";
     import { getStripe } from "@/lib/payment";
     import { handleStripeEvent, verifyStripeEvent } from "@/lib/webhook";
     
     export const dynamic = "force-dynamic";
     
    +function appOrigin() {
    +  return (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
    +}
    +
     // Stripe が支払い結果を知らせてくる入口。利用者のブラウザではなく Stripe のサーバーから呼ばれる。
     // ログイン不要で誰でも URL を叩けるので、本物かどうかは署名だけで判断する
     export async function POST(request: Request) {
    @@ -22,6 +27,12 @@ export async function POST(request: Request) {
         if (outcome === "slot_lost" || outcome === "mismatch") {
           console.error(`要確認: ${event.id}(${event.type})の処理結果は ${outcome} です`); // 人が見る必要がある結果は、ログに必ず残す
         }
    +    if (outcome === "confirmed" || outcome === "revived") {
    +      // 確定したときだけ確認メールを送る。メールの失敗で 500 を返すと、Stripe の再送では「処理済み」になって送り直せないので、
    +      // ここでは例外を外に出さない(未送信の予約は定期実行で送り直す)
    +      const id = Number((event.data.object as { client_reference_id?: string | null }).client_reference_id);
    +      if (Number.isInteger(id)) await sendConfirmationMail(id, appOrigin());
    +    }
         return Response.json({ received: true, outcome });
       } catch (error) {
         // 2xx 以外を返すと Stripe が時間をおいて再送する。DB の一時的な不調ならここで拾い直せる

    定期実行の入口でも、未送信の確認メールを送り直します。app/api/cron/expire-holds/route.ts に次の変更を加えます(+ が追加、- が削除)

    --- a/app/api/cron/expire-holds/route.ts
    +++ b/app/api/cron/expire-holds/route.ts
    @@ -1,3 +1,4 @@
    +import { resendMissingConfirmations } from "@/lib/notify";
     import { expireStaleHolds } from "@/lib/reservations";
     
     export const dynamic = "force-dynamic";
    @@ -10,5 +11,7 @@ export async function GET(request: Request) {
         return Response.json({ error: "unauthorized" }, { status: 401 });
       }
       const expired = await expireStaleHolds();
    -  return Response.json({ expired });
    +  // ついでに、確認メールが未送信の予約へ送り直す(Webhook の直後に送れなかった分)
    +  const resent = await resendMissingConfirmations((process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, ""));
    +  return Response.json({ expired, resent });
     }

    二重送信を防ぐ工夫が、「送った印を先に付けてから送る」ことです。

    // lib/notify.ts(抜粋)
    export async function sendConfirmationMail(id: number, origin: string, send: Send = sendMail, now: Date = new Date()): Promise<"sent" | "skipped" | "failed"> {
      const db = getDb();
      const claimed = await db
        .update(reservations)
        .set({ confirmationSentAt: now })
        .where(and(eq(reservations.id, id), eq(reservations.status, "confirmed"), isNull(reservations.confirmationSentAt), isNotNull(reservations.contactEmail)))
        .returning({ id: reservations.id });
      if (claimed.length === 0) return "skipped";
    
      try {
        const r = await loadMailReservation(id);
        if (!r) throw new Error("宛先が無い予約です");
        await send(confirmationMail(r, origin));
        return "sent";
      } catch (error) {
        await db.update(reservations).set({ confirmationSentAt: null }).where(eq(reservations.id, id));
        console.error(`予約 ${id} の確認メールを送れませんでした`, error instanceof Error ? error.message : error);
        return "failed";
      }
    }

    通知が重なって届いたり、定期実行と Webhook が同時に動いたりしても、印を付けられるのは1つの処理だけです。送信に失敗したら印を外して、あとで再挑戦できるようにします。

    lib/notify.ts の全文です(新しく作るファイル)。キャンセル受付のメールもここから送ります。

    lib/notify.ts の全文(72行)
    // lib/notify.ts
    import { and, eq, isNotNull, isNull } from "drizzle-orm";
    import { getDb } from "./db";
    import { cancellationMail, confirmationMail, type MailReservation } from "./mail-templates";
    import { sendMail } from "./mailer";
    import { reservations, spaces } from "./schema";
    
    type Send = typeof sendMail;
    
    async function loadMailReservation(id: number): Promise<MailReservation | undefined> {
      const [r] = await getDb()
        .select({
          id: reservations.id,
          spaceName: spaces.name,
          startsAt: reservations.startsAt,
          endsAt: reservations.endsAt,
          totalYen: reservations.totalYen,
          contactName: reservations.contactName,
          email: reservations.contactEmail,
        })
        .from(reservations)
        .innerJoin(spaces, eq(spaces.id, reservations.spaceId))
        .where(eq(reservations.id, id))
        .limit(1);
      if (!r || !r.email) return undefined;
      return { ...r, totalYen: r.totalYen ?? 0, email: r.email };
    }
    
    // 予約確認メールを送る。送信済みの印(confirmation_sent_at)を先に付けてから送るので、
    // 通知が重なって届いても2通は送らない。送信に失敗したら印を外し、あとでやり直せるようにする
    export async function sendConfirmationMail(id: number, origin: string, send: Send = sendMail, now: Date = new Date()): Promise<"sent" | "skipped" | "failed"> {
      const db = getDb();
      const claimed = await db
        .update(reservations)
        .set({ confirmationSentAt: now })
        .where(and(eq(reservations.id, id), eq(reservations.status, "confirmed"), isNull(reservations.confirmationSentAt), isNotNull(reservations.contactEmail)))
        .returning({ id: reservations.id });
      if (claimed.length === 0) return "skipped";
    
      try {
        const r = await loadMailReservation(id);
        if (!r) throw new Error("宛先が無い予約です");
        await send(confirmationMail(r, origin));
        return "sent";
      } catch (error) {
        await db.update(reservations).set({ confirmationSentAt: null }).where(eq(reservations.id, id));
        console.error(`予約 ${id} の確認メールを送れませんでした`, error instanceof Error ? error.message : error);
        return "failed";
      }
    }
    
    // 確認メールが未送信の確定済み予約に、送り直す。定期実行(cron)から呼ぶ
    export async function resendMissingConfirmations(origin: string, send: Send = sendMail, now: Date = new Date()): Promise<number> {
      const rows = await getDb()
        .select({ id: reservations.id })
        .from(reservations)
        .where(and(eq(reservations.status, "confirmed"), isNull(reservations.confirmationSentAt), isNotNull(reservations.contactEmail)))
        .limit(50);
      let sent = 0;
      for (const { id } of rows) {
        if ((await sendConfirmationMail(id, origin, send, now)) === "sent") sent += 1;
      }
      return sent;
    }
    
    export async function sendCancellationMail(id: number, refundYen: number, send: Send = sendMail): Promise<void> {
      try {
        const r = await loadMailReservation(id);
        if (r) await send(cancellationMail(r, refundYen));
      } catch (error) {
        console.error(`予約 ${id} のキャンセルメールを送れませんでした`, error instanceof Error ? error.message : error);
      }
    }

    メールの文面は lib/mail-templates.ts にまとめます(新しく作るファイル)。

    // lib/mail-templates.ts
    import { formatYen } from "./format";
    
    const jst = new Intl.DateTimeFormat("ja-JP", { dateStyle: "long", timeStyle: "short", timeZone: "Asia/Tokyo" });
    
    export type MailReservation = {
      id: number;
      spaceName: string;
      startsAt: Date;
      endsAt: Date;
      totalYen: number;
      contactName: string | null;
      email: string;
    };
    
    const footer = "\nこのメールは送信専用です。ご不明点は、サービスの問い合わせ窓口へご連絡ください。";
    
    // 予約確認メール。予約番号と日時・金額、キャンセル規定の要点を入れる
    export function confirmationMail(r: MailReservation, origin: string) {
      return {
        to: r.email,
        subject: `【予約確定】${r.spaceName}(${jst.format(r.startsAt)})`,
        text: [
          `${r.contactName ?? "お客様"} 様`,
          "",
          "ご予約が確定しました。",
          "",
          `予約番号: ${r.id}`,
          `スペース: ${r.spaceName}`,
          `日時: ${jst.format(r.startsAt)} 〜 ${jst.format(r.endsAt)}`,
          `お支払い額: ${formatYen(r.totalYen)}`,
          "",
          "キャンセルについて: 利用開始の7日前まで全額、3日前まで半額を返金します。それ以降は返金できません。",
          `予約の確認・キャンセル: ${origin}/reservations`,
          footer,
        ].join("\n"),
      };
    }
    
    // キャンセル受付のメール。返金額と、返金が実際に戻るまでの目安の書き方に注意する(カード会社によって反映時期が違う)
    export function cancellationMail(r: MailReservation, refundYen: number) {
      return {
        to: r.email,
        subject: `【キャンセル受付】${r.spaceName}(${jst.format(r.startsAt)})`,
        text: [
          `${r.contactName ?? "お客様"} 様`,
          "",
          "次のご予約のキャンセルを受け付けました。",
          "",
          `予約番号: ${r.id}`,
          `スペース: ${r.spaceName}`,
          `日時: ${jst.format(r.startsAt)} 〜 ${jst.format(r.endsAt)}`,
          refundYen > 0
            ? `返金額: ${formatYen(refundYen)}(お支払いに使ったカードへ返金します。反映の時期はカード会社によって異なります)`
            : "返金額: なし(キャンセル規定により、返金の対象外です)",
          footer,
        ].join("\n"),
      };
    }

    送信そのものは、ライブラリを足さずに送信サービス(Resend)の HTTP API を呼ぶだけの小さな関数にしました。

    第5回で作った lib/mailer.ts を、次のように書き換えます(+ が追加、- が削除)

    --- a/lib/mailer.ts
    +++ b/lib/mailer.ts
    @@ -1,8 +1,43 @@
    -// メール送信の入口。実際の送信は第8回で作る。
    -// それまでは開発中だけ、送る代わりにサーバーのログへリンクを出す。本番でログに出すと誰でも見られかねないので、エラーにする
    -export async function sendLoginLink(email: string, url: string): Promise<void> {
    -  if (process.env.NODE_ENV === "production") {
    -    throw new Error("メール送信が設定されていません(第8回で作ります)");
    +// メール送信の入口。送信サービスには Resend の HTTP API を使う(ライブラリを足さず、fetch だけで呼ぶ)。
    +// 送信元のドメイン認証(SPF・DKIM)は Resend の画面で行う。この環境では実際に送っていないので、記事では「未確認」と書いた
    +export type Mail = { to: string; subject: string; text: string };
    +
    +export type Fetcher = (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number }>;
    +
    +export class MailNotConfiguredError extends Error {
    +  constructor() {
    +    super("RESEND_API_KEY / MAIL_FROM が設定されていません(.env.example を参照)");
       }
    -  console.log(`[開発用] ログイン用リンク(宛先 ${email})\n${url}`);
    +}
    +
    +// 送信に失敗したとき。メッセージには宛先も本文も入れない(ログに個人情報を残さないため)
    +export class MailSendError extends Error {
    +  constructor(readonly status: number) {
    +    super(`メール送信に失敗しました(HTTP ${status})`);
    +  }
    +}
    +
    +export async function sendMail(mail: Mail, fetcher: Fetcher = fetch, env: NodeJS.ProcessEnv = process.env): Promise<void> {
    +  const key = env.RESEND_API_KEY;
    +  const from = env.MAIL_FROM;
    +  if (!key || !from) {
    +    // 開発中だけは、送らずにサーバーのログへ出す。本番でログに出すと誰でも見られかねないので、エラーにする
    +    if (env.NODE_ENV === "production") throw new MailNotConfiguredError();
    +    console.log(`[開発用] メール(宛先 ${mail.to}/件名 ${mail.subject})\n${mail.text}`);
    +    return;
    +  }
    +  const res = await fetcher("https://api.resend.com/emails", {
    +    method: "POST",
    +    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    +    body: JSON.stringify({ from, to: [mail.to], subject: mail.subject, text: mail.text }),
    +  });
    +  if (!res.ok) throw new MailSendError(res.status);
    +}
    +
    +export async function sendLoginLink(email: string, url: string, send: typeof sendMail = sendMail): Promise<void> {
    +  await send({
    +    to: email,
    +    subject: "【ログイン用リンク】貸し会議室の予約サービス",
    +    text: `次のリンクを開き、画面のボタンを押すとログインできます(15分間・1回だけ有効)。\n\n${url}\n\n心当たりがない場合は、このメールを破棄してください。`,
    +  });
     }

    📰 出典:Resend ドキュメント「Send Email」

    エラーのメッセージには宛先も本文も入れていません。ログに個人情報が残らないようにするためです。開発中はメールを送らずにサーバーのログへ出し、本番で設定が無いときは黙って成功にせずエラーにします。

    .env.example に、メール送信の設定を足します。空のままなら、開発中はログに出すだけです(+ が追加、- が削除)

    --- a/.env.example
    +++ b/.env.example
    @@ -8,3 +8,6 @@ APP_URL=http://localhost:3000
     STRIPE_WEBHOOK_SECRET=
     # 定期実行の入口(/api/cron/expire-holds)を呼べる人を限る合言葉。長いランダムな文字列にする
     CRON_SECRET=
    +# メール送信(Resend)。API キーと、ドメイン認証を済ませた送信元アドレス。空のままなら開発中はログに出すだけ
    +RESEND_API_KEY=
    +MAIL_FROM=

    テストを足す

    キャンセル規定・キャンセルと返金・メール送信のテストを足し、決済と通知のテストに返金まわりの確認を足します。

    // tests/cancellation.test.ts
    import { describe, expect, it } from "vitest";
    import { quoteCancellation } from "@/lib/cancellation";
    
    const start = new Date("2026-12-10T01:00:00Z"); // JST 10:00
    const hoursBefore = (h: number) => new Date(start.getTime() - h * 3_600_000);
    
    describe("キャンセル規定", () => {
      it("7日前までは全額返金", () => {
        expect(quoteCancellation(start, 4400, hoursBefore(24 * 7))).toEqual({ allowed: true, refundYen: 4400, percent: 100 });
        expect(quoteCancellation(start, 4400, hoursBefore(24 * 30)).refundYen).toBe(4400);
      });
    
      it("7日前を過ぎて3日前までは半額", () => {
        expect(quoteCancellation(start, 4400, hoursBefore(24 * 7 - 1))).toEqual({ allowed: true, refundYen: 2200, percent: 50 });
        expect(quoteCancellation(start, 4400, hoursBefore(24 * 3)).refundYen).toBe(2200);
      });
    
      it("3日前を過ぎたら返金なし(キャンセル自体はできる)", () => {
        expect(quoteCancellation(start, 4400, hoursBefore(24 * 3 - 1))).toEqual({ allowed: true, refundYen: 0, percent: 0 });
      });
    
      it("半額の端数は切り捨てる", () => {
        expect(quoteCancellation(start, 3333, hoursBefore(24 * 4)).refundYen).toBe(1666);
      });
    
      it("利用開始後はキャンセルできない", () => {
        expect(quoteCancellation(start, 4400, start).allowed).toBe(false);
        expect(quoteCancellation(start, 4400, new Date(start.getTime() + 1000))).toEqual({ allowed: false, refundYen: 0, percent: 0 });
      });
    });

    tests/cancel.test.ts の全文です(新しく作るファイル)。返金は偽の関数に差し替えて確かめます。

    tests/cancel.test.ts の全文(149行)
    // tests/cancel.test.ts
    // キャンセル・返金・確認メールは DB につないで確かめる。DATABASE_URL が無い環境では飛ばす。
    import { eq } from "drizzle-orm";
    import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
    import { cancelReservation } from "@/lib/cancel";
    import { createDb } from "@/lib/db";
    import { resendMissingConfirmations, sendConfirmationMail } from "@/lib/notify";
    import { reservations, spaces, users } from "@/lib/schema";
    import { jstDateTime } from "@/lib/slots";
    
    const now = new Date("2026-12-01T00:00:00Z");
    
    describe.skipIf(!process.env.DATABASE_URL)("キャンセルと返金・確認メール(DB)", () => {
      const { db, client } = createDb();
      let spaceId = 0;
      let userId = 0;
      let otherUserId = 0;
    
      beforeAll(async () => {
        const [space] = await db
          .insert(spaces)
          .values({ slug: "test-cancel", name: "キャンセルテスト用", area: "テスト", description: "テスト用", capacity: 4, hourlyPriceYen: 1000 })
          .onConflictDoUpdate({ target: spaces.slug, set: { name: "キャンセルテスト用" } })
          .returning({ id: spaces.id });
        spaceId = space.id;
        const [u] = await db.insert(users).values({ email: "cancel-owner@example.com" }).onConflictDoUpdate({ target: users.email, set: { email: "cancel-owner@example.com" } }).returning({ id: users.id });
        const [o] = await db.insert(users).values({ email: "cancel-other@example.com" }).onConflictDoUpdate({ target: users.email, set: { email: "cancel-other@example.com" } }).returning({ id: users.id });
        userId = u.id;
        otherUserId = o.id;
      });
    
      afterAll(async () => {
        await db.delete(spaces).where(eq(spaces.slug, "test-cancel"));
        await db.delete(users).where(eq(users.email, "cancel-owner@example.com"));
        await db.delete(users).where(eq(users.email, "cancel-other@example.com"));
        await client.end();
      });
    
      // 確定済みの予約を作る。date は利用日(JST)
      async function confirmed(date: string, over: Partial<typeof reservations.$inferInsert> = {}) {
        await db.delete(reservations).where(eq(reservations.spaceId, spaceId));
        const [row] = await db
          .insert(reservations)
          .values({
            spaceId,
            userId,
            startsAt: jstDateTime(date, 10),
            endsAt: jstDateTime(date, 12),
            contactName: "テスト",
            contactEmail: "cancel-owner@example.com",
            attendees: 2,
            status: "confirmed",
            totalYen: 2000,
            stripePaymentIntentId: "pi_test_1",
            ...over,
          })
          .returning({ id: reservations.id });
        return row.id;
      }
      const rowOf = async (id: number) => (await db.select().from(reservations).where(eq(reservations.id, id)))[0];
    
      it("7日以上前のキャンセルは全額を返金し、予約は取消になる", async () => {
        const id = await confirmed("2026-12-20");
        const refund = vi.fn().mockResolvedValue({});
        const result = await cancelReservation({ id, userId }, refund, now);
        expect(result).toEqual({ ok: true, reservationId: id, refundYen: 2000, refundStatus: "succeeded" });
        expect(refund).toHaveBeenCalledWith({ reservationId: id, paymentIntentId: "pi_test_1", amountYen: 2000 });
        const row = await rowOf(id);
        expect(row.status).toBe("cancelled");
        expect(row.refundStatus).toBe("succeeded");
        expect(row.cancelledAt).toEqual(now);
      });
    
      it("取り消した枠は、他の人がまた予約できる", async () => {
        const id = await confirmed("2026-12-20");
        await cancelReservation({ id, userId }, vi.fn().mockResolvedValue({}), now);
        const [again] = await db
          .insert(reservations)
          .values({ spaceId, startsAt: jstDateTime("2026-12-20", 10), endsAt: jstDateTime("2026-12-20", 12), status: "pending", totalYen: 2000 })
          .returning({ id: reservations.id });
        expect(again.id).toBeGreaterThan(0);
      });
    
      it("返金なしの時期は Stripe を呼ばない", async () => {
        const id = await confirmed("2026-12-02");
        const refund = vi.fn();
        expect(await cancelReservation({ id, userId }, refund, now)).toMatchObject({ ok: true, refundYen: 0, refundStatus: "none" });
        expect(refund).not.toHaveBeenCalled();
      });
    
      it("返金に失敗しても取消は戻さず、failed と記録する", async () => {
        const id = await confirmed("2026-12-20");
        vi.spyOn(console, "error").mockImplementation(() => {});
        const result = await cancelReservation({ id, userId }, vi.fn().mockRejectedValue(new Error("stripe down")), now);
        expect(result).toMatchObject({ ok: true, refundStatus: "failed" });
        const row = await rowOf(id);
        expect(row.status).toBe("cancelled");
        expect(row.refundStatus).toBe("failed");
        expect(row.refundYen).toBe(2000);
      });
    
      it("支払い情報が記録されていない予約は、取消にして failed(人が対応)にする", async () => {
        const id = await confirmed("2026-12-20", { stripePaymentIntentId: null });
        vi.spyOn(console, "error").mockImplementation(() => {});
        const refund = vi.fn();
        expect(await cancelReservation({ id, userId }, refund, now)).toMatchObject({ ok: true, refundStatus: "failed" });
        expect(refund).not.toHaveBeenCalled();
      });
    
      it("他人の予約はキャンセルできない(見つからない扱い)", async () => {
        const id = await confirmed("2026-12-20");
        expect(await cancelReservation({ id, userId: otherUserId }, vi.fn(), now)).toEqual({ ok: false, reason: "not_found" });
        expect((await rowOf(id)).status).toBe("confirmed");
      });
    
      it("同時に2回キャンセルしても、返金は1回だけ", async () => {
        const id = await confirmed("2026-12-20");
        const refund = vi.fn().mockResolvedValue({});
        const results = await Promise.all([cancelReservation({ id, userId }, refund, now), cancelReservation({ id, userId }, refund, now)]);
        expect(results.filter((r) => r.ok)).toHaveLength(1);
        expect(refund).toHaveBeenCalledTimes(1);
      });
    
      it("利用開始後・確定前・取消済みの予約はキャンセルできない", async () => {
        const past = await confirmed("2026-11-20");
        expect(await cancelReservation({ id: past, userId }, vi.fn(), now)).toEqual({ ok: false, reason: "past" });
        const pending = await confirmed("2026-12-20", { status: "pending" });
        expect(await cancelReservation({ id: pending, userId }, vi.fn(), now)).toEqual({ ok: false, reason: "not_cancellable" });
      });
    
      it("確認メールは1回だけ送る(2回呼んでも2通目は送らない)", async () => {
        const id = await confirmed("2026-12-20");
        const send = vi.fn().mockResolvedValue(undefined);
        expect(await sendConfirmationMail(id, "https://example.com", send, now)).toBe("sent");
        expect(await sendConfirmationMail(id, "https://example.com", send, now)).toBe("skipped");
        expect(send).toHaveBeenCalledTimes(1);
        expect(send.mock.calls[0][0].to).toBe("cancel-owner@example.com");
        expect((await rowOf(id)).confirmationSentAt).toEqual(now);
      });
    
      it("送信に失敗したら未送信に戻り、あとで送り直せる", async () => {
        const id = await confirmed("2026-12-20");
        vi.spyOn(console, "error").mockImplementation(() => {});
        expect(await sendConfirmationMail(id, "https://example.com", vi.fn().mockRejectedValue(new Error("mail down")), now)).toBe("failed");
        expect((await rowOf(id)).confirmationSentAt).toBeNull();
        const send = vi.fn().mockResolvedValue(undefined);
        expect(await resendMissingConfirmations("https://example.com", send, now)).toBeGreaterThanOrEqual(1);
        expect((await rowOf(id)).confirmationSentAt).toEqual(now);
      });
    });
    // tests/mailer.test.ts
    import { describe, expect, it, vi } from "vitest";
    import { formatYen } from "@/lib/format";
    import { cancellationMail, confirmationMail } from "@/lib/mail-templates";
    import { MailNotConfiguredError, MailSendError, sendLoginLink, sendMail } from "@/lib/mailer";
    import { jstDateTime } from "@/lib/slots";
    
    const mail = { to: "hanako@example.com", subject: "件名", text: "本文" };
    const env = { RESEND_API_KEY: "re_test_dummy", MAIL_FROM: "予約 <noreply@example.com>" } as unknown as NodeJS.ProcessEnv;
    
    describe("メール送信", () => {
      it("Resend の API に、キーを Authorization ヘッダーに入れて送る", async () => {
        const fetcher = vi.fn().mockResolvedValue({ ok: true, status: 200 });
        await sendMail(mail, fetcher, env);
        const [url, init] = fetcher.mock.calls[0];
        expect(url).toBe("https://api.resend.com/emails");
        expect(init.headers.Authorization).toBe("Bearer re_test_dummy");
        expect(JSON.parse(init.body)).toEqual({ from: "予約 <noreply@example.com>", to: ["hanako@example.com"], subject: "件名", text: "本文" });
      });
    
      it("送信に失敗したら例外にする。メッセージに宛先や本文を含めない", async () => {
        const fetcher = vi.fn().mockResolvedValue({ ok: false, status: 422 });
        const error = await sendMail(mail, fetcher, env).catch((e) => e);
        expect(error).toBeInstanceOf(MailSendError);
        expect(error.message).not.toContain("hanako@example.com");
      });
    
      it("設定が無い本番ではエラー、開発中はログに出すだけで送信しない", async () => {
        const fetcher = vi.fn();
        await expect(sendMail(mail, fetcher, { NODE_ENV: "production" } as unknown as NodeJS.ProcessEnv)).rejects.toThrow(MailNotConfiguredError);
        const log = vi.spyOn(console, "log").mockImplementation(() => {});
        await sendMail(mail, fetcher, { NODE_ENV: "development" } as unknown as NodeJS.ProcessEnv);
        expect(fetcher).not.toHaveBeenCalled();
        expect(log).toHaveBeenCalled();
        log.mockRestore();
      });
    
      it("ログイン用リンクのメールにリンクが入る", async () => {
        const send = vi.fn().mockResolvedValue(undefined);
        await sendLoginLink("a@example.com", "https://example.com/login/verify?token=abc", send);
        expect(send.mock.calls[0][0].text).toContain("https://example.com/login/verify?token=abc");
      });
    });
    
    const r = {
      id: 42,
      spaceName: "渋谷Aルーム",
      startsAt: jstDateTime("2026-12-10", 10),
      endsAt: jstDateTime("2026-12-10", 12),
      totalYen: 4400,
      contactName: "山田花子",
      email: "hanako@example.com",
    };
    
    describe("メールの文面", () => {
      it("確認メールに予約番号・日時・金額・キャンセル規定・確認先が入る", () => {
        const m = confirmationMail(r, "https://example.com");
        expect(m.to).toBe("hanako@example.com");
        expect(m.subject).toContain("渋谷Aルーム");
        for (const word of ["予約番号: 42", "2026年12月10日", formatYen(4400), "7日前まで全額", "https://example.com/reservations"]) {
          expect(m.text).toContain(word);
        }
      });
    
      it("キャンセルメールは返金額の有無で文面が変わる", () => {
        expect(cancellationMail(r, 2200).text).toContain("返金額:");
        expect(cancellationMail(r, 2200).text).toContain(formatYen(2200));
        expect(cancellationMail(r, 0).text).toContain("返金の対象外");
      });
    });

    tests/payment.test.ts に次の変更を加えます(+ が追加、- が削除)。

    --- a/tests/payment.test.ts
    +++ b/tests/payment.test.ts
    @@ -56,3 +56,16 @@ describe("決済ページの作成", () => {
         await expect(createCheckout({ checkout: { sessions: { create } } } as never, input)).rejects.toThrow();
       });
     });
    +
    +describe("返金", () => {
    +  it("支払い(PaymentIntent)と金額を指定し、予約ごとの合言葉を付ける", async () => {
    +    const create = vi.fn().mockResolvedValue({ id: "re_1", status: "succeeded" });
    +    const { refundPayment } = await import("@/lib/payment");
    +    const result = await refundPayment({ refunds: { create } } as never, { reservationId: 42, paymentIntentId: "pi_1", amountYen: 2200 });
    +    expect(result).toEqual({ refundId: "re_1", status: "succeeded" });
    +    expect(create).toHaveBeenCalledWith(
    +      { payment_intent: "pi_1", amount: 2200, metadata: { reservationId: "42" } },
    +      { idempotencyKey: "refund-reservation-42" },
    +    );
    +  });
    +});

    tests/webhook.test.ts に次の変更を加えます(+ が追加、- が削除)。

    --- a/tests/webhook.test.ts
    +++ b/tests/webhook.test.ts
    @@ -47,11 +47,11 @@ const t0 = new Date("2026-12-01T00:00:00Z");
     let seq = 0;
     
     // Stripe から届く通知の形(必要な項目だけ)
    -function sessionEvent(type: string, session: { id: string; reservationId: number; amount: number; paid?: boolean }): Stripe.Event {
    +function sessionEvent(type: string, session: { id: string; reservationId: number; amount: number; paid?: boolean; paymentIntent?: string }): Stripe.Event {
       return {
         id: `evt_test_${++seq}_${Date.now()}`,
         type,
    -    data: { object: { id: session.id, client_reference_id: String(session.reservationId), amount_total: session.amount, payment_status: session.paid === false ? "unpaid" : "paid" } },
    +    data: { object: { id: session.id, client_reference_id: String(session.reservationId), amount_total: session.amount, payment_status: session.paid === false ? "unpaid" : "paid", payment_intent: session.paymentIntent ?? null } },
       } as unknown as Stripe.Event;
     }
     
    @@ -92,6 +92,12 @@ describe.skipIf(!process.env.DATABASE_URL)("支払い通知の処理(DB)", (
         expect(row.paidAt).toEqual(t0);
       });
     
    +  it("確定のとき、返金の宛先になる支払い(PaymentIntent)の ID を残す", async () => {
    +    const id = await pendingReservation("cs_test_pi");
    +    await handleStripeEvent(sessionEvent("checkout.session.completed", { id: "cs_test_pi", reservationId: id, amount: 2000, paymentIntent: "pi_test_123" }), t0);
    +    expect((await statusOf(id)).stripePaymentIntentId).toBe("pi_test_123");
    +  });
    +
       it("同じ通知(同じイベント ID)が2回届いても、2回目は何もしない", async () => {
         const id = await pendingReservation("cs_test_b");
         const event = sessionEvent("checkout.session.completed", { id: "cs_test_b", reservationId: id, amount: 2000 });

    次のコマンドで検査と起動をします。

    docker compose up -d   # データベースを起動(起動済みなら不要)
    export DATABASE_URL=postgres://yoyaku:yoyaku@localhost:5432/yoyaku
    npm run lint && npm run typecheck && npm test
    npm run build && npm start

    動作確認の方法と、確認できていないこと

    • 型チェック・ESLint・ビルドは成功しました。テストは98件が成功しています(キャンセル規定、メール送信、返金の呼び出し、キャンセルの同時実行、確認メールの二重送信防止など。データベースにつなぐ分はローカルのPostgreSQL 16で実行)。
    • ローカルの本番起動で、確定済みの予約に「キャンセルする(返金 ¥4,400/100%)」ボタンが表示され、押すと予約が取消になることを確認しました。このときは Stripe のキーを設定していないため、返金は「失敗」として記録され、画面に「運営側で確認する」旨が出ることも確認しています。
    • 未確認:Stripe の実際の返金(テストモードを含む)、Resend での実際のメール送信、送信元ドメインの認証、メールの到達率。この環境ではキーとドメインが無いため、公式ドキュメントの仕様どおりに書いたものです。
    • このビルドは、環境の都合で next build --webpack を使いました(標準の Turbopack のネイティブ部分がこの環境で読み込めないため)。

    つまずきやすい点・省略したこと

    • 返金の反映時期:返金を依頼してから、利用者のカード明細に反映されるまでの期間は、カード会社によって異なります。メールには「反映の時期はカード会社によって異なります」と書くにとどめ、日数は断定しません。
    • 一部返金と手数料:Stripe の決済手数料が返金時にどう扱われるかは、契約やプランによります。経理に関わるので、事前に確認が必要です。
    • キャンセル後の再予約:取り消した枠は、第6回で作った排他制約の条件(支払い待ちと確定だけが対象)により、すぐ他の人が予約できます。テストで確かめています。
    • 省略したこと:管理者による代理キャンセル、返金の失敗を知らせる通知(監視)、領収書・請求書のメール、メールの再送上限と配信停止の扱いは作っていません。「返金が失敗」の予約を探す関数(listRefundsToCheck)だけ用意しています。

    発注者向けメモ:キャンセルと返金を開発会社に頼むときの確認点

    キャンセルと返金は、お金と信用に直結するのに、見積もりの段階では見落とされやすい部分です。次の点を確認すると安心です。

    • ☐ キャンセル規定(いつまでに何%返金か)を、事業者側で決めて、予約画面と利用規約に書いてあるか
    • ☐ 返金額を、画面ではなくサーバー側で計算しているか
    • ☐ ボタンの二度押しや同時操作で、二重に返金されない作りか
    • ☐ 返金が失敗したとき、誰が・どの画面で気づき、どう対応するかが決まっているか
    • ☐ 確認メールが届かなかったとき、送り直す仕組みがあるか。送信元ドメインの認証(SPF・DKIM)を誰が設定するか
    • ☐ メールの送信サービスの費用と、アカウントの契約者(発注者名義か)が決まっているか

    📰 出典:消費者庁「特定商取引法ガイド」

    インターネットで物やサービスを販売する場合は、特定商取引法の通信販売のルールが関わることがあります。キャンセルや返品の条件の表示が必要かどうかは、事業の内容によって変わりますので、最終的な判断は消費者庁のガイドや専門家に確認してください。

    開発会社への質問例です。

    • 「返金に失敗した予約は、どの画面で確認できますか? 運営の手間はどのくらいですか?」
    • 「キャンセル規定を変えたいときは、設定の変更だけで済みますか。それともコードの修正が必要ですか?」
    • 「確認メールの送信が止まったとき、どのくらいで気づけますか?」

    工数やリスクが増える条件は、キャンセル規定の種類が多い(スペースや日時で変わる)、一部返金や追加料金の精算、複数の決済方法(コンビニ払いなど返金方法が異なるもの)の併用、領収書の自動発行、メール文面の多言語対応などです。最初は「カード払い・規定は1種類」から始め、必要になってから広げるのが堅実です。

    まとめと次回予告

    この回では、予約が確定した後の運用に関わる部分を作りました。

    • 返金額は、1つの関数にまとめたキャンセル規定からサーバーが計算する
    • 予約を取消にする記録を先に行い、そのあと返金を頼む。失敗は記録して人が対応する
    • 返金の依頼には予約ごとの合言葉を付け、二重返金を防ぐ
    • 確認メールは「送った印を先に付けてから送る」ことで二重送信を防ぎ、送れなかった分は定期実行で送り直す

    次回の【第9回】は「管理画面を作る」です。スペースや料金の登録、予約の一覧、返金に失敗した予約の確認など、運営側が使う画面と、その権限の分け方を作ります。前の回は第7回 Webhookで予約を確定するです。

    この連載の記事一覧

    この記事は連載「Next.jsで作るオンライン予約サービス」の1回です。連載のほかの回は次のとおりです(連載の一覧ページ)。

    システム制作・運用・保守のお問い合わせはこちら


      よかったらシェアしてね!
      • URLをコピーしました!
      • URLをコピーしました!

      この記事を書いた人

      株式会社THIRD HERO代表取締役 朝野貴朗
      Webシステム開発を中心に、toC向けサービスサイトの運営、ツール開発などを行ってまいりました。

      コメント

      目次