# Chargebee subscription cancelled notifications on your phone

> Get a push notification when a Chargebee subscription ends, with your cancellation reason code or the reason Chargebee cancelled it.

- Company: Chargebee (https://www.justpush.io/recipes/chargebee)
- Event: `subscription_cancelled` (subscription_cancelled)
- Tags: Payments & billing, Subscriptions
- Install: https://studio.justpush.io/recipes/chargebee/subscription-cancelled
- Web page: https://www.justpush.io/recipes/chargebee/subscription-cancelled

## Setup

1. Click Install in Studio and sign in. The recipe is added to your account and you get a personal webhook URL.
2. In Chargebee, go to Settings > Configure Chargebee > API Keys and Webhooks, open the Webhooks tab and click Add Webhook.
3. Paste your webhook URL (shown in Studio after install) as the Webhook URL (add ?site=your-site for dashboard buttons).
4. Under Events to Send, pick only subscription_cancelled and save the webhook.
5. Under **Events to Send**, pick only `subscription_cancelled` (Chargebee selects All Events by default). It fires when the subscription actually ends. A cancellation scheduled for the end of the term sends `subscription_cancellation_scheduled` first, which this recipe ignores, so you get one push when it ends.
6. **Dashboard button:** Chargebee events don't include your site's name, so add it to the webhook URL to get a button that opens the subscription in Chargebee. Use the part before `.chargebee.com` in your dashboard address (test sites usually end in `-test`):
7. ```
8. your webhook URL (shown in Studio after install)?site=your-site
9. ```
10. Without `?site=` the push arrives without a button.
11. Built for API version **v2** events. Chargebee's **Test Webhook** button sends a sample of the event you pick, which should give a normal push.
12. Chargebee doesn't sign webhooks. It can send a username and password (basic authentication), but JustPush doesn't check them yet, so you can leave that off. Keep your endpoint URL private.

## Code

Studio calls `handleRequest(request)` with the incoming webhook (`{ method, headers, body, query, raw }`) and sends the message object it returns. Returning `null` sends nothing.

```js
// Chargebee → subscription_cancelled
// Fires when a subscription actually ends: cancelled right away, at the end of its term, or for non-payment.
// Docs: https://apidocs.chargebee.com/docs/api/events/webhook/subscription_cancelled
//
// Paste this into a JustPush Studio integration and add a Chargebee webhook for the
// "subscription_cancelled" event pointing at the integration's endpoint URL.
// Add ?site=your-site to the URL to get a button that opens the subscription in Chargebee.

// Reasons Chargebee sets itself when it cancels a subscription (subscription.cancel_reason).
const AUTO_REASONS = {
    not_paid: "not paid",
    no_card: "no card on file",
    fraud_review_failed: "failed fraud review",
    non_compliant_eu_customer: "non-compliant EU customer",
    non_compliant_customer: "non-compliant customer",
    tax_calculation_failed: "tax calculation failed",
    currency_incompatible_with_gateway: "currency not supported by the gateway",
}

// Cancelled because the money didn't come in: involuntary churn you may want to chase.
const PAYMENT_REASONS = new Set(["not_paid", "no_card"])

// A trimmed string, or null for anything else.
function text(value) {
    return typeof value === "string" && value.trim() ? value.trim() : null
}

// Look a key up in a table without tripping over inherited names such as "toString".
function pick(table, key, fallback) {
    return typeof key === "string" && Object.prototype.hasOwnProperty.call(table, key) ? table[key] : fallback
}

// Only link to real http(s) URLs.
function link(url, cta) {
    return typeof url === "string" && /^https?:\/\//.test(url) ? [{ cta, url }] : []
}

// Chargebee events don't carry your site's name, so the dashboard link needs ?site=acme
// (or ?site=acme-test for a test site) on the webhook URL.
function adminUrl(request, path, id) {
    const raw = Array.isArray(request.query?.site) ? request.query.site[0] : request.query?.site
    const site = (typeof raw === "string" ? raw : "")
        .trim()
        .toLowerCase()
        .replace(/^https?:\/\//, "")
        .replace(/\.chargebee\.com.*$/, "")

    if (!/^[a-z0-9][a-z0-9-]*$/.test(site) || !text(id)) return null
    return `https://${site}.chargebee.com/d/${path}/${encodeURIComponent(id)}`
}

