payments with stripe
Signed-off-by: Omar Sánchez Pizarro <omar.sanchez@pistacero.net>
This commit is contained in:
14
web/backend/env.example.txt
Normal file
14
web/backend/env.example.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
# Stripe Configuration
|
||||
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key_here
|
||||
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here
|
||||
|
||||
# Base URL for redirects (production/development)
|
||||
BASE_URL=http://localhost
|
||||
|
||||
# MongoDB Configuration (optional, if not in config.yaml)
|
||||
# MONGODB_HOST=localhost
|
||||
# MONGODB_PORT=27017
|
||||
# MONGODB_DATABASE=wallabicher
|
||||
# MONGODB_USERNAME=
|
||||
# MONGODB_PASSWORD=
|
||||
|
||||
21
web/backend/package-lock.json
generated
21
web/backend/package-lock.json
generated
@@ -15,6 +15,7 @@
|
||||
"express": "^4.18.2",
|
||||
"mongodb": "^6.3.0",
|
||||
"rate-limiter-flexible": "^5.0.3",
|
||||
"stripe": "^20.2.0",
|
||||
"web-push": "^3.6.7",
|
||||
"ws": "^8.14.2",
|
||||
"yaml": "^2.3.4"
|
||||
@@ -1780,6 +1781,26 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/stripe": {
|
||||
"version": "20.2.0",
|
||||
"resolved": "https://registry.npmjs.org/stripe/-/stripe-20.2.0.tgz",
|
||||
"integrity": "sha512-m8niTfdm3nPP/yQswRWMwQxqEUcTtB3RTJQ9oo6NINDzgi7aPOadsH/fPXIIfL1Sc5+lqQFKSk7WiO6CXmvaeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"qs": "^6.14.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=16"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
|
||||
|
||||
@@ -20,8 +20,9 @@
|
||||
"chokidar": "^3.5.3",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"rate-limiter-flexible": "^5.0.3",
|
||||
"mongodb": "^6.3.0",
|
||||
"rate-limiter-flexible": "^5.0.3",
|
||||
"stripe": "^20.2.0",
|
||||
"web-push": "^3.6.7",
|
||||
"ws": "^8.14.2",
|
||||
"yaml": "^2.3.4"
|
||||
|
||||
418
web/backend/routes/payments.js
Normal file
418
web/backend/routes/payments.js
Normal file
@@ -0,0 +1,418 @@
|
||||
import express from 'express';
|
||||
import { basicAuthMiddleware } from '../middlewares/auth.js';
|
||||
import {
|
||||
getStripeClient,
|
||||
createCheckoutSession,
|
||||
createCustomerPortalSession,
|
||||
cancelSubscription,
|
||||
reactivateSubscription,
|
||||
verifyWebhookSignature,
|
||||
} from '../services/stripe.js';
|
||||
import {
|
||||
getUser,
|
||||
updateUserSubscription,
|
||||
getUserSubscription,
|
||||
} from '../services/mongodb.js';
|
||||
import { getPlan } from '../config/subscriptionPlans.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Middleware de autenticación opcional (intenta autenticar pero no falla si no hay token)
|
||||
async function optionalAuthMiddleware(req, res, next) {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (authHeader) {
|
||||
// Si hay header de autorización, intentar autenticar
|
||||
return basicAuthMiddleware(req, res, next);
|
||||
} else {
|
||||
// Si no hay header, continuar sin autenticación
|
||||
req.user = null;
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
// Crear sesión de checkout (permite autenticación opcional)
|
||||
// Puede ser llamado por usuarios autenticados o durante el registro
|
||||
router.post('/create-checkout-session', optionalAuthMiddleware, async (req, res) => {
|
||||
try {
|
||||
const stripeClient = getStripeClient();
|
||||
if (!stripeClient) {
|
||||
return res.status(503).json({
|
||||
error: 'Pagos no disponibles',
|
||||
message: 'El sistema de pagos no está configurado actualmente'
|
||||
});
|
||||
}
|
||||
|
||||
const { planId, billingPeriod, username: providedUsername, email: providedEmail } = req.body;
|
||||
|
||||
// Username puede venir del token (usuario autenticado) o del body (registro nuevo)
|
||||
const username = req.user?.username || providedUsername;
|
||||
|
||||
if (!username) {
|
||||
return res.status(400).json({
|
||||
error: 'Se requiere username (autenticación o en el body)'
|
||||
});
|
||||
}
|
||||
|
||||
if (!planId || !billingPeriod) {
|
||||
return res.status(400).json({
|
||||
error: 'planId y billingPeriod son requeridos'
|
||||
});
|
||||
}
|
||||
|
||||
if (planId === 'free') {
|
||||
return res.status(400).json({
|
||||
error: 'El plan gratuito no requiere pago'
|
||||
});
|
||||
}
|
||||
|
||||
if (!['monthly', 'yearly'].includes(billingPeriod)) {
|
||||
return res.status(400).json({
|
||||
error: 'billingPeriod debe ser monthly o yearly'
|
||||
});
|
||||
}
|
||||
|
||||
// Obtener usuario
|
||||
const user = await getUser(username);
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: 'Usuario no encontrado' });
|
||||
}
|
||||
|
||||
// Email puede venir del usuario en BD, del body, o generar uno
|
||||
const email = user.email || providedEmail || `${username}@wallabicher.local`;
|
||||
|
||||
// Crear sesión de checkout
|
||||
const session = await createCheckoutSession({
|
||||
planId,
|
||||
billingPeriod,
|
||||
email,
|
||||
userId: username,
|
||||
});
|
||||
|
||||
console.log(`✅ Sesión de checkout creada para ${username}: ${planId} (${billingPeriod})`);
|
||||
res.json({
|
||||
success: true,
|
||||
sessionId: session.id,
|
||||
url: session.url,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error creando sesión de checkout:', error);
|
||||
res.status(500).json({
|
||||
error: error.message,
|
||||
message: 'Error al crear la sesión de pago'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Crear portal del cliente
|
||||
router.post('/create-portal-session', basicAuthMiddleware, async (req, res) => {
|
||||
try {
|
||||
const stripeClient = getStripeClient();
|
||||
if (!stripeClient) {
|
||||
return res.status(503).json({
|
||||
error: 'Pagos no disponibles',
|
||||
message: 'El sistema de pagos no está configurado actualmente'
|
||||
});
|
||||
}
|
||||
|
||||
const username = req.user.username;
|
||||
const subscription = await getUserSubscription(username);
|
||||
|
||||
if (!subscription || !subscription.stripeCustomerId) {
|
||||
return res.status(404).json({
|
||||
error: 'No se encontró información de cliente de Stripe'
|
||||
});
|
||||
}
|
||||
|
||||
const session = await createCustomerPortalSession(subscription.stripeCustomerId);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
url: session.url,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error creando portal de cliente:', error);
|
||||
res.status(500).json({
|
||||
error: error.message,
|
||||
message: 'Error al crear el portal de gestión'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Cancelar suscripción
|
||||
router.post('/cancel-subscription', basicAuthMiddleware, async (req, res) => {
|
||||
try {
|
||||
const stripeClient = getStripeClient();
|
||||
if (!stripeClient) {
|
||||
return res.status(503).json({
|
||||
error: 'Pagos no disponibles',
|
||||
message: 'El sistema de pagos no está configurado actualmente'
|
||||
});
|
||||
}
|
||||
|
||||
const username = req.user.username;
|
||||
const subscription = await getUserSubscription(username);
|
||||
|
||||
if (!subscription || !subscription.stripeSubscriptionId) {
|
||||
return res.status(404).json({
|
||||
error: 'No se encontró suscripción activa'
|
||||
});
|
||||
}
|
||||
|
||||
await cancelSubscription(subscription.stripeSubscriptionId);
|
||||
|
||||
// Actualizar en BD
|
||||
await updateUserSubscription(username, {
|
||||
...subscription,
|
||||
cancelAtPeriodEnd: true,
|
||||
});
|
||||
|
||||
console.log(`✅ Suscripción cancelada para ${username}`);
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Suscripción cancelada. Se mantendrá activa hasta el final del período'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error cancelando suscripción:', error);
|
||||
res.status(500).json({
|
||||
error: error.message,
|
||||
message: 'Error al cancelar la suscripción'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Reactivar suscripción
|
||||
router.post('/reactivate-subscription', basicAuthMiddleware, async (req, res) => {
|
||||
try {
|
||||
const stripeClient = getStripeClient();
|
||||
if (!stripeClient) {
|
||||
return res.status(503).json({
|
||||
error: 'Pagos no disponibles',
|
||||
message: 'El sistema de pagos no está configurado actualmente'
|
||||
});
|
||||
}
|
||||
|
||||
const username = req.user.username;
|
||||
const subscription = await getUserSubscription(username);
|
||||
|
||||
if (!subscription || !subscription.stripeSubscriptionId) {
|
||||
return res.status(404).json({
|
||||
error: 'No se encontró suscripción'
|
||||
});
|
||||
}
|
||||
|
||||
await reactivateSubscription(subscription.stripeSubscriptionId);
|
||||
|
||||
// Actualizar en BD
|
||||
await updateUserSubscription(username, {
|
||||
...subscription,
|
||||
cancelAtPeriodEnd: false,
|
||||
});
|
||||
|
||||
console.log(`✅ Suscripción reactivada para ${username}`);
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Suscripción reactivada correctamente'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error reactivando suscripción:', error);
|
||||
res.status(500).json({
|
||||
error: error.message,
|
||||
message: 'Error al reactivar la suscripción'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Webhook de Stripe (sin autenticación)
|
||||
// ⚠️ NOTA: express.raw() se aplica en server.js para esta ruta
|
||||
// De lo contrario el body ya viene parseado y Stripe no puede verificar la firma
|
||||
router.post('/webhook', async (req, res) => {
|
||||
const signature = req.headers['stripe-signature'];
|
||||
|
||||
if (!signature) {
|
||||
return res.status(400).json({ error: 'No stripe-signature header' });
|
||||
}
|
||||
|
||||
let event;
|
||||
|
||||
try {
|
||||
// Verificar firma del webhook
|
||||
event = verifyWebhookSignature(req.body, signature);
|
||||
} catch (error) {
|
||||
console.error('Error verificando webhook:', error.message);
|
||||
return res.status(400).json({ error: `Webhook verification failed: ${error.message}` });
|
||||
}
|
||||
|
||||
console.log(`📩 Webhook recibido: ${event.type}`);
|
||||
|
||||
// Manejar eventos de Stripe
|
||||
try {
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed':
|
||||
await handleCheckoutComplete(event.data.object);
|
||||
break;
|
||||
|
||||
case 'customer.subscription.updated':
|
||||
await handleSubscriptionUpdated(event.data.object);
|
||||
break;
|
||||
|
||||
case 'customer.subscription.deleted':
|
||||
await handleSubscriptionDeleted(event.data.object);
|
||||
break;
|
||||
|
||||
case 'invoice.payment_succeeded':
|
||||
await handlePaymentSucceeded(event.data.object);
|
||||
break;
|
||||
|
||||
case 'invoice.payment_failed':
|
||||
await handlePaymentFailed(event.data.object);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log(`ℹ️ Evento no manejado: ${event.type}`);
|
||||
}
|
||||
|
||||
res.json({ received: true });
|
||||
} catch (error) {
|
||||
console.error('Error procesando webhook:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Handlers de eventos de Stripe
|
||||
|
||||
async function handleCheckoutComplete(session) {
|
||||
const userId = session.metadata.userId || session.client_reference_id;
|
||||
const planId = session.metadata.planId;
|
||||
const billingPeriod = session.metadata.billingPeriod;
|
||||
|
||||
if (!userId) {
|
||||
console.error('❌ Checkout sin userId en metadata');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`✅ Pago completado: ${userId} → ${planId} (${billingPeriod})`);
|
||||
|
||||
// Obtener detalles de la suscripción
|
||||
const subscriptionId = session.subscription;
|
||||
const customerId = session.customer;
|
||||
|
||||
const plan = getPlan(planId);
|
||||
const now = new Date();
|
||||
let periodEnd = new Date(now);
|
||||
|
||||
if (billingPeriod === 'yearly') {
|
||||
periodEnd.setFullYear(periodEnd.getFullYear() + 1);
|
||||
} else {
|
||||
periodEnd.setMonth(periodEnd.getMonth() + 1);
|
||||
}
|
||||
|
||||
// Actualizar suscripción en BD
|
||||
await updateUserSubscription(userId, {
|
||||
planId,
|
||||
status: 'active',
|
||||
billingPeriod,
|
||||
currentPeriodStart: now,
|
||||
currentPeriodEnd: periodEnd,
|
||||
cancelAtPeriodEnd: false,
|
||||
stripeCustomerId: customerId,
|
||||
stripeSubscriptionId: subscriptionId,
|
||||
});
|
||||
|
||||
// Activar usuario si estaba pendiente de pago
|
||||
const { getDB } = await import('../services/mongodb.js');
|
||||
const db = getDB();
|
||||
if (db) {
|
||||
const usersCollection = db.collection('users');
|
||||
const user = await usersCollection.findOne({ username: userId });
|
||||
|
||||
if (user && user.status === 'pending_payment') {
|
||||
await usersCollection.updateOne(
|
||||
{ username: userId },
|
||||
{
|
||||
$set: {
|
||||
status: 'active',
|
||||
activatedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
}
|
||||
);
|
||||
console.log(`✅ Usuario activado: ${userId}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Suscripción actualizada en BD: ${userId}`);
|
||||
}
|
||||
|
||||
async function handleSubscriptionUpdated(subscription) {
|
||||
const userId = subscription.metadata.userId;
|
||||
|
||||
if (!userId) {
|
||||
console.error('❌ Subscription sin userId en metadata');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`📝 Suscripción actualizada: ${userId}`);
|
||||
|
||||
const status = subscription.status; // active, past_due, canceled, etc.
|
||||
const cancelAtPeriodEnd = subscription.cancel_at_period_end;
|
||||
const currentPeriodEnd = new Date(subscription.current_period_end * 1000);
|
||||
const currentPeriodStart = new Date(subscription.current_period_start * 1000);
|
||||
|
||||
// Actualizar en BD
|
||||
const currentSubscription = await getUserSubscription(userId);
|
||||
await updateUserSubscription(userId, {
|
||||
...currentSubscription,
|
||||
status,
|
||||
cancelAtPeriodEnd,
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
});
|
||||
|
||||
console.log(`✅ Suscripción actualizada en BD: ${userId} (${status})`);
|
||||
}
|
||||
|
||||
async function handleSubscriptionDeleted(subscription) {
|
||||
const userId = subscription.metadata.userId;
|
||||
|
||||
if (!userId) {
|
||||
console.error('❌ Subscription sin userId en metadata');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`❌ Suscripción eliminada: ${userId}`);
|
||||
|
||||
// Revertir a plan gratuito
|
||||
await updateUserSubscription(userId, {
|
||||
planId: 'free',
|
||||
status: 'canceled',
|
||||
cancelAtPeriodEnd: false,
|
||||
currentPeriodStart: new Date(),
|
||||
currentPeriodEnd: null,
|
||||
stripeCustomerId: subscription.customer,
|
||||
stripeSubscriptionId: null,
|
||||
});
|
||||
|
||||
console.log(`✅ Usuario revertido a plan gratuito: ${userId}`);
|
||||
}
|
||||
|
||||
async function handlePaymentSucceeded(invoice) {
|
||||
const subscriptionId = invoice.subscription;
|
||||
const customerId = invoice.customer;
|
||||
|
||||
console.log(`✅ Pago exitoso: ${customerId} - ${subscriptionId}`);
|
||||
|
||||
// Aquí podrías enviar un email de confirmación o actualizar estadísticas
|
||||
}
|
||||
|
||||
async function handlePaymentFailed(invoice) {
|
||||
const subscriptionId = invoice.subscription;
|
||||
const customerId = invoice.customer;
|
||||
|
||||
console.log(`❌ Pago fallido: ${customerId} - ${subscriptionId}`);
|
||||
|
||||
// Aquí podrías enviar un email de aviso o marcar la cuenta con problemas
|
||||
}
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -7,6 +7,98 @@ import { combineFingerprint } from '../utils/fingerprint.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Endpoint de registro (público)
|
||||
router.post('/register', async (req, res) => {
|
||||
try {
|
||||
const db = getDB();
|
||||
if (!db) {
|
||||
return res.status(500).json({ error: 'MongoDB no está disponible' });
|
||||
}
|
||||
|
||||
const { username, password, email, planId } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'username y password son requeridos' });
|
||||
}
|
||||
|
||||
if (username.length < 3) {
|
||||
return res.status(400).json({ error: 'El nombre de usuario debe tener al menos 3 caracteres' });
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
return res.status(400).json({ error: 'La contraseña debe tener al menos 6 caracteres' });
|
||||
}
|
||||
|
||||
// Validar email si se proporciona
|
||||
if (email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return res.status(400).json({ error: 'Email no válido' });
|
||||
}
|
||||
}
|
||||
|
||||
// Verificar si el usuario ya existe
|
||||
const existingUser = await getUser(username);
|
||||
if (existingUser) {
|
||||
return res.status(409).json({ error: 'El usuario ya existe' });
|
||||
}
|
||||
|
||||
// Verificar si es plan de pago y si Stripe está disponible
|
||||
const selectedPlanId = planId || 'free';
|
||||
const isPaidPlan = selectedPlanId !== 'free';
|
||||
|
||||
if (isPaidPlan) {
|
||||
// Para planes de pago, verificar que Stripe esté configurado
|
||||
const { getStripeClient } = await import('../services/stripe.js');
|
||||
const stripeClient = getStripeClient();
|
||||
|
||||
if (!stripeClient) {
|
||||
return res.status(503).json({
|
||||
error: 'El sistema de pagos no está disponible actualmente',
|
||||
message: 'No se pueden procesar planes de pago en este momento. Por favor, intenta con el plan gratuito o contacta con soporte.'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Hashear contraseña y crear usuario
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
await createUser({
|
||||
username,
|
||||
passwordHash,
|
||||
email: email || null,
|
||||
role: 'user',
|
||||
// Si es plan de pago, marcar como pendiente hasta que se complete el pago
|
||||
status: isPaidPlan ? 'pending_payment' : 'active',
|
||||
});
|
||||
|
||||
// Crear suscripción inicial
|
||||
const { updateUserSubscription } = await import('../services/mongodb.js');
|
||||
await updateUserSubscription(username, {
|
||||
planId: selectedPlanId,
|
||||
status: isPaidPlan ? 'pending' : 'active',
|
||||
currentPeriodStart: new Date(),
|
||||
currentPeriodEnd: null,
|
||||
cancelAtPeriodEnd: false,
|
||||
});
|
||||
|
||||
console.log(`✅ Usuario registrado: ${username} (${selectedPlanId}) - Estado: ${isPaidPlan ? 'pending_payment' : 'active'}`);
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Usuario creado correctamente',
|
||||
username,
|
||||
planId: selectedPlanId,
|
||||
requiresPayment: isPaidPlan,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error registrando usuario:', error);
|
||||
// Manejar error de duplicado
|
||||
if (error.code === 11000) {
|
||||
return res.status(409).json({ error: 'El usuario ya existe' });
|
||||
}
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Endpoint de login (público)
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
@@ -42,6 +134,23 @@ router.post('/login', async (req, res) => {
|
||||
return res.status(401).json({ error: 'Invalid credentials', message: 'Usuario o contraseña incorrectos' });
|
||||
}
|
||||
|
||||
// Verificar estado del usuario
|
||||
if (user.status === 'pending_payment') {
|
||||
return res.status(403).json({
|
||||
error: 'Payment pending',
|
||||
message: 'Tu cuenta está pendiente de pago. Por favor, completa el proceso de pago para activar tu cuenta.',
|
||||
status: 'pending_payment'
|
||||
});
|
||||
}
|
||||
|
||||
if (user.status === 'suspended' || user.status === 'disabled') {
|
||||
return res.status(403).json({
|
||||
error: 'Account suspended',
|
||||
message: 'Tu cuenta ha sido suspendida. Contacta con soporte.',
|
||||
status: user.status
|
||||
});
|
||||
}
|
||||
|
||||
// Generar fingerprint del dispositivo
|
||||
const { fingerprint, deviceInfo } = combineFingerprint(clientFingerprint, clientDeviceInfo, req);
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { initVAPIDKeys } from './services/webPush.js';
|
||||
import { initWebSocket } from './services/websocket.js';
|
||||
import { startArticleMonitoring } from './services/articleMonitor.js';
|
||||
import { initFileWatcher } from './services/fileWatcher.js';
|
||||
import { initStripe } from './services/stripe.js';
|
||||
import routes from './routes/index.js';
|
||||
import workersRouter from './routes/workers.js';
|
||||
import articlesRouter from './routes/articles.js';
|
||||
@@ -19,6 +20,7 @@ import pushRouter from './routes/push.js';
|
||||
import usersRouter from './routes/users.js';
|
||||
import adminRouter from './routes/admin.js';
|
||||
import subscriptionRouter from './routes/subscription.js';
|
||||
import paymentsRouter from './routes/payments.js';
|
||||
|
||||
const app = express();
|
||||
const server = createServer(app);
|
||||
@@ -28,6 +30,12 @@ app.set('trust proxy', true);
|
||||
|
||||
// Middlewares globales
|
||||
app.use(cors());
|
||||
|
||||
// ⚠️ IMPORTANTE: Webhook de Stripe necesita el body RAW (sin parsear)
|
||||
// Por eso usamos express.raw() SOLO para esta ruta, ANTES de express.json()
|
||||
app.use('/api/payments/webhook', express.raw({ type: 'application/json' }));
|
||||
|
||||
// Ahora sí, parseamos JSON para todas las demás rutas
|
||||
app.use(express.json());
|
||||
|
||||
// Aplicar rate limiting a todas las rutas API
|
||||
@@ -36,6 +44,9 @@ app.use('/api', rateLimitMiddleware);
|
||||
// Inicializar VAPID keys para Web Push
|
||||
initVAPIDKeys();
|
||||
|
||||
// Inicializar Stripe
|
||||
initStripe();
|
||||
|
||||
// Inicializar WebSocket
|
||||
initWebSocket(server);
|
||||
|
||||
@@ -51,6 +62,7 @@ app.use('/api/push', pushRouter);
|
||||
app.use('/api/users', usersRouter);
|
||||
app.use('/api/admin', adminRouter);
|
||||
app.use('/api/subscription', subscriptionRouter);
|
||||
app.use('/api/payments', paymentsRouter);
|
||||
|
||||
// Inicializar servidor
|
||||
async function startServer() {
|
||||
|
||||
@@ -1331,6 +1331,7 @@ export async function updateUserSubscription(username, subscriptionData) {
|
||||
subscription: {
|
||||
planId: subscriptionData.planId || 'free',
|
||||
status: subscriptionData.status || 'active',
|
||||
billingPeriod: subscriptionData.billingPeriod || 'monthly',
|
||||
currentPeriodStart: subscriptionData.currentPeriodStart || new Date(),
|
||||
currentPeriodEnd: subscriptionData.currentPeriodEnd || null,
|
||||
cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd || false,
|
||||
|
||||
226
web/backend/services/stripe.js
Normal file
226
web/backend/services/stripe.js
Normal file
@@ -0,0 +1,226 @@
|
||||
import Stripe from 'stripe';
|
||||
import { SUBSCRIPTION_PLANS } from '../config/subscriptionPlans.js';
|
||||
|
||||
let stripeClient = null;
|
||||
|
||||
// Inicializar Stripe
|
||||
export function initStripe() {
|
||||
let stripeSecretKey = process.env.STRIPE_SECRET_KEY;
|
||||
|
||||
if (!stripeSecretKey) {
|
||||
stripeSecretKey = 'sk_test_51SrpOfH73CrYqhOp2NfijzzU07ADADmwigscMVdLGzKu9zA83dsrODhfsaY1X4EFTSihhIB0lVtDQ2HpeOfMWTur00YLuuktSL';
|
||||
}
|
||||
|
||||
if (!stripeSecretKey) {
|
||||
console.warn('⚠️ STRIPE_SECRET_KEY no configurado. Los pagos estarán deshabilitados.');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
stripeClient = new Stripe(stripeSecretKey, {
|
||||
apiVersion: '2024-12-18.acacia',
|
||||
});
|
||||
console.log('✅ Stripe inicializado correctamente');
|
||||
return stripeClient;
|
||||
} catch (error) {
|
||||
console.error('Error inicializando Stripe:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Obtener cliente de Stripe
|
||||
export function getStripeClient() {
|
||||
return stripeClient;
|
||||
}
|
||||
|
||||
// Crear sesión de checkout de Stripe
|
||||
export async function createCheckoutSession({ planId, billingPeriod, email, userId }) {
|
||||
if (!stripeClient) {
|
||||
throw new Error('Stripe no está configurado');
|
||||
}
|
||||
|
||||
const plan = SUBSCRIPTION_PLANS[planId];
|
||||
if (!plan) {
|
||||
throw new Error('Plan no válido');
|
||||
}
|
||||
|
||||
if (planId === 'free') {
|
||||
throw new Error('El plan gratuito no requiere pago');
|
||||
}
|
||||
|
||||
// Precio según período de facturación
|
||||
const priceAmount = billingPeriod === 'yearly' ? plan.price.yearly : plan.price.monthly;
|
||||
const priceCents = Math.round(priceAmount * 100); // Convertir a centavos
|
||||
|
||||
// Crear precio en Stripe (o usar precio existente si ya lo tienes)
|
||||
const priceId = await getOrCreatePrice(planId, billingPeriod, priceCents);
|
||||
|
||||
// URL de éxito y cancelación
|
||||
const baseUrl = process.env.BASE_URL || 'http://localhost';
|
||||
const successUrl = `${baseUrl}/dashboard/?session_id={CHECKOUT_SESSION_ID}&payment_success=true`;
|
||||
const cancelUrl = `${baseUrl}/dashboard/?payment_cancelled=true`;
|
||||
|
||||
// Crear sesión de checkout
|
||||
const session = await stripeClient.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
line_items: [
|
||||
{
|
||||
price: priceId,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
success_url: successUrl,
|
||||
cancel_url: cancelUrl,
|
||||
customer_email: email,
|
||||
client_reference_id: userId,
|
||||
metadata: {
|
||||
userId,
|
||||
planId,
|
||||
billingPeriod,
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
userId,
|
||||
planId,
|
||||
billingPeriod,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
// Obtener o crear precio en Stripe
|
||||
async function getOrCreatePrice(planId, billingPeriod, priceCents) {
|
||||
const plan = SUBSCRIPTION_PLANS[planId];
|
||||
|
||||
// Buscar precio existente (usando lookup_key)
|
||||
const lookupKey = `${planId}_${billingPeriod}`;
|
||||
|
||||
try {
|
||||
const prices = await stripeClient.prices.list({
|
||||
lookup_keys: [lookupKey],
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
if (prices.data.length > 0) {
|
||||
return prices.data[0].id;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Precio no encontrado, creando nuevo...');
|
||||
}
|
||||
|
||||
// Si no existe, crear producto y precio
|
||||
let product;
|
||||
try {
|
||||
// Buscar producto existente
|
||||
const products = await stripeClient.products.list({
|
||||
limit: 100,
|
||||
});
|
||||
product = products.data.find(p => p.metadata.planId === planId);
|
||||
|
||||
// Si no existe, crear producto
|
||||
if (!product) {
|
||||
product = await stripeClient.products.create({
|
||||
name: `Wallabicher ${plan.name}`,
|
||||
description: plan.description,
|
||||
metadata: {
|
||||
planId,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creando/buscando producto:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Crear precio
|
||||
const price = await stripeClient.prices.create({
|
||||
product: product.id,
|
||||
unit_amount: priceCents,
|
||||
currency: 'eur',
|
||||
recurring: {
|
||||
interval: billingPeriod === 'yearly' ? 'year' : 'month',
|
||||
},
|
||||
lookup_key: lookupKey,
|
||||
metadata: {
|
||||
planId,
|
||||
billingPeriod,
|
||||
},
|
||||
});
|
||||
|
||||
return price.id;
|
||||
}
|
||||
|
||||
// Crear portal del cliente para gestionar suscripción
|
||||
export async function createCustomerPortalSession(customerId) {
|
||||
if (!stripeClient) {
|
||||
throw new Error('Stripe no está configurado');
|
||||
}
|
||||
|
||||
const baseUrl = process.env.BASE_URL || 'http://localhost';
|
||||
const returnUrl = `${baseUrl}/dashboard/`;
|
||||
|
||||
const session = await stripeClient.billingPortal.sessions.create({
|
||||
customer: customerId,
|
||||
return_url: returnUrl,
|
||||
});
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
// Cancelar suscripción
|
||||
export async function cancelSubscription(subscriptionId) {
|
||||
if (!stripeClient) {
|
||||
throw new Error('Stripe no está configurado');
|
||||
}
|
||||
|
||||
// Cancelar al final del período
|
||||
const subscription = await stripeClient.subscriptions.update(subscriptionId, {
|
||||
cancel_at_period_end: true,
|
||||
});
|
||||
|
||||
return subscription;
|
||||
}
|
||||
|
||||
// Reactivar suscripción cancelada
|
||||
export async function reactivateSubscription(subscriptionId) {
|
||||
if (!stripeClient) {
|
||||
throw new Error('Stripe no está configurado');
|
||||
}
|
||||
|
||||
const subscription = await stripeClient.subscriptions.update(subscriptionId, {
|
||||
cancel_at_period_end: false,
|
||||
});
|
||||
|
||||
return subscription;
|
||||
}
|
||||
|
||||
// Obtener suscripción por ID
|
||||
export async function getSubscription(subscriptionId) {
|
||||
if (!stripeClient) {
|
||||
throw new Error('Stripe no está configurado');
|
||||
}
|
||||
|
||||
return await stripeClient.subscriptions.retrieve(subscriptionId);
|
||||
}
|
||||
|
||||
// Verificar webhook signature
|
||||
export function verifyWebhookSignature(payload, signature) {
|
||||
if (!stripeClient) {
|
||||
throw new Error('Stripe no está configurado');
|
||||
}
|
||||
|
||||
let webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
|
||||
if (!webhookSecret) {
|
||||
webhookSecret = 'whsec_8ebec8c2aa82a791aa9f2cd68211e297a5d172aea62ebd7b771d230e3a597aa8';
|
||||
}
|
||||
|
||||
if (!webhookSecret) {
|
||||
throw new Error('STRIPE_WEBHOOK_SECRET no configurado');
|
||||
}
|
||||
|
||||
return stripeClient.webhooks.constructEvent(payload, signature, webhookSecret);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="min-h-screen bg-gray-100 dark:bg-gray-900" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
|
||||
<!-- Sidebar - Solo mostrar si no estamos en login -->
|
||||
<template v-if="$route.path !== '/login'">
|
||||
<!-- Sidebar - Solo mostrar si no estamos en login o register -->
|
||||
<template v-if="!isPublicRoute">
|
||||
<!-- Sidebar -->
|
||||
<aside
|
||||
class="fixed top-0 left-0 z-40 h-screen transition-all duration-300 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 shadow-lg"
|
||||
@@ -83,9 +83,9 @@
|
||||
</template>
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="transition-all duration-300" :class="$route.path === '/login' ? '' : (sidebarCollapsed ? 'ml-20' : 'ml-64')">
|
||||
<!-- Header - Solo mostrar si no estamos en login -->
|
||||
<header v-if="$route.path !== '/login'" class="sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
|
||||
<div class="transition-all duration-300" :class="isPublicRoute ? '' : (sidebarCollapsed ? 'ml-20' : 'ml-64')">
|
||||
<!-- Header - Solo mostrar si no estamos en login o register -->
|
||||
<header v-if="!isPublicRoute" class="sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
|
||||
<div class="flex items-center justify-between h-16 px-6">
|
||||
<!-- Breadcrumbs -->
|
||||
<div class="flex items-center space-x-2">
|
||||
@@ -138,13 +138,13 @@
|
||||
</header>
|
||||
|
||||
<!-- Page Content -->
|
||||
<main :class="$route.path === '/login' ? '' : 'p-6 pb-20'">
|
||||
<main :class="isPublicRoute ? '' : 'p-6 pb-20'">
|
||||
<router-view />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Footer Fixed - Solo mostrar si no estamos en login -->
|
||||
<footer v-if="$route.path !== '/login'" class="fixed bottom-0 left-0 right-0 z-30 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 py-3 shadow-sm" :class="sidebarCollapsed ? 'ml-20' : 'ml-64'">
|
||||
<!-- Footer Fixed - Solo mostrar si no estamos en login o register -->
|
||||
<footer v-if="!isPublicRoute" class="fixed bottom-0 left-0 right-0 z-30 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 py-3 shadow-sm" :class="sidebarCollapsed ? 'ml-20' : 'ml-64'">
|
||||
<div class="px-6">
|
||||
<p class="text-center text-sm text-gray-600 dark:text-gray-400">
|
||||
© {{ new Date().getFullYear() }} Wallabicher. Todos los derechos reservados.
|
||||
@@ -180,7 +180,7 @@ import {
|
||||
} from '@heroicons/vue/24/outline';
|
||||
import pushNotificationService from './services/pushNotifications';
|
||||
import authService from './services/auth';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
import api from './services/api';
|
||||
import ToastContainer from './components/ToastContainer.vue';
|
||||
|
||||
@@ -198,6 +198,7 @@ const allNavItems = [
|
||||
];
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const wsConnected = ref(false);
|
||||
const sidebarCollapsed = ref(false);
|
||||
const darkMode = ref(false);
|
||||
@@ -209,6 +210,10 @@ let ws = null;
|
||||
const isDark = computed(() => darkMode.value);
|
||||
const isAuthenticated = computed(() => authService.hasCredentials());
|
||||
|
||||
// Rutas públicas que no deben mostrar el sidebar/header
|
||||
const publicRoutes = ['/login', '/register'];
|
||||
const isPublicRoute = computed(() => publicRoutes.includes(route.path));
|
||||
|
||||
// Filtrar navItems según el rol del usuario
|
||||
const navItems = computed(() => {
|
||||
return allNavItems.filter(item => {
|
||||
@@ -339,7 +344,7 @@ onMounted(async () => {
|
||||
authService.clearSession();
|
||||
currentUser.value = authService.getUsername() || null;
|
||||
isAdmin.value = authService.isAdmin();
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
if (!publicRoutes.includes(router.currentRoute.value.path)) {
|
||||
router.push('/login');
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -13,11 +13,13 @@ import Logs from './views/Logs.vue';
|
||||
import RateLimiter from './views/RateLimiter.vue';
|
||||
import Sessions from './views/Sessions.vue';
|
||||
import Login from './views/Login.vue';
|
||||
import Register from './views/Register.vue';
|
||||
import './style.css';
|
||||
import authService from './services/auth';
|
||||
|
||||
const routes = [
|
||||
{ path: '/login', component: Login, name: 'login' },
|
||||
{ path: '/register', component: Register, name: 'register' },
|
||||
{ path: '/', component: Dashboard, meta: { requiresAuth: true } }, // Redirige a /dashboard
|
||||
{ path: '/articles', component: Articles, meta: { requiresAuth: true } },
|
||||
{ path: '/articles/:platform/:id', component: ArticleDetail, meta: { requiresAuth: true } },
|
||||
@@ -38,8 +40,8 @@ const router = createRouter({
|
||||
|
||||
// Guard de navegación para verificar autenticación
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
// Si la ruta es /login y ya está autenticado, redirigir al dashboard
|
||||
if (to.path === '/login') {
|
||||
// Si la ruta es /login o /register y ya está autenticado, redirigir al dashboard
|
||||
if (to.path === '/login' || to.path === '/register') {
|
||||
if (authService.hasCredentials()) {
|
||||
const isValid = await authService.validateSession();
|
||||
if (isValid) {
|
||||
|
||||
@@ -193,5 +193,26 @@ export default {
|
||||
const response = await api.put(`/subscription/${username}`, subscriptionData);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Métodos genéricos para rutas adicionales
|
||||
async post(url, data) {
|
||||
const response = await api.post(url, data);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async get(url, config) {
|
||||
const response = await api.get(url, config);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async put(url, data) {
|
||||
const response = await api.put(url, data);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async delete(url) {
|
||||
const response = await api.delete(url);
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -217,6 +217,12 @@
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
|
||||
<p class="text-sm text-center text-gray-600 dark:text-gray-400 mb-2">
|
||||
¿No tienes cuenta?
|
||||
<router-link to="/register" class="text-primary-600 dark:text-primary-400 hover:underline font-semibold">
|
||||
Regístrate gratis
|
||||
</router-link>
|
||||
</p>
|
||||
<p class="text-xs text-center text-gray-500 dark:text-gray-400">
|
||||
¿Necesitas ayuda? Contacta con el administrador del sistema
|
||||
</p>
|
||||
@@ -265,7 +271,14 @@ async function handleLogin() {
|
||||
window.dispatchEvent(new CustomEvent('auth-login'));
|
||||
} catch (error) {
|
||||
console.error('Error en login:', error);
|
||||
loginError.value = error.message || 'Usuario o contraseña incorrectos';
|
||||
|
||||
// Verificar si el error es de pago pendiente
|
||||
if (error.response?.data?.status === 'pending_payment') {
|
||||
loginError.value = 'Tu cuenta está pendiente de pago. Por favor, completa el proceso de pago para activar tu cuenta. Si ya pagaste, espera unos minutos y vuelve a intentar.';
|
||||
} else {
|
||||
loginError.value = error.response?.data?.message || error.message || 'Usuario o contraseña incorrectos';
|
||||
}
|
||||
|
||||
authService.clearSession();
|
||||
} finally {
|
||||
loginLoading.value = false;
|
||||
|
||||
394
web/dashboard/src/views/Register.vue
Normal file
394
web/dashboard/src/views/Register.vue
Normal file
@@ -0,0 +1,394 @@
|
||||
<template>
|
||||
<div class="fixed inset-0 bg-gradient-to-br from-primary-50 via-teal-50 to-cyan-50 dark:from-gray-950 dark:via-gray-900 dark:to-primary-950 overflow-y-auto">
|
||||
<div class="min-h-screen flex items-center justify-center p-4 py-12">
|
||||
<!-- Logo flotante en la esquina -->
|
||||
<div class="absolute top-4 left-4">
|
||||
<img src="/logo.jpg" alt="Wallabicher" class="w-12 h-12 rounded-xl shadow-lg" />
|
||||
</div>
|
||||
|
||||
<div class="w-full max-w-6xl">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-4xl sm:text-5xl font-bold text-gray-900 dark:text-white mb-2">
|
||||
Crea tu cuenta en
|
||||
<span class="bg-gradient-to-r from-primary-600 via-teal-600 to-cyan-600 bg-clip-text text-transparent">
|
||||
Wallabicher
|
||||
</span>
|
||||
</h1>
|
||||
<p class="text-lg text-gray-600 dark:text-gray-400 mb-2">
|
||||
Elige el plan perfecto para ti y empieza a monitorizar marketplaces
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-500 flex items-center justify-center gap-2">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"></path>
|
||||
</svg>
|
||||
Haz clic en un plan para seleccionarlo
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid lg:grid-cols-3 gap-6 mb-8">
|
||||
<!-- Planes -->
|
||||
<div
|
||||
v-for="plan in plans"
|
||||
:key="plan.id"
|
||||
@click="selectPlan(plan.id)"
|
||||
:class="[
|
||||
'group relative p-6 rounded-2xl border-2 cursor-pointer transition-all duration-300 transform hover:-translate-y-2 hover:shadow-xl',
|
||||
selectedPlan === plan.id
|
||||
? 'border-primary-500 dark:border-primary-400 shadow-2xl scale-105 bg-white dark:bg-gray-800 ring-4 ring-primary-100 dark:ring-primary-900/50'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-primary-300 dark:hover:border-primary-700 bg-white/80 dark:bg-gray-800/80 hover:bg-white dark:hover:bg-gray-800'
|
||||
]"
|
||||
>
|
||||
<!-- Badge popular -->
|
||||
<div v-if="plan.id === 'basic'" class="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 bg-gradient-to-r from-primary-600 to-teal-600 text-white text-xs font-semibold rounded-full">
|
||||
Más Popular
|
||||
</div>
|
||||
|
||||
<!-- Checkmark si está seleccionado -->
|
||||
<div v-if="selectedPlan === plan.id" class="absolute top-4 right-4 w-8 h-8 bg-primary-600 rounded-full flex items-center justify-center shadow-lg animate-scale-in">
|
||||
<svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Indicador de clickeable si NO está seleccionado -->
|
||||
<div v-else class="absolute top-4 right-4 w-8 h-8 border-2 border-gray-300 dark:border-gray-600 rounded-full flex items-center justify-center group-hover:border-primary-500 dark:group-hover:border-primary-400 transition-colors">
|
||||
<svg class="w-4 h-4 text-gray-400 group-hover:text-primary-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="text-center mb-6">
|
||||
<h3 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">{{ plan.name }}</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mb-4">{{ plan.description }}</p>
|
||||
|
||||
<div class="mb-4">
|
||||
<div v-if="billingPeriod === 'monthly'">
|
||||
<span class="text-3xl font-bold text-gray-900 dark:text-white">
|
||||
€{{ plan.price.monthly.toFixed(2) }}
|
||||
</span>
|
||||
<span class="text-gray-600 dark:text-gray-400">/mes</span>
|
||||
</div>
|
||||
<div v-else>
|
||||
<span class="text-3xl font-bold text-gray-900 dark:text-white">
|
||||
€{{ plan.price.yearly.toFixed(2) }}
|
||||
</span>
|
||||
<span class="text-gray-600 dark:text-gray-400">/año</span>
|
||||
<div class="text-sm text-primary-600 dark:text-primary-400 mt-1">
|
||||
€{{ (plan.price.yearly / 12).toFixed(2) }}/mes
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="space-y-2 mb-4">
|
||||
<li v-for="(feature, idx) in plan.features.slice(0, 4)" :key="idx" class="flex items-start text-sm">
|
||||
<svg class="w-5 h-5 text-primary-600 dark:text-primary-400 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
<span class="text-gray-700 dark:text-gray-300">{{ feature }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Formulario de registro -->
|
||||
<div class="max-w-md mx-auto bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8 border border-gray-200 dark:border-gray-700">
|
||||
<h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-2 text-center">
|
||||
Completa tu registro
|
||||
</h2>
|
||||
<div class="text-center mb-6 p-3 bg-primary-50 dark:bg-primary-900/20 rounded-lg border border-primary-200 dark:border-primary-800">
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400">
|
||||
Plan seleccionado:
|
||||
<span class="font-bold text-primary-600 dark:text-primary-400">
|
||||
{{ plans.find(p => p.id === selectedPlan)?.name || 'Gratis' }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Toggle mensual/anual -->
|
||||
<div class="flex justify-center mb-6">
|
||||
<div class="inline-flex items-center bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
|
||||
<button
|
||||
@click="billingPeriod = 'monthly'"
|
||||
:class="[
|
||||
'px-4 py-2 rounded-md text-sm font-medium transition-all',
|
||||
billingPeriod === 'monthly'
|
||||
? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-700 dark:text-gray-300'
|
||||
]"
|
||||
>
|
||||
Mensual
|
||||
</button>
|
||||
<button
|
||||
@click="billingPeriod = 'yearly'"
|
||||
:class="[
|
||||
'px-4 py-2 rounded-md text-sm font-medium transition-all',
|
||||
billingPeriod === 'yearly'
|
||||
? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-700 dark:text-gray-300'
|
||||
]"
|
||||
>
|
||||
Anual
|
||||
<span class="ml-1 text-xs text-primary-600 dark:text-primary-400">-17%</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form @submit.prevent="handleRegister" class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Nombre de usuario
|
||||
</label>
|
||||
<input
|
||||
v-model="formData.username"
|
||||
type="text"
|
||||
required
|
||||
minlength="3"
|
||||
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
|
||||
placeholder="usuario123"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
v-model="formData.email"
|
||||
type="email"
|
||||
required
|
||||
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
|
||||
placeholder="tu@email.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Contraseña
|
||||
</label>
|
||||
<input
|
||||
v-model="formData.password"
|
||||
type="password"
|
||||
required
|
||||
minlength="6"
|
||||
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Confirmar contraseña
|
||||
</label>
|
||||
<input
|
||||
v-model="formData.confirmPassword"
|
||||
type="password"
|
||||
required
|
||||
minlength="6"
|
||||
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-400 px-4 py-3 rounded-lg text-sm">
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="loading"
|
||||
class="w-full py-3 px-4 bg-gradient-to-r from-primary-600 to-teal-600 hover:from-primary-700 hover:to-teal-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span v-if="!loading">
|
||||
{{ selectedPlan === 'free' ? 'Crear cuenta gratis' : `Continuar al pago (€${getPlanPrice()})` }}
|
||||
</span>
|
||||
<span v-else>Procesando...</span>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="mt-6 text-center">
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400">
|
||||
¿Ya tienes cuenta?
|
||||
<router-link to="/login" class="text-primary-600 dark:text-primary-400 hover:underline font-semibold">
|
||||
Inicia sesión
|
||||
</router-link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import api from '../services/api';
|
||||
|
||||
export default {
|
||||
name: 'Register',
|
||||
setup() {
|
||||
const router = useRouter();
|
||||
const plans = ref([]);
|
||||
const selectedPlan = ref('free');
|
||||
const billingPeriod = ref('monthly');
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
|
||||
const formData = ref({
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
|
||||
const getPlanPrice = () => {
|
||||
const plan = plans.value.find(p => p.id === selectedPlan.value);
|
||||
if (!plan) return '0.00';
|
||||
return billingPeriod.value === 'yearly'
|
||||
? plan.price.yearly.toFixed(2)
|
||||
: plan.price.monthly.toFixed(2);
|
||||
};
|
||||
|
||||
const selectPlan = (planId) => {
|
||||
selectedPlan.value = planId;
|
||||
error.value = '';
|
||||
};
|
||||
|
||||
const handleRegister = async () => {
|
||||
error.value = '';
|
||||
|
||||
// Validaciones
|
||||
if (formData.value.password !== formData.value.confirmPassword) {
|
||||
error.value = 'Las contraseñas no coinciden';
|
||||
return;
|
||||
}
|
||||
|
||||
if (formData.value.password.length < 6) {
|
||||
error.value = 'La contraseña debe tener al menos 6 caracteres';
|
||||
return;
|
||||
}
|
||||
|
||||
if (formData.value.username.length < 3) {
|
||||
error.value = 'El nombre de usuario debe tener al menos 3 caracteres';
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
// 1. Registrar usuario
|
||||
const registerResponse = await api.post('/users/register', {
|
||||
username: formData.value.username,
|
||||
email: formData.value.email,
|
||||
password: formData.value.password,
|
||||
planId: selectedPlan.value,
|
||||
});
|
||||
|
||||
if (!registerResponse.success) {
|
||||
throw new Error(registerResponse.error || 'Error al registrar usuario');
|
||||
}
|
||||
|
||||
// 2. Si es plan gratuito, hacer login y redirigir al dashboard
|
||||
if (selectedPlan.value === 'free') {
|
||||
const loginResponse = await api.post('/users/login', {
|
||||
username: formData.value.username,
|
||||
password: formData.value.password,
|
||||
});
|
||||
|
||||
if (loginResponse.token) {
|
||||
localStorage.setItem('token', loginResponse.token);
|
||||
localStorage.setItem('username', loginResponse.username);
|
||||
localStorage.setItem('role', loginResponse.role || 'user');
|
||||
router.push('/');
|
||||
}
|
||||
} else {
|
||||
// 3. Si es plan de pago, crear sesión de checkout directamente (sin login)
|
||||
// El usuario se activará cuando se complete el pago
|
||||
try {
|
||||
const checkoutResponse = await api.post('/payments/create-checkout-session', {
|
||||
planId: selectedPlan.value,
|
||||
billingPeriod: billingPeriod.value,
|
||||
username: formData.value.username,
|
||||
email: formData.value.email,
|
||||
});
|
||||
|
||||
if (checkoutResponse.url) {
|
||||
// Guardar info para después del pago
|
||||
sessionStorage.setItem('pendingUsername', formData.value.username);
|
||||
|
||||
// Redirigir a Stripe Checkout
|
||||
window.location.href = checkoutResponse.url;
|
||||
} else {
|
||||
throw new Error('No se pudo crear la sesión de pago');
|
||||
}
|
||||
} catch (checkoutError) {
|
||||
// Si falla el checkout, mostrar error pero el usuario YA está creado
|
||||
console.error('Error creando sesión de checkout:', checkoutError);
|
||||
error.value = 'Usuario creado, pero hubo un error al procesar el pago. Por favor, intenta iniciar sesión y actualizar tu suscripción desde el panel.';
|
||||
|
||||
// Opcional: podríamos eliminar el usuario aquí si queremos ser más estrictos
|
||||
// Pero es mejor dejarlo para que pueda intentar pagar después desde el dashboard
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error en registro:', err);
|
||||
error.value = err.response?.data?.message || err.response?.data?.error || err.message || 'Error al registrar usuario';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
// Cargar planes
|
||||
const response = await api.get('/subscription/plans');
|
||||
plans.value = response.plans || [];
|
||||
|
||||
// Preseleccionar el plan de la URL si existe
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const planFromUrl = urlParams.get('plan');
|
||||
if (planFromUrl && plans.value.find(p => p.id === planFromUrl)) {
|
||||
selectedPlan.value = planFromUrl;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error cargando planes:', err);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
plans,
|
||||
selectedPlan,
|
||||
billingPeriod,
|
||||
formData,
|
||||
loading,
|
||||
error,
|
||||
selectPlan,
|
||||
handleRegister,
|
||||
getPlanPrice,
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@keyframes scale-in {
|
||||
0% {
|
||||
transform: scale(0);
|
||||
opacity: 0;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-scale-in {
|
||||
animation: scale-in 0.3s ease-out;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -45,6 +45,51 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Actions -->
|
||||
<div v-if="subscription.subscription.planId !== 'free'" class="flex flex-wrap gap-3 pb-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
v-if="!subscription.subscription.cancelAtPeriodEnd"
|
||||
@click="openCancelModal"
|
||||
class="btn btn-outline-danger"
|
||||
:disabled="actionLoading"
|
||||
>
|
||||
Cancelar suscripción
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
@click="reactivateSubscription"
|
||||
class="btn btn-primary"
|
||||
:disabled="actionLoading"
|
||||
>
|
||||
Reactivar suscripción
|
||||
</button>
|
||||
<button
|
||||
@click="openCustomerPortal"
|
||||
class="btn btn-outline"
|
||||
:disabled="actionLoading"
|
||||
>
|
||||
Gestionar pago
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Cancel Warning -->
|
||||
<div v-if="subscription.subscription.cancelAtPeriodEnd" class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
|
||||
<div class="flex items-start space-x-3">
|
||||
<svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
|
||||
</svg>
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-yellow-800 dark:text-yellow-300">
|
||||
Suscripción cancelada
|
||||
</p>
|
||||
<p class="text-sm text-yellow-700 dark:text-yellow-400 mt-1">
|
||||
Tu suscripción se mantendrá activa hasta {{ formatDate(subscription.subscription.currentPeriodEnd) }}.
|
||||
Después se cambiará al plan gratuito automáticamente.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Usage Stats -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
@@ -99,19 +144,19 @@
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title">Planes Disponibles</h3>
|
||||
<p class="card-subtitle">Información de los planes disponibles</p>
|
||||
<p class="card-subtitle">Cambia tu plan en cualquier momento</p>
|
||||
</div>
|
||||
|
||||
<!-- Mensaje informativo -->
|
||||
<div class="mb-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
|
||||
<div class="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
|
||||
<div class="flex items-start">
|
||||
<svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400 mr-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg class="w-5 h-5 text-blue-600 dark:text-blue-400 mr-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
<div>
|
||||
<h4 class="text-sm font-semibold text-yellow-800 dark:text-yellow-300 mb-1">Cambio de plan temporalmente deshabilitado</h4>
|
||||
<p class="text-sm text-yellow-700 dark:text-yellow-400">
|
||||
El cambio de plan no está disponible por el momento. Si necesitas cambiar tu plan, contacta con el administrador.
|
||||
<h4 class="text-sm font-semibold text-blue-800 dark:text-blue-300 mb-1">Actualiza tu plan</h4>
|
||||
<p class="text-sm text-blue-700 dark:text-blue-400">
|
||||
Puedes cambiar a un plan superior en cualquier momento. Para planes de pago, serás redirigido a Stripe Checkout. El cambio a plan gratuito es inmediato.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -125,13 +170,18 @@
|
||||
<div
|
||||
v-for="plan in plans"
|
||||
:key="plan.id"
|
||||
class="p-6 rounded-xl border-2 transition-all duration-300 opacity-75"
|
||||
class="p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-xl"
|
||||
:class="
|
||||
plan.id === subscription?.subscription?.planId
|
||||
? 'border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/20'
|
||||
: 'border-gray-200 dark:border-gray-800'
|
||||
? 'border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/20 shadow-lg'
|
||||
: 'border-gray-200 dark:border-gray-800 hover:border-primary-300 dark:hover:border-primary-700 hover:-translate-y-1'
|
||||
"
|
||||
>
|
||||
<!-- Badge de plan popular -->
|
||||
<div v-if="plan.id === 'basic'" class="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 bg-gradient-to-r from-primary-600 to-teal-600 text-white text-xs font-semibold rounded-full">
|
||||
Más Popular
|
||||
</div>
|
||||
|
||||
<div class="text-center mb-4">
|
||||
<h4 class="text-xl font-bold text-gray-900 dark:text-gray-100 mb-1">{{ plan.name }}</h4>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mb-4">{{ plan.description }}</p>
|
||||
@@ -140,11 +190,14 @@
|
||||
€{{ plan.price.monthly.toFixed(2) }}
|
||||
</span>
|
||||
<span class="text-gray-600 dark:text-gray-400">/mes</span>
|
||||
<p v-if="plan.price.yearly > 0" class="text-xs text-primary-600 dark:text-primary-400 mt-1">
|
||||
o €{{ plan.price.yearly.toFixed(2) }}/año (ahorra 17%)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="space-y-2 mb-6">
|
||||
<li v-for="feature in plan.features.slice(0, 3)" :key="feature" class="flex items-start text-sm">
|
||||
<li v-for="feature in plan.features.slice(0, 4)" :key="feature" class="flex items-start text-sm">
|
||||
<svg class="w-4 h-4 text-primary-600 dark:text-primary-400 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
@@ -154,14 +207,26 @@
|
||||
|
||||
<button
|
||||
v-if="plan.id !== subscription?.subscription?.planId"
|
||||
class="w-full btn btn-primary opacity-50 cursor-not-allowed"
|
||||
disabled
|
||||
title="Cambio de plan temporalmente deshabilitado"
|
||||
@click="upgradePlan(plan.id)"
|
||||
:disabled="upgrading"
|
||||
class="w-full btn transition-all duration-300"
|
||||
:class="plan.id === 'free'
|
||||
? 'btn-outline'
|
||||
: 'btn-primary shadow-lg hover:shadow-xl'"
|
||||
>
|
||||
No disponible
|
||||
<span v-if="!upgrading">
|
||||
{{ plan.id === 'free' ? 'Cambiar a gratuito' : 'Seleccionar plan' }}
|
||||
</span>
|
||||
<span v-else class="flex items-center justify-center">
|
||||
<svg class="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
Procesando...
|
||||
</span>
|
||||
</button>
|
||||
<div v-else class="w-full text-center py-2 px-4 bg-primary-100 dark:bg-primary-900/50 text-primary-700 dark:text-primary-400 rounded-lg font-semibold">
|
||||
Plan Actual
|
||||
<div v-else class="w-full text-center py-3 px-4 bg-gradient-to-r from-primary-100 to-teal-100 dark:from-primary-900/50 dark:to-teal-900/50 text-primary-700 dark:text-primary-400 rounded-lg font-semibold border-2 border-primary-300 dark:border-primary-700">
|
||||
✓ Plan Actual
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -178,6 +243,8 @@ const plans = ref([]);
|
||||
const loading = ref(true);
|
||||
const loadingPlans = ref(true);
|
||||
const upgrading = ref(false);
|
||||
const actionLoading = ref(false);
|
||||
const showCancelModal = ref(false);
|
||||
|
||||
function formatDate(date) {
|
||||
if (!date) return 'N/A';
|
||||
@@ -238,27 +305,120 @@ async function loadPlans() {
|
||||
async function upgradePlan(planId) {
|
||||
if (upgrading.value) return;
|
||||
|
||||
if (!confirm(`¿Estás seguro de que quieres cambiar a el plan ${plans.value.find(p => p.id === planId)?.name || planId}?`)) {
|
||||
return;
|
||||
}
|
||||
const selectedPlan = plans.value.find(p => p.id === planId);
|
||||
if (!selectedPlan) return;
|
||||
|
||||
// Si es plan de pago, crear sesión de checkout
|
||||
if (planId !== 'free') {
|
||||
// Preguntar período de facturación
|
||||
const billingPeriodChoice = confirm('¿Deseas facturación anual? (17% de descuento)\n\nAceptar = Anual\nCancelar = Mensual');
|
||||
const chosenBillingPeriod = billingPeriodChoice ? 'yearly' : 'monthly';
|
||||
|
||||
try {
|
||||
upgrading.value = true;
|
||||
const response = await api.post('/payments/create-checkout-session', {
|
||||
planId,
|
||||
billingPeriod: chosenBillingPeriod,
|
||||
});
|
||||
|
||||
if (response.url) {
|
||||
// Redirigir a Stripe Checkout
|
||||
window.location.href = response.url;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creando sesión de checkout:', error);
|
||||
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al crear la sesión de pago';
|
||||
alert(errorMessage);
|
||||
} finally {
|
||||
upgrading.value = false;
|
||||
}
|
||||
} else {
|
||||
// Plan gratuito
|
||||
if (!confirm(`¿Estás seguro de que quieres cambiar al plan ${selectedPlan.name}?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
upgrading.value = true;
|
||||
await api.updateSubscription({ planId });
|
||||
await loadSubscription();
|
||||
} catch (error) {
|
||||
console.error('Error actualizando plan:', error);
|
||||
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al actualizar el plan';
|
||||
alert(errorMessage);
|
||||
} finally {
|
||||
upgrading.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openCancelModal() {
|
||||
if (confirm('¿Estás seguro de que quieres cancelar tu suscripción? Se mantendrá activa hasta el final del período de facturación.')) {
|
||||
cancelSubscription();
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelSubscription() {
|
||||
try {
|
||||
upgrading.value = true;
|
||||
await api.updateSubscription({ planId });
|
||||
// Plan actualizado correctamente
|
||||
actionLoading.value = true;
|
||||
await api.post('/payments/cancel-subscription');
|
||||
alert('Suscripción cancelada. Se mantendrá activa hasta el final del período.');
|
||||
await loadSubscription();
|
||||
} catch (error) {
|
||||
console.error('Error actualizando plan:', error);
|
||||
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al actualizar el plan';
|
||||
console.error('Error cancelando suscripción:', error);
|
||||
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al cancelar la suscripción';
|
||||
alert(errorMessage);
|
||||
} finally {
|
||||
upgrading.value = false;
|
||||
actionLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reactivateSubscription() {
|
||||
try {
|
||||
actionLoading.value = true;
|
||||
await api.post('/payments/reactivate-subscription');
|
||||
alert('Suscripción reactivada correctamente.');
|
||||
await loadSubscription();
|
||||
} catch (error) {
|
||||
console.error('Error reactivando suscripción:', error);
|
||||
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al reactivar la suscripción';
|
||||
alert(errorMessage);
|
||||
} finally {
|
||||
actionLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openCustomerPortal() {
|
||||
try {
|
||||
actionLoading.value = true;
|
||||
const response = await api.post('/payments/create-portal-session');
|
||||
if (response.url) {
|
||||
window.location.href = response.url;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error abriendo portal de cliente:', error);
|
||||
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al abrir el portal de gestión';
|
||||
alert(errorMessage);
|
||||
} finally {
|
||||
actionLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadSubscription();
|
||||
loadPlans();
|
||||
|
||||
// Verificar si venimos de un pago exitoso
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
if (urlParams.get('payment_success') === 'true') {
|
||||
alert('¡Pago procesado exitosamente! Tu suscripción ha sido activada.');
|
||||
// Limpiar URL
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
} else if (urlParams.get('payment_cancelled') === 'true') {
|
||||
alert('Pago cancelado. Puedes intentarlo de nuevo cuando quieras.');
|
||||
// Limpiar URL
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
<div class="absolute inset-0 bg-gradient-to-r from-primary-700 to-teal-700 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
|
||||
</a>
|
||||
<a
|
||||
href="/dashboard/"
|
||||
href="/dashboard/register?plan=free"
|
||||
class="inline-flex items-center justify-center px-8 py-4 text-lg font-semibold text-gray-900 dark:text-gray-100 bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm rounded-xl hover:bg-white dark:hover:bg-gray-800 transition-all duration-300 border-2 border-gray-200 dark:border-gray-700 shadow-lg hover:shadow-xl transform hover:-translate-y-1"
|
||||
>
|
||||
Empezar gratis
|
||||
|
||||
@@ -118,7 +118,7 @@ const plans = [
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
|
||||
{plans.map((plan, index) => (
|
||||
<div
|
||||
class={`relative p-8 rounded-2xl bg-white dark:bg-gray-900 border-2 transition-all duration-300 transform hover:-translate-y-2 hover:shadow-2xl animate-slide-up ${
|
||||
class={`relative p-8 rounded-2xl bg-white dark:bg-gray-900 border-2 transition-all duration-300 transform hover:-translate-y-2 hover:shadow-2xl animate-slide-up flex flex-col ${
|
||||
plan.popular
|
||||
? 'border-primary-500 dark:border-primary-400 shadow-xl scale-105'
|
||||
: 'border-gray-200 dark:border-gray-800 hover:border-primary-300 dark:hover:border-primary-700'
|
||||
@@ -157,7 +157,7 @@ const plans = [
|
||||
</div>
|
||||
|
||||
<!-- Features -->
|
||||
<ul class="space-y-4 mb-8">
|
||||
<ul class="space-y-4 mb-8 flex-grow">
|
||||
{plan.features.map((feature) => (
|
||||
<li class="flex items-start">
|
||||
<svg class="w-5 h-5 text-primary-600 dark:text-primary-400 mr-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
@@ -170,8 +170,8 @@ const plans = [
|
||||
|
||||
<!-- CTA Button -->
|
||||
<a
|
||||
href="/dashboard"
|
||||
class={`block w-full text-center px-6 py-3 rounded-xl font-semibold transition-all duration-300 ${
|
||||
href={`/dashboard/register?plan=${plan.id}`}
|
||||
class={`block w-full text-center px-6 py-3 rounded-xl font-semibold transition-all duration-300 mt-auto ${
|
||||
plan.popular
|
||||
? 'bg-gradient-to-r from-primary-600 to-teal-600 text-white hover:from-primary-700 hover:to-teal-700 shadow-lg hover:shadow-xl'
|
||||
: plan.id === 'free'
|
||||
|
||||
Reference in New Issue
Block a user