Skip to content

Instantly share code, notes, and snippets.

@cptiwari20
Created September 14, 2020 16:51
Show Gist options
  • Save cptiwari20/28d79f4e13161b9c13cebfa5f5a6333b to your computer and use it in GitHub Desktop.
Save cptiwari20/28d79f4e13161b9c13cebfa5f5a6333b to your computer and use it in GitHub Desktop.
Handle Pabbly webhook events for your nodejs application
const pabblyWebhook = async (req, res, next) => {
if(req.body.event_name === 'test_webhook_url') return res.status(200).json({status: true, message: 'Tested data found'})
if(!req.body.data) return res.status(422).json({status: false, message: 'No data found'})
if(!req.body.event_type) return res.status(422).json({status: false, message: 'No event_type found'})
if(!req.body.data.id) return res.status(422).json({status: false, message: 'No id found'})
const subscription_id = req.body.data.id
try {
const subscription = await Subscriptions.findOne({subscription_id})
if(!subscription) return res.status(422).json({status: false, message: 'Subscription not found'})
switch (req.body.event_type) {
case 'subscription_cancel':
await subscription.updateOne(
{
$set: {
status: 'cancelled',
updated_at: new Date().now,
expiry_date: new Date().now,
}
},
);
return res.status(200).json({status: true, message: 'Subscription cancelled'})
case 'subscription_cancel_scheduled':
const resp = await subscription.updateOne(
{
$set: {
status: 'nonrenewing',
updated_at: new Date().now,
expiry_date: subscription.next_billing_date,
}
},
{ runValidators: true }
);
return res.status(200).json({status: true, message: 'Subscription subscription_cancel_scheduled event updated'})
case 'subscription_activate':
await subscription.updateOne(
{
$set: {
status: req.body.data.status,
updated_at: new Date().now,
expiry_date: req.body.data.expiry_date,
canceled_date: req.body.data.canceled_date,
last_billing_date: req.body.data.last_billing_date,
next_billing_date: req.body.data.next_billing_date
}
}
);
return res.status(200).json({status: true, message: 'Subscription subscription_activate event updated'})
// case 'subscription_activate':
// await subscription.updateOne(
// {
// $set: {
// status: req.body.data.status,
// updated_at: new Date().now,
// expiry_date: subscription.next_billing_date,S
// }
// }
// );
// return res.status(200).json({status: true, message: 'Subscription updated'})
default:
await subscription.updateOne(
{
$set: {
...req.body.data
}
}
)
return res.status(200).json({status: true, message: 'Subscription updated'})
}
} catch (error) {
console.log(error.message)
return res.status(500).json({status: false, message: error.message, error})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment