feat: Handle subscription payment succeeded event

This commit is contained in:
Faruk AYDIN
2023-03-25 14:24:24 +03:00
parent 62b9a8071a
commit 3534712478
2 changed files with 22 additions and 0 deletions

View File

@@ -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);

View File

@@ -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;