michangarrito/docs/02-integraciones/INT-002-stripe.md
rckrdmrd 97f407c661 [MIGRATION-V2] feat: Migrar michangarrito a estructura v2
- Prefijo v2: MCH
- TRACEABILITY-MASTER.yml creado
- Listo para integracion como submodulo

Workspace: v2.0.0 | SIMCO: v4.0.0
2026-01-10 11:28:54 -06:00

319 lines
7.6 KiB
Markdown

---
id: INT-002
type: Integration
title: "Stripe"
provider: "Stripe"
status: Activo
integration_type: "payments"
created_at: 2026-01-04
updated_at: 2026-01-10
simco_version: "3.8.0"
tags:
- stripe
- payments
- subscriptions
- webhooks
---
# INT-002: Stripe
## Metadata
| Campo | Valor |
|-------|-------|
| **Codigo** | INT-002 |
| **Proveedor** | Stripe, Inc. |
| **Tipo** | Pagos / Suscripciones |
| **Estado** | Implementado |
| **Multi-tenant** | No (credenciales globales) |
| **Fecha integracion** | 2026-01-06 |
| **Ultimo update** | 2026-01-10 |
| **Owner** | Backend Team |
---
## 1. Descripcion
Stripe es el procesador de pagos para las suscripciones de MiChangarrito. Maneja el cobro mensual de los planes (Changarrito $99/mes, Tiendita $199/mes) y la compra de paquetes de tokens de IA.
**Casos de uso principales:**
- Cobro de suscripciones mensuales
- Venta de paquetes de tokens ($29-$299)
- Generacion de facturas
- Pago con OXXO para usuarios sin tarjeta
- Portal de cliente para gestionar suscripcion
---
## 2. Credenciales Requeridas
### Variables de Entorno
| Variable | Descripcion | Tipo | Obligatorio |
|----------|-------------|------|-------------|
| `STRIPE_API_KEY` | API Key (sk_test o sk_live) | string | SI |
| `STRIPE_WEBHOOK_SECRET` | Secret para validar webhooks | string | SI |
| `STRIPE_PRICE_CHANGARRITO` | Price ID plan Changarrito | string | SI |
| `STRIPE_PRICE_TIENDITA` | Price ID plan Tiendita | string | SI |
### Ejemplo de .env
```env
# Stripe
STRIPE_API_KEY=sk_test_xxxxxxxxxxxxxxxxxxxx
STRIPE_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxx
STRIPE_PRICE_CHANGARRITO=price_xxxxxxxxxxxxxxxxxxxx
STRIPE_PRICE_TIENDITA=price_xxxxxxxxxxxxxxxxxxxx
```
### Obtencion de Credenciales
1. Crear cuenta en [Stripe Dashboard](https://dashboard.stripe.com/)
2. Obtener API keys de Developers → API Keys
3. Crear Products y Prices para los planes
4. Configurar Webhook endpoint
---
## 3. Endpoints/SDK Utilizados
### Operaciones Implementadas
| Operacion | SDK Method | Descripcion |
|-----------|------------|-------------|
| Crear Customer | `stripe.customers.create()` | Crear cliente |
| Crear Subscription | `stripe.subscriptions.create()` | Iniciar suscripcion |
| Crear Checkout Session | `stripe.checkout.sessions.create()` | Pago one-time (tokens) |
| Portal de Cliente | `stripe.billingPortal.sessions.create()` | Gestionar suscripcion |
| Cancelar Suscripcion | `stripe.subscriptions.cancel()` | Cancelar |
### SDK Utilizado
```typescript
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: '2023-10-16',
});
// Crear suscripcion
const subscription = await stripe.subscriptions.create({
customer: customerId,
items: [{ price: process.env.STRIPE_PRICE_CHANGARRITO }],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent'],
});
```
---
## 4. Rate Limits
| Limite | Valor | Periodo | Accion si excede |
|--------|-------|---------|------------------|
| Read operations | 100 | por segundo | 429 + Retry-After |
| Write operations | 100 | por segundo | 429 + Retry-After |
### Estrategia de Retry
```typescript
const stripe = new Stripe(apiKey, {
maxNetworkRetries: 3,
timeout: 30000,
});
```
---
## 5. Manejo de Errores
### Codigos de Error
| Tipo | Descripcion | Accion Recomendada | Retry |
|------|-------------|-------------------|-------|
| `card_error` | Tarjeta rechazada | Mostrar mensaje al usuario | NO |
| `invalid_request_error` | Parametros invalidos | Validar input | NO |
| `authentication_error` | API key invalida | Verificar configuracion | NO |
| `rate_limit_error` | Limite excedido | Backoff | SI |
| `api_error` | Error de Stripe | Retry | SI |
### Ejemplo de Manejo
```typescript
try {
const subscription = await stripe.subscriptions.create(params);
return subscription;
} catch (error) {
if (error instanceof Stripe.errors.StripeCardError) {
throw new BadRequestException(error.message);
}
if (error instanceof Stripe.errors.StripeRateLimitError) {
await sleep(1000);
return this.createSubscription(params); // retry
}
throw error;
}
```
---
## 6. Fallbacks
### Estrategia de Fallback
| Escenario | Fallback | Tiempo maximo |
|-----------|----------|---------------|
| Tarjeta rechazada | Ofrecer OXXO | Inmediato |
| API caida | Encolar para reintento | 1 hora |
| Webhook fallido | Reenvio automatico | 72 horas |
### Pago con OXXO
Para usuarios sin tarjeta:
```typescript
const paymentIntent = await stripe.paymentIntents.create({
amount: 9900, // $99 MXN
currency: 'mxn',
payment_method_types: ['oxxo'],
payment_method_options: {
oxxo: {
expires_after_days: 3,
},
},
});
```
---
## 7. Multi-tenant
### Modelo de Credenciales
- [x] **Global:** Una cuenta Stripe para toda la plataforma
MiChangarrito es el "merchant", los tenants son clientes.
### Relacion con Tenants
```sql
-- En schema subscriptions
CREATE TABLE subscriptions.tenant_subscriptions (
id UUID PRIMARY KEY,
tenant_id UUID REFERENCES auth.tenants(id),
stripe_customer_id VARCHAR(50),
stripe_subscription_id VARCHAR(50),
plan_type subscription_plan_type,
status subscription_status,
current_period_end TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```
---
## 8. Webhooks
### Endpoints Registrados
| Evento | Endpoint Local | Descripcion |
|--------|----------------|-------------|
| `customer.subscription.created` | `/webhooks/stripe` | Suscripcion creada |
| `customer.subscription.updated` | `/webhooks/stripe` | Cambio en suscripcion |
| `customer.subscription.deleted` | `/webhooks/stripe` | Suscripcion cancelada |
| `invoice.paid` | `/webhooks/stripe` | Factura pagada |
| `invoice.payment_failed` | `/webhooks/stripe` | Pago fallido |
| `checkout.session.completed` | `/webhooks/stripe` | Compra tokens |
### Validacion de Webhooks
```typescript
const sig = request.headers['stripe-signature'];
const event = stripe.webhooks.constructEvent(
request.rawBody,
sig,
process.env.STRIPE_WEBHOOK_SECRET
);
```
### Configuracion en Stripe
1. Dashboard → Developers → Webhooks
2. Endpoint: `https://api.michangarrito.com/webhooks/stripe`
3. Eventos: Los listados arriba
---
## 9. Testing
### Modo Test
| Ambiente | Credenciales | Datos |
|----------|--------------|-------|
| Test | `sk_test_*` | Tarjetas de prueba |
| Live | `sk_live_*` | Tarjetas reales |
### Tarjetas de Prueba
```
# Pago exitoso
4242 4242 4242 4242
# Requiere autenticacion
4000 0025 0000 3155
# Fondos insuficientes
4000 0000 0000 9995
```
### Comandos de Test
```bash
# Test webhook local
stripe listen --forward-to localhost:3141/webhooks/stripe
# Trigger evento de prueba
stripe trigger customer.subscription.created
```
---
## 10. Monitoreo
### Metricas a Monitorear
| Metrica | Descripcion | Alerta |
|---------|-------------|--------|
| MRR | Monthly Recurring Revenue | - |
| Churn Rate | % cancelaciones | > 5% |
| Failed Payments | Pagos fallidos | > 10% |
| Webhook Success | % webhooks procesados | < 95% |
### Dashboard
Usar Stripe Dashboard para metricas de negocio:
- Revenue por plan
- Suscriptores activos
- Churn analysis
---
## 11. Referencias
### Documentacion Oficial
- [Stripe API Reference](https://stripe.com/docs/api)
- [Subscriptions Guide](https://stripe.com/docs/billing/subscriptions)
- [Webhooks Guide](https://stripe.com/docs/webhooks)
### Modulos Relacionados
- [Subscriptions Module](../../apps/backend/src/modules/subscriptions/)
- [Payments Module](../../apps/backend/src/modules/payments/)
### Soporte
- Stripe Support: https://support.stripe.com/
---
**Ultima actualizacion:** 2026-01-10
**Autor:** Backend Team