Home > Mobile >  Stripe subscription Id coming back undefined when querying by customer ID
Stripe subscription Id coming back undefined when querying by customer ID

Time:01-10

My stripe customer ID is no longer querying the corresponding subscription ID from stripe and the results come back undefined so my customers can't cancel subscriptions.

I'd like to follow the stripe docs but I can't get the subscription ID to return and I've found a couple examples on stack that recommend the format as customer.subscriptions.data[0] but it's not working as intended (github autopilot also recommends this format).

I'm able to create new customers via the webhook so my connection and stripeSecret are working correctly but how do I fix my code to cancel a subscription using the customer ID:

Controller function

module.exports.cancelSubscription = async (req, res) => {
    const user = await User.findById(req.user.id);
    if (!user) {
        req.flash('error', 'Cannot find that user');
        return res.redirect('/users');
    }

    const customer = await stripe.customers.retrieve(user.stripeId);

    // use customer id to get subscription id
    const subscriptionId = customer.subscriptions.data[0];

    // cancel subscription
    stripe.subscriptions.del(subscriptionId, { at_period_end: false });

    // update user subscription status in my database
    user.subscription.active = "cancelled";
    await user.save();
    req.flash('success', 'Subscription cancelled');
    res.redirect(`/users/${user._id}`);
}

Thank you!

CodePudding user response:

subscriptions parameter in Customer object is not included by default and it's expandable by including it in expand parameter. For example,

const customer = await stripe.customers.retrieve(cus_xxx, {
  expand: ['subscriptions'],
});

const subscriptions = customer.subscriptions.data;

Alternatively, you can also use List Subscriptions API with customer set to retrieve customer's subscriptions.

After the subscriptions are retrieved, you can then delete the subscription individually with Cancel Subscription API.

  • Related