API Reference

πŸ” Upsell Subscription with Cancellation & Refund

This guide shows how to handle a subscription upsell: when a user upgrades, cancel their previous subscription and optionally refund the last invoice.


πŸ”— API References


πŸ“‹ When to Use This

Use this logic if:

  • A user upgrades to a new plan.
  • You want to cancel the previous subscription automatically.
  • You optionally want to refund the last invoice of the canceled subscription.

βœ… Steps

1. Access window.subscriptions

const subscriptions = window.subscriptions || [];

Each object contains details like:

{
  id: 308308,
  price_id: "price_1QrEIVHCcS7hScp6SvOoSaIL",
  status: "active",
  invoices: [
    {
      id: "in_1ROelZHCcS7hScp6qarbeZWB",
      status: "paid"
    }
  ],
  ...
}

2. Identify New (Upsell) and Old (Previous) Subscriptions

Replace the priceIdToKeep and priceIdToCancel with your actual values.

const priceIdToKeep = "price_1UpsellNewID";      // new upsell price_id
const priceIdToCancel = "price_1PreviousOldID";  // old subscription price_id

const activeSubs = subscriptions.filter(sub => sub.status === "active");

const newSubscription = activeSubs.find(sub => sub.price_id === priceIdToKeep);
const oldSubscription = activeSubs.find(sub => sub.price_id === priceIdToCancel);

3. Cancel the Old Subscription

if (newSubscription && oldSubscription) {
  fetch("https://your-api.com/api/subscription/cancel", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ subscription_id: oldSubscription.id })
  })
    .then(res => res.json())
    .then(data => {
      console.log("Subscription canceled:", data);
      refundOldInvoice(oldSubscription);
    })
    .catch(err => console.error("Cancel error:", err));
}

4. Refund the Last Invoice

function refundOldInvoice(subscription) {
  const invoice = subscription.invoices?.[0]; // assume first is latest
  if (!invoice || invoice.status !== "paid") return;

  fetch("https://your-api.com/api/subscription/refund", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ invoice_id: invoice.id })
  })
    .then(res => res.json())
    .then(data => console.log("Invoice refunded:", data))
    .catch(err => console.error("Refund error:", err));
}

🧠 Edge Cases to Handle

  • Only cancel if status === "active".
  • Only refund invoices with status === "paid".
  • Ensure you only refund the latest invoice.

🧩 Summary Flow

1. User subscribes to upsell
2. Check window.subscriptions for both old and new
3. Cancel old subscription via API
4. Refund latest invoice (if needed)

Use these API endpoints:

  • PUT /api/subscription/cancel
  • PUT /api/subscription/refund