|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const Archetype = require('archetype'); |
| 4 | +const assert = require('assert'); |
| 5 | +const connect = require('../../src/db'); |
| 6 | +const mongoose = require('mongoose'); |
| 7 | +const stripe = require('../integrations/stripe'); |
| 8 | + |
| 9 | +const StripeWebhookParams = new Archetype({ |
| 10 | + type: { |
| 11 | + $type: 'string' |
| 12 | + }, |
| 13 | + data: { |
| 14 | + object: { |
| 15 | + client_reference_id: { |
| 16 | + $type: 'string' |
| 17 | + }, |
| 18 | + customer: { |
| 19 | + $type: 'string' |
| 20 | + }, |
| 21 | + subscription: { |
| 22 | + $type: 'string' |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | +}).compile('StripeWebhookParams'); |
| 27 | + |
| 28 | +module.exports = async function stripeWebhook(params, req) { |
| 29 | + console.log('AB', req, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET); |
| 30 | + try { |
| 31 | + stripe.client.webhooks.constructEvent(req.rawBody, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET); |
| 32 | + } catch (err) { |
| 33 | + console.log('Caught', err); |
| 34 | + throw new Error('Invalid webhook signature'); |
| 35 | + } |
| 36 | + |
| 37 | + const db = await connect(); |
| 38 | + |
| 39 | + const { Workspace } = db.models; |
| 40 | + |
| 41 | + const { type, data } = new StripeWebhookParams(params); |
| 42 | + |
| 43 | + if (type === 'checkout.session.completed') { |
| 44 | + const workspaceId = data?.object?.client_reference_id; |
| 45 | + assert.ok(workspaceId, 'no workspace id found'); |
| 46 | + const workspace = await Workspace.findById(workspaceId).orFail(); |
| 47 | + assert.ok(!workspace.stripeSubscriptionId, 'workspace already has a subscription'); |
| 48 | + assert.ok(data.object.customer, 'no customer found in webhook'); |
| 49 | + assert.ok(data.object.subscription, 'no subscription found in webhook'); |
| 50 | + |
| 51 | + workspace.stripeCustomerId = data.object.customer; |
| 52 | + workspace.stripeSubscriptionId = data.object.subscription; |
| 53 | + workspace.subscriptionTier = 'pro'; |
| 54 | + await workspace.save(); |
| 55 | + |
| 56 | + return { workspace }; |
| 57 | + } |
| 58 | + |
| 59 | + return {}; |
| 60 | +}; |
0 commit comments