diff --git a/packages/backend/src/controllers/paddle/webhooks.ee.ts b/packages/backend/src/controllers/paddle/webhooks.ee.ts index eeb83e5a..272bbfdb 100644 --- a/packages/backend/src/controllers/paddle/webhooks.ee.ts +++ b/packages/backend/src/controllers/paddle/webhooks.ee.ts @@ -11,6 +11,8 @@ export default async (request: IRequest, response: Response) => { if (request.body.alert_name === 'subscription_created') { await Billing.webhooks.handleSubscriptionCreated(request); + } else if (request.body.alert_name === 'subscription_payment_succeeded') { + await Billing.webhooks.handleSubscriptionPaymentSucceeded(request); } return response.sendStatus(200); diff --git a/packages/backend/src/helpers/billing/webhooks.ee.ts b/packages/backend/src/helpers/billing/webhooks.ee.ts index 791708bc..cff68574 100644 --- a/packages/backend/src/helpers/billing/webhooks.ee.ts +++ b/packages/backend/src/helpers/billing/webhooks.ee.ts @@ -1,10 +1,29 @@ import { IRequest } from '@automatisch/types'; import Subscription from '../../models/subscription.ee'; +import Billing from './index.ee'; const handleSubscriptionCreated = async (request: IRequest) => { await Subscription.query().insertAndFetch(formatSubscription(request)); }; +const handleSubscriptionPaymentSucceeded = async (request: IRequest) => { + const subscription = await Subscription.query() + .findOne({ + paddleSubscriptionId: request.body.subscription_id, + }) + .throwIfNotFound(); + + const remoteSubscription = await Billing.paddleClient.getSubscriptionPlan( + Number(subscription.paddleSubscriptionId) + ); + + await subscription.$query().patch({ + nextBillAmount: remoteSubscription.next_payment.amount.toFixed(2), + nextBillDate: remoteSubscription.next_payment.date, + lastBillDate: remoteSubscription.last_payment.date, + }); +}; + const formatSubscription = (request: IRequest) => { return { userId: JSON.parse(request.body.passthrough).id, @@ -20,6 +39,7 @@ const formatSubscription = (request: IRequest) => { const webhooks = { handleSubscriptionCreated, + handleSubscriptionPaymentSucceeded, }; export default webhooks;