Stripe API refund after subscription cancelled

前端 未结 4 803
心在旅途
心在旅途 2021-01-17 20:03

From the Stripe docs:

When you cancel the subscription, the customer\'s card will not be charged again, but no money will be refunded either. If you

4条回答
  •  难免孤独
    2021-01-17 20:31

    After researching for a while, I came to this flow written in JavaScript for Node.js:

    refundAndUnsubscribe = async function () {
        try {
    
            // Set proration date to this moment:
            const proration_date = Math.floor(Date.now() / 1000);
    
            let sub = await stripe.subscriptions.retrieve("sub_CILnalN9HpvADj");
    
            // See what the next invoice would look like with a plan switch
            // and proration set:
            let items = [{
                quantity: 0,
                id: sub.items.data[0].id,
                plan: "your_plan" // Switch to new plan
            }];
    
    
            let invoices = await stripe.invoices.retrieveUpcoming('cus_CIP9dtlq143gq7', 'sub_CILnalN9HpvADj', {
                subscription_items: items,
                subscription_proration_date: proration_date
            });
    
            //List all invoices
            let payedInvoicesList = await stripe.invoices.list({
                customer: 'cus_CIP9dtlq143gq7'
            });
    
            // Calculate the proration cost:
            let current_prorations = [];
            let cost = 0;
            for (var i = 0; i < invoices.lines.data.length; i++) {
                let invoice_item = invoices.lines.data[i];
                if (invoice_item.period.start == proration_date) {
                    current_prorations.push(invoice_item);
                    cost += invoice_item.amount;
                }
            }
    
            //create a refund
            if (cost !== 0) {
                cost = (cost < 0) ? cost * -1 : cost //A positive integer in cents
    
                let refund = await stripe.refunds.create({
                    charge: payedInvoicesList.data[0].charge,
                    amount: cost
                });
            }
    
            // delete subscription
            return stripe.subscriptions.del('sub_CILnalN9HpvADj');
    
        } catch (e) {
            console.log(e);
        }
    }
    

提交回复
热议问题