Spaces:
Build error
Build error
File size: 2,819 Bytes
3eebcd0 | 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | import Stripe from "stripe";
const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || "";
const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET || "";
export const stripe = new Stripe(STRIPE_KEY, { apiVersion: "2026-02-25.clover" });
// Crear sesi贸n de checkout para suscripci贸n
export async function createCheckoutSession({
userId,
influencerId,
influencerName,
tier,
price,
stripeCustomerId,
origin,
}: {
userId: string;
influencerId: string;
influencerName: string;
tier: string;
price: number;
stripeCustomerId?: string;
origin: string;
}): Promise<string> {
const session = await stripe.checkout.sessions.create({
customer: stripeCustomerId,
payment_method_types: ["card"],
mode: "subscription",
line_items: [
{
price_data: {
currency: "usd",
product_data: {
name: `Suscripci贸n a ${influencerName} - ${tier}`,
description: `Acceso a contenido exclusivo de ${influencerName}`,
metadata: {
influencerId,
userId,
influencerName,
},
},
recurring: {
interval: "month",
interval_count: 1,
},
unit_amount: Math.round(price * 100), // Convert to cents
},
quantity: 1,
},
],
metadata: {
userId,
influencerId,
tier,
},
success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${origin}/cancel`,
});
return session.id;
}
// Validar firma del webhook
export function validateWebhookSignature(body: string, signature: string): boolean {
if (!STRIPE_WEBHOOK_SECRET) return false;
try {
const event = stripe.webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET);
return true;
} catch {
return false;
}
}
// Parsear webhook event
export function parseWebhookEvent(body: string, signature: string) {
if (!STRIPE_WEBHOOK_SECRET) throw new Error("STRIPE_WEBHOOK_SECRET no configurado");
return stripe.webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET);
}
// Crear o obtener cliente Stripe
export async function getOrCreateStripeCustomer(
userId: string,
email: string,
name?: string
): Promise<string> {
const customers = await stripe.customers.list({ email, limit: 1 });
if (customers.data.length > 0) return customers.data[0].id;
const customer = await stripe.customers.create({
email,
name: name || undefined,
metadata: { userId },
});
return customer.id;
}
// Cancelar suscripci贸n en Stripe
export async function cancelStripeSubscription(stripeSubscriptionId: string) {
if (!stripeSubscriptionId) throw new Error("stripeSubscriptionId es requerido");
return stripe.subscriptions.cancel(stripeSubscriptionId);
}
|