Derse dön

Özgün çalışan dosya

netlify/functions/mini-payment-webhook.mjs

Kodlardaki adlar ve çalışan örnek sayfalardaki metinler özgün halleriyle korunmuştur. Ders ve dosya açıklamaları bunları Türkçe olarak açıklar.

import Stripe from "stripe";
export const handler = async (event) => {
  if (event.httpMethod !== "POST") return { statusCode: 405, body: "Use POST" };
  const {
    STRIPE_SECRET_KEY,
    STRIPE_WEBHOOK_SECRET,
    STRIPE_PAYMENT_LINK_ID,
    SUPABASE_URL,
    SUPABASE_SECRET_KEY,
  } = process.env;
  if (
    !STRIPE_SECRET_KEY?.startsWith("sk_test_") ||
    !STRIPE_WEBHOOK_SECRET ||
    !STRIPE_PAYMENT_LINK_ID ||
    !SUPABASE_URL ||
    !SUPABASE_SECRET_KEY
  )
    return { statusCode: 503, body: "Test payment setup incomplete" };
  if ((event.body || "").length > 300000) return { statusCode: 413, body: "Too large" };
  const stripe = new Stripe(STRIPE_SECRET_KEY);
  let notification;
  try {
    const raw = Buffer.from(event.body || "", event.isBase64Encoded ? "base64" : "utf8");
    notification = stripe.webhooks.constructEvent(
      raw,
      event.headers?.["stripe-signature"],
      STRIPE_WEBHOOK_SECRET,
    );
  } catch {
    return { statusCode: 400, body: "Invalid signature" };
  }
  if (notification.livemode) return { statusCode: 400, body: "Test events only" };
  if (
    !["checkout.session.completed", "checkout.session.async_payment_succeeded"].includes(
      notification.type,
    )
  )
    return { statusCode: 200, body: "Ignored" };
  const session = notification.data.object;
  if (
    session.payment_link !== STRIPE_PAYMENT_LINK_ID ||
    session.payment_status !== "paid"
  )
    return { statusCode: 200, body: "No matching paid session" };
  if (
    typeof session.id !== "string" ||
    !Number.isInteger(session.amount_total) ||
    typeof session.currency !== "string"
  )
    return { statusCode: 400, body: "Invalid session" };
  try {
    const r = await fetch(
      SUPABASE_URL.replace(/\/$/, "") +
        "/rest/v1/payment_receipts?on_conflict=session_id",
      {
        method: "POST",
        headers: {
          apikey: SUPABASE_SECRET_KEY,
          "Content-Type": "application/json",
          Prefer: "resolution=ignore-duplicates,return=minimal",
        },
        body: JSON.stringify({
          session_id: session.id,
          amount: session.amount_total,
          currency: session.currency,
        }),
        signal: AbortSignal.timeout(10000),
      },
    );
    if (!r.ok) throw Error();
    return { statusCode: 200, body: "Receipt recorded or already present" };
  } catch {
    return { statusCode: 503, body: "Receipt storage unavailable; retry required" };
  }
};