From 0dad6d147f9651a174dffd5f3392a4933dff846d Mon Sep 17 00:00:00 2001 From: Rishabh Garg Date: Thu, 20 Aug 2020 14:24:29 +0530 Subject: [PATCH] Added update subscription method to members api (#198) refs TryGhost/Ghost#12127 - Adds new `updateSubscription` method to members-api which allows updating individual subscription for a member - New method only allows toggling of cancellation at period end for a subscription at the moment --- ghost/members-api/lib/users.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ghost/members-api/lib/users.js b/ghost/members-api/lib/users.js index e05ebe1b87..a76f653985 100644 --- a/ghost/members-api/lib/users.js +++ b/ghost/members-api/lib/users.js @@ -1,5 +1,6 @@ const _ = require('lodash'); const debug = require('ghost-ignition').debug('users'); +const common = require('../lib/common'); module.exports = function ({ stripe, @@ -86,12 +87,38 @@ module.exports = function ({ return stripe.setComplimentarySubscription(member); } + async function updateSubscription(memberId, {cancelAtPeriodEnd, subscriptionId}) { + // Don't allow removing subscriptions that don't belong to the member + const member = await get({id: memberId}); + const subscriptions = await stripe.getSubscriptions(member); + const subscription = subscriptions.find(sub => sub.id === subscriptionId); + if (!subscription) { + throw new common.errors.BadRequestError({ + message: 'Updating subscription failed! Could not find subscription' + }); + } + + if (cancelAtPeriodEnd === undefined) { + throw new common.errors.BadRequestError({ + message: 'Updating subscription failed!', + help: 'Request should contain "cancel" field.' + }); + } + const subscriptionUpdate = { + id: subscription.id, + cancel_at_period_end: !!(cancelAtPeriodEnd) + }; + + await stripe.updateSubscriptionFromClient(subscriptionUpdate); + } + return { create, update, list, get, destroy, + updateSubscription, setComplimentarySubscription: safeStripe('setComplimentarySubscription'), setComplimentarySubscriptionById, cancelComplimentarySubscription: safeStripe('cancelComplimentarySubscription'),