Katana24
Katana24

Reputation: 8959

How do I differentiate between an initial payment and a recurring one using webhooks for Stripe?

Here's a summary of what I've found in relation to the question:

https://stripe.com/docs/billing/subscriptions/overview#subscription-events

Each event object will have a type key associated with it to identify the event that has just occurred. Typically we’ll want to run a check on this to determine any actions (e.g. switch statement) & for Node implementations, it may look like this:

router.post("/webhook", bodyParser.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = req.body;
  } catch (err) {
    res.status(400).send("Webhook error: ${err.message}");
  }
  
  switch(event.type) {
    // Subscription created 
    case "customer.subscription.created":
      const subCreated = event.data.object;
      // Do stuff, e.g. email success
    break;
    // Recurring payments 
    case "invoice.paid":
      const invPaid = event.data.object;
      // Do other stuff
    break;
    default:
      return res.status(400).end();
  }
  res.json({ received: true });
});

Subscription Payment events:

Will trigger the invoice.created & invoice.finalized events; they occur before the payment_intent.created & payment_intent.succeeded events.

If we only want to take action on a successful payment then payment_intent.succeeded is the correct event. If we want to wait until the invoice has completed then we’d observe the invoice.paid event.

New Payments Will create a new subscription associated with the customer and will trigger the customer.subscription.created event; this event occurs last i.e. after a payment has succeeded.

Recurring Payments Will not trigger the above event but will move through the same lifecycle as any other subscription payment event so it would sufficient to just observe the invoice.paid event only (see the code above for the flow)

But from what I've found, the event customer.subscription.created occurs last on the initial payment, so the code I have above will run for both as multiple events are emitted for each, so how do I differentiate between the two?

Thanks!

Upvotes: 0

Views: 871

Answers (1)

v3nkman
v3nkman

Reputation: 1179

The initial Invoice from a new subscription will have a billing_reason of subscription_create, Invoices that are created by the Subscription renewing/recurring will have a value of subscription_cycle. You can interrogate that attribute and go from there:

https://stripe.com/docs/api/invoices/object#invoice_object-billing_reason

Upvotes: 4

Related Questions