File size: 2,173 Bytes
5bd4e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Stripe from "stripe";
import type { Ledger } from "./ledger.js";

export function makeStripe(secretKey: string): Stripe {
  if (!secretKey.startsWith("sk_test_") && !secretKey.startsWith("rk_test_")) throw new Error("Stripe TEST keys only");
  return new Stripe(secretKey);
}

export async function createFundingCheckout(stripe: Stripe, userId: string, amount: number, currency: string, successUrl: string, cancelUrl: string) {
  if (!Number.isSafeInteger(amount) || amount < 50 || amount > 100_000) throw new Error("amount must be 50..100000 minor units");
  return stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [{ quantity: 1, price_data: { currency, unit_amount: amount, product_data: { name: "ProjectOS wallet top-up (TEST)" } } }],
    metadata: { wallet_user_id: userId, purpose: "wallet_funding" },
    payment_intent_data: { metadata: { wallet_user_id: userId, purpose: "wallet_funding" } },
    success_url: successUrl, cancel_url: cancelUrl,
  });
}

export async function createFundingPaymentIntent(stripe: Stripe, userId: string, amount: number, currency: string) {
  if (!Number.isSafeInteger(amount) || amount < 50 || amount > 100_000) throw new Error("amount must be 50..100000 minor units");
  return stripe.paymentIntents.create({ amount, currency, automatic_payment_methods: { enabled: true },
    metadata: { wallet_user_id: userId, purpose: "wallet_funding" } });
}

/** Verifies signature (throws on mismatch) then credits the ledger idempotently. */
export async function handleWebhook(stripe: Stripe, ledger: Ledger, rawBody: Buffer, signature: string | undefined, secret: string) {
  if (!signature) throw new Error("missing stripe-signature header");
  const event = stripe.webhooks.constructEvent(rawBody, signature, secret);
  if (event.livemode) throw new Error("live-mode event rejected");
  if (event.type === "payment_intent.succeeded") {
    const pi = event.data.object as Stripe.PaymentIntent;
    if (pi.metadata?.purpose === "wallet_funding" && pi.metadata.wallet_user_id) {
      await ledger.recordFunding(pi.metadata.wallet_user_id, pi.amount_received, pi.currency, pi.id);
    }
  }
  return event;
}