// "Jane Doe", or the company or email when there's no name.
function customerName(customer) {
    const name = [text(customer?.first_name), text(customer?.last_name)].filter(Boolean).join(" ")
    return name || text(customer?.company) || text(customer?.email)
}

// The plan's item price ID (Product Catalog 2.0) or plan ID (Product Catalog 1.0).
function planName(subscription) {
    const items = Array.isArray(subscription.subscription_items) ? subscription.subscription_items : []
    const item = items.find((entry) => entry?.item_type === "plan") ?? items[0]
    return text(item?.item_price_id) ?? text(subscription.plan_id)
}

function handleRequest(request) {
    const event = request.body && typeof request.body === "object" ? request.body : {}

    // Guard: only this event type, so other Chargebee events on this integration stay quiet.
    // Chargebee sends no event header, so the payload's event_type decides.
    if (
        event.event_type !== "subscription_cancelled" ||
        (event.object !== undefined && event.object !== "event") ||
        !event.content?.subscription ||
        typeof event.content.subscription !== "object"
    ) {
        console.log(`Ignoring Chargebee event "${text(event.event_type) ?? "unknown"}"`)
        return null
    }

    const subscription = event.content.subscription
    const who = customerName(event.content.customer) ?? "a customer"
    const plan = planName(subscription)
    // Your own cancellation reason code wins; otherwise the reason Chargebee set itself.
    const reason = text(subscription.cancel_reason_code) ?? pick(AUTO_REASONS, subscription.cancel_reason, null)
    const unpaid = PAYMENT_REASONS.has(subscription.cancel_reason)

    return {
        title: "👋 Subscription cancelled",
        message: `${plan ? `${plan} for ` : "Subscription for "}${who} has ended` + (reason ? ` — ${reason}` : ""),
        topic: "Chargebee",
        // High when it ended because payment never came in (you may want to chase it),
        // Normal otherwise — worth knowing, nothing to fix right now.
        priority: unpaid ? 1 : 0,
        buttons: link(adminUrl(request, "subscriptions", subscription.id), "View subscription"),
    }
}
```

## Chargebee subscription_cancelled webhook payload (sample)

```json
{
  "id": "ev_test_subscription_cancelled",
  "object": "event",
  "source": "portal",
  "content": {
    "customer": {
      "id": "cus_test_16BjpLU3",
      "email": "jane@example.com",
      "object": "customer",
      "last_name": "Doe",
      "first_name": "Jane"
    },
    "subscription": {
      "id": "sub_test_16BjpLU3",
      "object": "subscription",
      "status": "cancelled",
      "customer_id": "cus_test_16BjpLU3",
      "cancelled_at": 1790584200,
      "currency_code": "EUR",
      "billing_period": 1,
      "cancel_reason_code": "Too expensive",
      "subscription_items": [
        {
          "amount": 2900,
          "quantity": 1,
          "item_type": "plan",
          "unit_price": 2900,
          "item_price_id": "Pro-EUR-Monthly"
        }
      ],
      "billing_period_unit": "month"
    }
  },
  "event_type": "subscription_cancelled",
  "api_version": "v2",
  "occurred_at": 1790584200,
  "webhook_status": "scheduled"
}
```

## FAQ

### Does this work on iPhone and Android?

Yes. Install the JustPush app from the App Store or Google Play and sign in. Every phone signed in to your account gets the notification.

### Do I need to write code?

No. Install the recipe in Studio, paste your webhook URL into Chargebee and you are done. The code is there if you want to change the text, the sound or the buttons.

### Can I change what the notification says?

Yes. After install the recipe's code is yours. Edit it in Studio and test it against the sample payload before you save.

### What does it cost?

JustPush is free for 30 days. After that it's $19.99 a year, or $39.99 once. There is no extra charge for recipes.
