Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I cancel Subscription in stripe inside react

I am using react. I want to delete old subscription when user changes his subscription plan.

this is my code.

import {loadStripe, useStripe} from '@stripe/stripe-js'

const loadCheckout = async (priceId) =>{
    const docRef = await db
    .collection('customers')
    .doc(user.uid)
    .collection('checkout_sessions')
    .add({
        price:priceId,
        success_url:window.location.origin,
        cancel_url: window.location.origin,
    })
    docRef.onSnapshot(async (snap) =>{
        const {error, sessionId} = snap.data();
        if(error){
            alert(`an error occured ${error.message}`)
        }
        if(sessionId){
            const stripe = await loadStripe("pk_test_51JG0BKLXYmn2IpSgISeCDbsCNllISGA3PvEbSzBz5bpo8WTvmqI6UKCbzpxX92LKiN0hftRrobm1J6wJZPCOWSTs0081pmQFJE")
            const deleted = await stripe.subscriptions.del(
                subscription.id
              );
              console.log(deleted)
            stripe.redirectToCheckout({sessionId});
        }
    })
    
}

my code give an error saying stripe.subscriptions.del is not a function. the code work if I remove this line the payment is successful and all. In stripe API Docs its says to use .del() but it isnt working here.

like image 877
Fahad Nadeem Avatar asked Sep 11 '25 18:09

Fahad Nadeem


2 Answers

Your React code uses Stripe.js which is a client-side library. It cannot modify Subscriptions, only secret key API calls can do that which Stripe.js does not use.

You need to make the request to update/delete the Subscription, you need to make the request server-side (in your Firebase app) using the stripe-node library and your secret API key: https://stripe.com/docs/api/subscriptions/cancel?lang=node.

like image 160
hmunoz Avatar answered Sep 14 '25 07:09

hmunoz


You can use "customer portal" option inside Stripe to avoid backend coding.

It will generate a link to a page where your customer will be able to cancel the subscription.

Inside Stripe: Billing -> subscriptions -> Setup Customer portal

like image 28
Mario Avatar answered Sep 14 '25 07:09

Mario