From e7484638e3359fa400ff5e995f5eb39fb9cd31f6 Mon Sep 17 00:00:00 2001 From: Fabien 'egg' O'Carroll Date: Fri, 24 Jul 2020 15:39:01 +0200 Subject: [PATCH] Ensured that we do not insert orphaned rows (#190) no-issue Previously we would blindly put subscriptions into the database when we received a webhook, which could result in orphaned rows that were not linked to a customer (and by extension a member) This updates the logic so that we will only add subscriptions if we have a record of their customer. Customers are only added during a checkout.session.completed webhook, at which point a member is guarunteed, but for formailty and safety against changes in the flow, the logic has been applied to inserting customers too. --- ghost/members-api/index.js | 1 + ghost/members-api/lib/metadata.js | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/ghost/members-api/index.js b/ghost/members-api/index.js index f5006f8f64..b425c9709e 100644 --- a/ghost/members-api/index.js +++ b/ghost/members-api/index.js @@ -41,6 +41,7 @@ module.exports = function MembersApi({ const {encodeIdentityToken, decodeToken} = Tokens({privateKey, publicKey, issuer}); const metadata = Metadata({ + Member, StripeWebhook, StripeCustomer, StripeCustomerSubscription diff --git a/ghost/members-api/lib/metadata.js b/ghost/members-api/lib/metadata.js index 7a843a4ec4..e14009dc29 100644 --- a/ghost/members-api/lib/metadata.js +++ b/ghost/members-api/lib/metadata.js @@ -1,4 +1,5 @@ module.exports = function ({ + Member, StripeWebhook, StripeCustomer, StripeCustomerSubscription @@ -9,15 +10,26 @@ module.exports = function ({ } if (metadata.customer) { - await StripeCustomer.upsert(metadata.customer, { - customer_id: metadata.customer.customer_id + const member = await Member.findOne({ + id: metadata.customer.member_id }); + + if (member) { + await StripeCustomer.upsert(metadata.customer, { + customer_id: metadata.customer.customer_id + }); + } } if (metadata.subscription) { - await StripeCustomerSubscription.upsert(metadata.subscription, { - subscription_id: metadata.subscription.subscription_id + const customer = await StripeCustomer.findOne({ + customer_id: metadata.subscription.customer_id }); + if (customer) { + await StripeCustomerSubscription.upsert(metadata.subscription, { + subscription_id: metadata.subscription.subscription_id + }); + } } if (metadata.webhook) {