diff --git a/ghost/members-api/index.js b/ghost/members-api/index.js index 9ef190aac4..ac5f8b6246 100644 --- a/ghost/members-api/index.js +++ b/ghost/members-api/index.js @@ -119,7 +119,8 @@ module.exports = function MembersApi({ const users = Users({ stripe, - Member + Member, + StripeCustomer }); async function sendEmailWithMagicLink({email, requestedType, tokenData, options = {forceEmailType: false}, requestSrc = ''}) { diff --git a/ghost/members-api/lib/users.js b/ghost/members-api/lib/users.js index b6df68d321..78abbf32cd 100644 --- a/ghost/members-api/lib/users.js +++ b/ghost/members-api/lib/users.js @@ -4,7 +4,8 @@ const common = require('../lib/common'); module.exports = function ({ stripe, - Member + Member, + StripeCustomer }) { async function get(data, options) { debug(`get id:${data.id} email:${data.email}`); @@ -127,6 +128,23 @@ module.exports = function ({ await stripe.updateSubscriptionFromClient(subscriptionUpdate); } + async function linkStripeCustomer(id, member, options) { + if (!stripe) { + throw new common.errors.BadRequestError({ + message: 'Cannot link Stripe Customer without a Stripe connection' + }); + } + const existingCustomer = await StripeCustomer.findOne({customer_id: id}, options); + + if (existingCustomer) { + throw new common.errors.BadRequestError({ + message: 'Cannot link Stripe Customer already associated with a member' + }); + } + + return stripe.linkStripeCustomer(id, member, options); + } + return { create, update, @@ -141,7 +159,7 @@ module.exports = function ({ getStripeCustomer: safeStripe('getCustomer'), createStripeCustomer: safeStripe('createCustomer'), createComplimentarySubscription: safeStripe('createComplimentarySubscription'), - linkStripeCustomer: safeStripe('linkStripeCustomer'), + linkStripeCustomer, linkStripeCustomerById }; };