#Adi

1 messages · Page 1 of 1 (latest)

ancient havenBOT
river jay
#

Hi! Let me help you with this.

#

You can just stop listening to the checkout.session.completed, and only listen to the invoice.paid event.

worldly prawn
#

but I am passing meta data to checkout session i.e priceId and userId and based on that I update customer object in DB

#
if (event.type === 'checkout.session.completed') {
            const eventData = event.data.object;

            const { customer, subscription, metadata } = eventData;
            const { userId, priceId } = metadata;
            let credits = 500;

            // $39 plan
            if (priceId === STRIPE_BASIC_PLAN) {
                credits = 2000
            } // $129 plan 
            else if (priceId === STRIPE_STANDARD_PLAN) {
                credits = 10000
            }

            await usersCollection.updateOne({ userId: userId }, { $set: { "priceId": priceId, "subscription": subscription, "customer": customer, "trial": false, "credits": credits } });

            logger.info("checkout.session.completed event: ", eventData);
worldly prawn
river jay
#

You can put metadata in subscription_data.metadata so it is always present on the Subscription object.

worldly prawn
#

If I add logic in invoice paid event then lets say if I have new customer making purchase. In that case checkout.session and invoice paid both will get triggered and it will add extra credits to user

#

Are you getting my point?

river jay
#

I get your point. That's because implementation was not correct from the very beginning.

To fix this you will need to retrieve the metadata from the original Checkout Session and copy it to the Subscription object. You can do it every time, but it might be easier to run a one-time migration. You can find the Checkout Session by searching by a Subscription ID: https://stripe.com/docs/api/checkout/sessions/list#list_checkout_sessions-subscription

#

You can also listen to customer.subscription.updated event, but you will still need to search for the original Checkout Session to fetch the metadata.

worldly prawn
#

Is there any reference or sample code available in nodejs Javascript which handles all these events and logic?

#

I can refer them

river jay
#

Yes, you can change the language at the top

river jay
worldly prawn
river jay
#

Yeah, that's one way.
Not sure what will be the reason in the subsequent invoices tho

#

Let me check

worldly prawn
#

if billing_reason has value subscription_create then I don't run my logic on customer object. If it not then I can run logic on customer object based on priceId and customerId present in invoice object

#

Can you also let me know what are all possible values of billing reason field ?

river jay
#

I checked and the next billing_reason will be subscription_cycle

worldly prawn
#

ok got it then it will work in my case. But what if someone upgrades plan or downgrades it?

river jay
ancient havenBOT
worldly prawn