From 8e9f232dba168e21aa040b9c32689a2badf8e45f Mon Sep 17 00:00:00 2001 From: posimai Date: Sun, 5 Apr 2026 14:01:41 +0900 Subject: [PATCH] feat: stripe webhook plan upgrade/downgrade, add plan/subscription columns --- server.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 0115ebc7..5b87be80 100644 --- a/server.js +++ b/server.js @@ -642,6 +642,9 @@ async function initDB() { `ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN DEFAULT false`, `ALTER TABLE users ADD COLUMN IF NOT EXISTS purchased_at TIMESTAMPTZ`, `ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_session_id TEXT`, + `ALTER TABLE users ADD COLUMN IF NOT EXISTS plan VARCHAR(20) NOT NULL DEFAULT 'free'`, + `ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_customer_id TEXT`, + `ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_subscription_id TEXT`, ]; for (const sql of migrations) { await pool.query(sql).catch(e => console.warn('[DB] Migration warning:', e.message)); @@ -2863,11 +2866,12 @@ async function handleStripeWebhook(req, res) { ); } await pool.query( - `UPDATE users SET purchased_at = NOW(), stripe_session_id = $1 - WHERE user_id = $2`, - [session.id, userId] + `UPDATE users SET purchased_at = NOW(), stripe_session_id = $1, + plan = 'premium', stripe_customer_id = $2, stripe_subscription_id = $3 + WHERE user_id = $4`, + [session.id, session.customer, session.subscription, userId] ); - console.log(`[Stripe] Purchase recorded for ${email} (userId: ${userId})`); + console.log(`[Stripe] Plan upgraded to premium for ${email}`); } catch (e) { console.error('[Stripe] DB error recording purchase:', e.message); return res.status(500).json({ error: 'DB error' }); @@ -2875,6 +2879,21 @@ async function handleStripeWebhook(req, res) { } } + // サブスクリプション解約 → plan を free に戻す + if (event.type === 'customer.subscription.deleted') { + const subscription = event.data.object; + try { + await pool.query( + `UPDATE users SET plan = 'free', stripe_subscription_id = NULL + WHERE stripe_customer_id = $1`, + [subscription.customer] + ); + console.log(`[Stripe] Plan downgraded to free for customer: ${subscription.customer}`); + } catch (e) { + console.error('[Stripe] DB error downgrading plan:', e.message); + } + } + res.json({ received: true }); }