Stripe CLI: testing action when trial period ends - stripe-payments

I'd like to be able to test locally that the correct actions are taken when the trial period for a user ends.
I set up the Stripe CLI, and start listening:
stripe listen --forward-to http://localhost:8000/api/stripe-webhook
When a trial comes to an end, the customer.subscription.updated event will occur.
I trigger this event using the Stripe CLI:
stripe trigger customer.subscription.updated
On my server side I can see that payload['data']['previous_attributes'] contains a metadata array with foo = null. When a trial ends, we should get previous_attributes containing something like: { "status": "trialing"...
I'm wondering if it's possible to trigger an event using the Stripe CLI that mimics a user trial ending (or maybe even just a way to set the previous_attributes to similar values that'd occur in a live environment when a trial ends)? If it's possible to do that then it'd be a little easier to test locally that the appropriate action occurs when a trial ends without pushing to a prod-like environment.

The easiest way is probably to just use trial_end to set a very short trial period either when creating a subscription, or on an existing subscription, and wait a couple of minutes for it to end, at which point it will generate the appropriate events.
stripe subscriptions update sub_HpOl9vDMzIEfGf --trial-end=`date -v +5M +%s`
https://stripe.com/docs/billing/testing#trials
https://stripe.com/docs/api/subscriptions/update#update_subscription-trial_end

Related

Stripe: Get total successfully paid invoices count

I'm using stripe for subscription. Where i need to fire an event after 3 successfully charges.
For this i am using invoice.payment_succeeded webhook.
But there is no key which specify the number of this recurring payment means whether it is first or second or nth charge. So how could i get the number of successfully payment made on a subscription.
You can call the https://api.stripe.com/v1/invoices API endpoint with the customer's ID, the status parameter set to paid and optionally, the subscription parameter and then count how many invoices were returned.
There are some other parameters, like limit, starting_after, etc. that you can send it too.
The invoice.payment_succeeded webhook sends the invoice object in the data.object field so you should be able to get the customer and subscription values from it.
I'd recommend doing the invoices call asynchronously to ensure that the webhook call doesn't time out.
FYI there is an expand to it, like with the current node api;
const ret = await stripe.invoices.list(
{
expand: ["total_count"],
limit: 0,
});
console.log(ret.total_count)
It can be called with ${url}?expand[]=total_count&limit=0 too, if you need to write it by hand.
I did not found this in the documentation, but some libs using it, and it is indeed works. (But be careful, if it is not documented it could stop working too.)
Here is the docs; https://stripe.com/docs/api/pagination/search#search_pagination-total_count
Yes, as it is stated in the answer by D Malan, you can use the https://api.stripe.com/v1/invoices endpoint.
Though there is one thing to keep in mind when retrieving data from Stripe.
You can only get 100 items per call. Therefore, if you had recurring payment that generates more than 100 invoices after some time, you wouldn't be able to get the total count in one call. I suggest storing invoices/payment intents to your database and then using your DB engine to count the results.
Keep in mind that you should listen to invoice.payment_succeeded event in order to keep your database in sync, if you store the invoice or payment intent beforehand, while its status is not paid or succeeded, respectively.

NodeJs - setTimeout() for delete user subscription from db

I am new to nodeJs.
I am developing a platform where users can subscribe in trial or pro version. I would like to know if I can use the setTimeout method to delete a user's info from db after the subscription expiration date. if this is not possible is there a way to do it or a library that allows you to manage subscriptions?
You can, but it would not be a good approach since you be manging that on memory and if your server restarts you will lose this subscription status.
Why don't you just save on database the subscription date and on user login verify if the subscription date difference from the now is greater than the period of free subscription?
A solution to your problem is to run a CRON job. That may run once every 24 hours to check user's subscription's and if trial has expired then delete the user. You can use the cron npm package to achieve this.
setTimeout is not reliable, service can go up or down and your request should be persistent.
You need an offline job manager, DB-based, like agenda or similar.
Question is also discussed widely here: I need a Nodejs scheduler that allows for tasks at different intervals
Other solution: create TTL Index. Mongodb periodically checks and remove expired users.
You don't need to write any extra code / logic.

Stripe subscriptions: Modify when period ends instead of now

Context: There is a Stripe plan "Starter". The customer subscribes to the "Starter" plan. Within a subscription period the user wants to up- or downgrade the subscription (in my case: the quantity will be increased or decreased). Programmatically I want to achieve this with a subscription update.
Problem: Stripe wants to make the update immediately. But I want to have it changed at the end of the period.
Alternatives:
I saw this Stackoverflow asking exact the same question, but is six years ago -> Stripe: downgrade a user at "period end". The proposed solutions are not really reflecting the desired solution and also do not work for me.
I saw that Stripe has a subscription schedule API. Is this probably related to the problem solution?
I'm relly looking forward for (high-level) solutions to solve this problem. Thank you in advance.
So you want to update the subscription details at the end of the current period. In that case, you may want to use the subscription webhook events mentioned here
"When the subscription period elapses, invoice.created event is sent, indicating the creation of a draft invoice."
"About an hour after the invoice is created, it is finalized (changes are no longer permitted), and an invoice.finalized event is sent."
So you can listen to that invoice.created event and then update the subscription.
This is what I discussed with the Stripe support channel:
I understand that scheduling is not the best fit for you, as you'd
have to release the schedule once the update is made so the new
subscription rolls over, and this doesn't cancel the subscription, but
start a new one.
What you could do, is to cancel the first subscription at_period_end,
and then start the next one when the event
customer.subscription.deleted comes through:
https://stripe.com/docs/api/events/types#event_types-customer.subscription.deleted
If you don't want to use Webhooks, you can also cancel at period end
and then generate the new subscription at the same time using the
billing cycle anchor
https://stripe.com/docs/api/subscriptions/create#create_subscription-billing_cycle_anchor.
This will only work though for subscriptions with the same interval,
or if the second subscription interval is shorter than the first.
I implemented the webhook solution. It works perfectly for me.

Getting notification of sales/refunds done through Square POS/Connect

I would like to integrate my web application with the Square POS.
The goal would be to be notified each time a transaction (sale/refund/etc) is processed by Square for an account so that I can update inventory levels etc, ultimately so I can update inventory levels as transactions occur.
From what I can tell, it seems that the Square API's seem to be designed around my application initiating the transaction, then handing off to Square to process the payment. I simply want to be notified that a transaction has happened so that I can update inventory.
Is it possible to do this? Or is the Square API just for processing payments?
edit: After some more reading, I still haven't found a webhook to be notified, but it looks like I can ListTransactions, and RetrieveTransaction, so if I poll I should be ok.
You’re correct. Square’s API Webhooks will be what you’ll use to be notified each time a transaction is created or updated. We have a quick setup guide available in Square’s Developer Doc (https://docs.connect.squareup.com/api/connect/v1/?q=webhooks#setupwebhooks).
The PAYMENT_UPDATED webhook will alert you every time a payment is made, so that you can update your inventory.

Time based notifications service

I am dealing with subscriptions where a user is subscribed to a plan and it has an expiration.
So basically each user store has an expiration field.
I want to be able to get notified when a user plan is expired as soon as it is actually expired.
Right now, I have a job that runs on all users once a day and check if anyone has expired but ideally I would like to get a server postback or some sort of event whenever a user is expired without running this each day.
Can you think of any third party service / database / other tool that deals with these sort of things ?
A lot of services, Stripe for example, notify you with a webhook whenever a user's subscription is renewed / expired. Are they just running a job repeatedly like I am ?
Hope I made myself clear enough, would appreciate help in how to focus my search in Google as well.
My current stack is Mongodb, Node.js, AWS
Thanks
We do not know for sure, how Stripe handles it.
There are two solutions coming to my mind. Let's start with the simple one:
Cronjob
As you mentioned, you already have a Cronjob solution, but you can instead make it run each hour, or each 10 minutes. Just ensure you optimize your query to the maximum, so that it is not super-heavy to run.
It is attractive, easy to implement, very few edge cases, but as you might have though can be a performance drag once you reach millions of clients.
Timers
Implementation varries, and you need to worry about the edge cases, but the concept:
On day start* (00:00) query for all clients who are set to expire today, save them into array (in-memory). Sort the array by time (preferably descending).
Create timer to execute on last array's element time.
Function: If Client X expires now, query database to ensure subscription was not extended. Notify if it wasn't.
Remove Client X from the tracked array. Repeat step 2.
On day start* - Also run it on script launch.

Resources