DEV Community

Discussion on: Stripe - Upgrading a subscription synchronously (immediately charge for a proration without webhooks)

Collapse
 
marckohlbrugge profile image
Marc Köhlbrugge

Just a heads up for anyone else that gets erratic behavior with this code:

current_prorations = invoice.lines.data.select { |ii| ii.period.start == proration_date }

All line items seem to match the select statement, so it returns whatever line item happens to be first in the array. It seems that order is random. So sometimes you end up getting the pro-rated amount the customer needs to pay, while other times, you get the "unused amount" on the current subscription period, which is basically the discount amount itself.

I think the official Stripe Docs had this same code, but this part has since been removed. They don't provide an alternative, but one way would be to look for the line item with "Remaining time on" in the description.

Collapse
 
marckohlbrugge profile image
Marc Köhlbrugge

I haven't thoroughly tested, but this seems to work more reliably:

invoice.lines.data.pluck(:amount).keep_if(&:negative?).inject(:+)

👆 This returns the 'unused amount'. So if a customer is halfway through a $25/mo period, this would be about $12.50

It looks through all the line items, selects just the negative amounts, and adds them all up. Usually this is just one line item, but in theory it could be multiple.

invoice.total

👆 This is pretty simple. It's the total amount (including any taxes) the customer were to pay. So continuing the $25/mo example, with let's say a $200/year annual plan, this would be about $200 - $12.50 (see above) = $187.50