Reputation: 4806
How can I report how much a customer has used of the service right before the billing period ends in Stripe?
What I found in the docs is that usage can be reported periodically, but in my use case I just want to charge the user in function of how much they used the service. For example if the user has used 900 (arbitrary unit) during the billing period (monthly in my case), then I want to charge them for example 3% of 900 in usd. I can't report usage as it happens because it happens way too often and the sql query to get it is somewhat expensive. But I could at the end of the month get the total usage during that month.
I was thinking I could do this by creating a monthly recurring price for the product with metered usage, and then use a webhook event at the end of the month to report usage. But I'm not sure what webhook event I should be listening to.
Upvotes: 4
Views: 1687
Reputation: 4806
I achieved this by completely ditching the metered price and creating a normal monthly price for the product with $0/month. I then listen to the invoice.created
webhook, and I check if the invoice is for this new price, and if so I'd add invoiceItems
to the invoice with an inline price describing how much the user should pay (which is of course calculated in function of the customer's recorded usage) :
$stripe->invoiceItems->create(
[
'customer' => $customer,
'invoice' => $invoiceId,
'price_data' => [
'currency' => 'usd',
'product' => $product,
'unit_amount_decimal' => $howMuchToPay * 100 //because in cents
]
]
);
This is possible because when the invoice is created, it can still be edited until it's finalized
.
Upvotes: 4
Reputation: 1938
If you want to collate usage into a single report request, you have up until 5 minutes after the end of the billing period to report usage for that period. Based on that, my recommendation would be to:
customer.subscription.updated
events which will fire to reflect the start of a new billing period.current_period_start
timestamp from the webhook event, and make the required API request to Stripe reporting the usage.Upvotes: 1