Skip to content

Commit

Permalink
Handle Stripe subscription expired webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
FadhlanR committed Nov 18, 2024
1 parent db8c1b1 commit d47bbb9
Show file tree
Hide file tree
Showing 4 changed files with 425 additions and 1 deletion.
34 changes: 33 additions & 1 deletion packages/billing/stripe-webhook-handlers/subscription-deleted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,23 @@ import {
} from '../billing-queries';

import { PgAdapter, TransactionManager } from '@cardstack/postgres';
import Stripe from 'stripe';



let stripe: Stripe;

export function getStripe() {
if (!process.env.STRIPE_WEBHOOK_SECRET) {
throw new Error('STRIPE_WEBHOOK_SECRET is not set');
}

if (!stripe) {
stripe = new Stripe(process.env.STRIPE_WEBHOOK_SECRET);
}

return stripe;
}

export async function handleSubscriptionDeleted(
dbAdapter: DBAdapter,
Expand Down Expand Up @@ -71,9 +88,24 @@ export async function handleSubscriptionDeleted(

// This happens when the payment method fails for a couple of times and then Stripe subscription gets expired.
if (newStatus === 'expired') {
// TODO: Put the user back on the free plan (by calling Stripe API). Will be handled in CS-7466
await subcribeUserToFreePlan(event.data.object.customer);
}

await markStripeEventAsProcessed(dbAdapter, event.id);
});
}

async function subcribeUserToFreePlan(stripeCustomerId: string) {
try {
await getStripe().subscriptions.create({
customer: stripeCustomerId,
items: [
{
price: '0'
}
],
});
} catch(err) {
console.error(`Failed to subscribe user back to free plan, error:`, err);
}
}
2 changes: 2 additions & 0 deletions packages/realm-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@types/qs": "^6.9.17",
"@types/qunit": "^2.11.3",
"@types/sane": "^2.0.1",
"@types/sinon": "^17.0.3",
"@types/supertest": "^2.0.12",
"@types/tmp": "^0.2.3",
"@types/uuid": "^9.0.8",
Expand Down Expand Up @@ -54,6 +55,7 @@
"qs": "^6.13.0",
"qunit": "^2.20.0",
"sane": "^5.0.1",
"sinon": "^19.0.2",
"start-server-and-test": "^1.14.0",
"supertest": "^6.2.4",
"testem": "^3.10.1",
Expand Down
Loading

0 comments on commit d47bbb9

Please sign in to comment.