Spaces:
Build error
Build error
| # 🚀 Stripe Integration - Resumen Rápido | |
| ## ¿Qué Se Agregó? | |
| ### ✨ Nuevas Funcionalidades | |
| 1. **Pagos con Stripe** 💳 | |
| - Checkout sessions | |
| - Validación de webhooks | |
| - Webhook handlers completos | |
| 2. **Renovación Automática** 🔄 | |
| - Mensual con fecha exacta | |
| - Sincronizado con Stripe | |
| - Rastreo en `nextRenewalDate` | |
| 3. **Cancelación del Cliente** ❌ | |
| - Cancelar suscripción en cualquier momento | |
| - Sincroniza con Stripe automáticamente | |
| - Responde en segundos | |
| 4. **Reportes Exactos** 📊 | |
| - Por influencer | |
| - Contabilidad por pago (`Earning` model) | |
| - Estados: active, paused, expired, cancelled | |
| ### 📂 Archivos Nuevos | |
| - `src/lib/stripe.ts` - Funciones helper Stripe | |
| - `src/app/api/payments/checkout/route.ts` - Generar sesión checkout | |
| - `src/app/api/payments/webhook/route.ts` - Recibir webhooks Stripe | |
| - `src/app/api/influencers/subscription/cancel/route.ts` - Cancelar suscripción | |
| ### 📝 Archivos Actualizados | |
| - `prisma/schema.prisma` - Nuevos campos Stripe+Earning | |
| - `src/app/api/influencers/subscription/route.ts` - Soporta renovación | |
| - `src/app/api/influencers/report/route.ts` - Reportes detallados | |
| --- | |
| ## ⚡ Quick Start | |
| ### 1. Migrar BD | |
| ```bash | |
| npx prisma migrate dev --name add_stripe_and_renewals | |
| ``` | |
| ### 2. Configurar .env | |
| ```env | |
| STRIPE_SECRET_KEY="sk_test_..." | |
| STRIPE_WEBHOOK_SECRET="whsec_..." | |
| ``` | |
| ### 3. Configurar Webhook en Stripe Dashboard | |
| - URL: `https://<tu-dominio>/api/payments/webhook` | |
| - Eventos: checkout.session.completed, invoice.payment_*, customer.subscription.* | |
| ### 4. Compilar y Testear | |
| ```bash | |
| npm run build # Compilar | |
| npm run dev # Iniciar servidor | |
| # En otra terminal: | |
| stripe listen --forward-to localhost:3000/api/payments/webhook | |
| stripe trigger checkout.session.completed | |
| ``` | |
| --- | |
| ## 🔑 Endpoints (API) | |
| ### Crear Suscripción | |
| ```bash | |
| POST /api/influencers/subscription | |
| Content-Type: application/json | |
| { | |
| "userId": "user123", | |
| "influencerId": "inf456", | |
| "tier": "premium", | |
| "price": 9.99 | |
| } | |
| ``` | |
| ### Iniciar Pago (Checkout) | |
| ```bash | |
| POST /api/payments/checkout | |
| Content-Type: application/json | |
| { | |
| "userId": "user123", | |
| "influencerId": "inf456", | |
| "tier": "premium", | |
| "price": 9.99 | |
| } | |
| Retorna: { sessionId, checkoutUrl } | |
| ``` | |
| ### Cancelar Suscripción | |
| ```bash | |
| POST /api/influencers/subscription/cancel | |
| Content-Type: application/json | |
| { | |
| "subscriptionId": "sub_12345", | |
| "userId": "user123" | |
| } | |
| ``` | |
| ### Obtener Reportes | |
| ```bash | |
| GET /api/influencers/report?influencerId=inf456&userId=user123 | |
| Retorna: | |
| { | |
| "subscribers": { active, paused, expired, cancelled }, | |
| "revenue": { completed, pending, failed }, | |
| "subscriptions": [...], | |
| "payments": [...] | |
| } | |
| ``` | |
| --- | |
| ## 📚 Documentación Completa | |
| - **[MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)** - Paso a paso migración BD + env | |
| - **[STRIPE_TESTING_GUIDE.md](./STRIPE_TESTING_GUIDE.md)** - Testear con Stripe CLI | |
| - **[VERIFICATION_CHECKLIST.md](./VERIFICATION_CHECKLIST.md)** - Pre-producción checklist | |
| --- | |
| ## 🔒 Seguridad | |
| ✅ Validación de firmas Stripe (HMAC-SHA256) | |
| ✅ Campos sensibles en `.env`, no en código | |
| ✅ `.gitignore` excluye `.env` | |
| ✅ Webhook endpoint validado | |
| --- | |
| ## 📊 Diagrama de Flujo | |
| ``` | |
| Cliente | |
| ↓ | |
| POST /api/payments/checkout | |
| ↓ | |
| Retorna checkoutUrl | |
| ↓ | |
| Cliente redirige a Stripe | |
| ↓ | |
| Cliente paga tarjeta | |
| ↓ | |
| Stripe → Webhook checkout.session.completed | |
| ↓ | |
| Server: Crea InfluencerSubscription + Earning | |
| ↓ | |
| Cliente: Suscripción activa | |
| ↓ | |
| (30 días después) | |
| ↓ | |
| Stripe: invoice.payment_succeeded | |
| ↓ | |
| Server: Crea nuevo Earning + actualiza nextRenewalDate | |
| ↓ | |
| Cliente: Renovación automática | |
| ``` | |
| --- | |
| ## ⚙️ Configuración BD | |
| ### InfluencerSubscription (Nueva: Stripe Fields) | |
| ```sql | |
| - stripeSubscriptionId TEXT | |
| - stripeCustomerId TEXT | |
| - nextRenewalDate DATETIME ← Próxima renovación | |
| - autoRenew BOOLEAN ← true = se renueva automático | |
| ``` | |
| ### Earning (Mejorado) | |
| ```sql | |
| - subscriptionId TEXT (FK) | |
| - stripePaymentIntentId TEXT | |
| - isRecurring BOOLEAN ← true = pago automático | |
| - paymentStatus ENUM ← pending|completed|failed | |
| - paymentMethod TEXT ← "stripe" | "manual" | |
| ``` | |
| --- | |
| ## 🧪 Testing Local | |
| ```bash | |
| # Terminal 1: Webhook listener | |
| stripe listen --forward-to localhost:3000/api/payments/webhook | |
| # Terminal 2: Servidor | |
| npm run dev | |
| # Terminal 3: Simular evento | |
| stripe trigger checkout.session.completed | |
| # Ver BD: | |
| npx prisma studio | |
| ``` | |
| --- | |
| ## 🚀 Deployment | |
| ```bash | |
| # VPS/Producción | |
| git push origin main | |
| # En VPS: | |
| npm install stripe | |
| npx prisma migrate deploy # Aplicar migraciones | |
| npm run build | |
| npm start | |
| # Actualizar .env con: | |
| # - STRIPE_SECRET_KEY=sk_live_... (VIVA, no test) | |
| # - STRIPE_WEBHOOK_SECRET=whsec_... (del webhook en producción) | |
| # - DATABASE_URL=<BD producción> | |
| ``` | |
| --- | |
| ## ✅ Status | |
| | Componente | Status | | |
| |-----------|--------| | |
| | Stripe SDK | ✅ Instalado | | |
| | BD Schema | ✅ Actualizado | | |
| | Endpoints | ✅ Implementados | | |
| | Webhooks | ✅ Validados | | |
| | Renovación | ✅ Automática | | |
| | Compilación | ✅ OK (28.4s) | | |
| | Testing | 📖 Ver STRIPE_TESTING_GUIDE.md | | |
| | BD Migration | 📖 Ver MIGRATION_GUIDE.md | | |
| --- | |
| **¿Listo?** Sigue los pasos en [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md) 🎯 | |