# Polar subscription canceled notifications on your phone

> Get a push notification when a Polar subscription is canceled, with the customer's reason and the date their access ends.

- Company: Polar (https://www.justpush.io/recipes/polar)
- Event: `subscription.canceled` (subscription.canceled)
- Tags: Payments & billing, Subscriptions
- Install: https://studio.justpush.io/recipes/polar/subscription-canceled
- Web page: https://www.justpush.io/recipes/polar/subscription-canceled

## 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 the Polar dashboard, open Settings > Webhooks and click Add Endpoint.
3. Paste your webhook URL (shown in Studio after install) as the URL and leave the format on Raw.
4. Generate a secret (JustPush doesn't need it), tick the subscription.canceled event and save.
5. Tick **subscription.canceled**. By default Polar cancels at the end of the billing period: this event fires straight away while the customer still has access, and the push says until when. When access actually ends, Polar sends `subscription.revoked` (see the *Subscription ended* recipe).
6. If you cancel a subscription with **immediate revocation**, Polar sends `subscription.canceled` and `subscription.revoked` together, so with both recipes installed you'll get two pushes for it.
7. Don't tick `subscription.updated`: it repeats every cancellation as well.
8. Testing in the **sandbox**? Add `?sandbox=1` to the URL so the button opens the sandbox dashboard.
9. Polar signs every delivery (`webhook-id`, `webhook-timestamp`, `webhook-signature`; Standard Webhooks for secrets made on or after 8 September 2026), but JustPush doesn't check that signature yet, so 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
// Polar → subscription.canceled
// Fires when a subscription is canceled, by the customer or by you. With the default
// end-of-period cancellation the customer keeps access until the period ends
// (status "active", cancel_at_period_end true); subscription.revoked follows at the real end.
// Docs: https://polar.sh/docs/api-reference/current/subscription_canceled

// The customer's cancellation reason, in words.
const REASONS = {
    customer_service: "customer service",
    low_quality: "quality",
    missing_features: "missing features",
    switched_service: "switched to another service",
    too_complex: "too complex",
    too_expensive: "too expensive",
    unused: "not using it",
    other: "other",
}

// Polar amounts are in the currency's smallest unit (cents), except zero-decimal currencies.
const ZERO_DECIMAL = new Set([
    "bif", "clp", "djf", "gnf", "jpy", "kmf", "krw", "mga",
    "pyg", "rwf", "ugx", "vnd", "vuv", "xaf", "xof", "xpf",
])

function money(amount, currency) {
    if (typeof amount !== "number" || !Number.isFinite(amount) || typeof currency !== "string" || !currency) return null

    const code = currency.toLowerCase()
    const value = ZERO_DECIMAL.has(code) ? amount : amount / 100

    try {
        return new Intl.NumberFormat("en-GB", { style: "currency", currency: code.toUpperCase() }).format(value)
    } catch {
        return `${value} ${code.toUpperCase()}`
    }
}

// "€19.00/month", or "€49.00 every 3 months".
const INTERVALS = { day: "day", week: "week", month: "month", year: "year" }

function price(sub) {
    const amount = money(sub.amount, sub.currency)
    const unit = pick(INTERVALS, sub.recurring_interval, null)

    if (!amount) return null
    if (!unit) return amount

    const count = Number.isInteger(sub.recurring_interval_count) ? sub.recurring_interval_count : 1
    return count > 1 ? `${amount} every ${count} ${unit}s` : `${amount}/${unit}`
}

// "29 Oct 2026" from an ISO timestamp, or null.
function day(value) {
    const date = typeof value === "string" ? new Date(value) : null
    return date && !Number.isNaN(date.getTime())
        ? date.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" })
        : null
}

// Table lookup that ignores 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 }] : []
}

// A non-empty string, or null.
function text(value) {
    return typeof value === "string" && value.trim() ? value.trim() : null
}

function flag(query, name) {
    return ["1", "true", "yes"].includes(String(query?.[name] ?? "").toLowerCase())
}

// "Jane Doe's Pro plan (€19.00/month)"
function describe(sub) {
    const who = text(sub.customer?.name) ?? text(sub.customer?.billing_name) ?? text(sub.customer?.email)
    const product = text(sub.product?.name) ?? "subscription"
    const cost = price(sub)

    return (who ? `${who}'s ${product}` : `A ${product}`) + (cost ? ` (${cost})` : "")
}

function dashboard(request, sub) {
    // ?sandbox=1 points the button at the sandbox dashboard.
    const host = flag(request.query, "sandbox") ? "https://sandbox.polar.sh" : "https://polar.sh"
    return link(`${host}/to/dashboard/sales/subscriptions/${encodeURIComponent(sub.id)}`, "View subscription")
}

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

    // Guard: only subscription.canceled, so other Polar events on this integration stay quiet.
    if (body.type !== "subscription.canceled" || !sub || typeof sub !== "object" || !sub.id) {
        console.log(`Ignoring Polar "${typeof body.type === "string" ? body.type : "unknown"}" event`)
        return null
    }

    // Immediate revocation: canceled and ended at once (subscription.revoked is sent right after).
    const immediate = sub.cancel_at_period_end !== true && (sub.status === "canceled" || Boolean(sub.ended_at))
    const until = day(sub.ends_at) ?? day(sub.current_period_end)
    const reason = pick(REASONS, sub.customer_cancellation_reason, null)
    let comment = text(sub.customer_cancellation_comment)
    if (comment && comment.length > 120) comment = `${comment.slice(0, 117)}…`

    return {
        title: "👋 Subscription canceled",
        message:
            `${describe(sub)} was canceled.` +
            (immediate ? " Access ended right away." : until ? ` Access until ${until}.` : "") +
            (reason ? ` Reason: ${reason}.` : "") +
            (comment ? ` “${comment}”` : ""),
        topic: "Polar",
        priority: 0, // Normal: worth knowing, and they usually keep access until the period ends
        buttons: dashboard(request, sub),
    }
}
```

## Polar subscription.canceled webhook payload (sample)

```json
{
  "data": {
    "id": "s1a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b",
    "amount": 1900,
    "status": "active",
    "ends_at": "2026-10-29T08:00:00.000000Z",
    "product": {
      "id": "p2a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b",
      "name": "Pro plan",
      "description": null,
      "is_archived": false,
      "is_recurring": true,
      "organization_id": "o1a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b",
      "recurring_interval": "month",
      "recurring_interval_count": 1
    },
    "currency": "eur",
    "customer": {
      "id": "c1a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b",
      "name": "Jane Doe",
      "type": "individual",
      "email": "jane@example.com",
      "billing_name": "Jane Doe",
      "email_verified": true,
      "organization_id": "o1a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b"
    },
    "discount": null,
    "ended_at": null,
    "metadata": [],
    "trial_end": null,
    "created_at": "2026-06-29T08:00:00.000000Z",
    "product_id": "p2a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b",
    "started_at": "2026-06-29T08:00:00.000000Z",
    "canceled_at": "2026-09-29T08:06:40.000000Z",
    "checkout_id": null,
    "customer_id": "c1a2b3c4-d5e6-4f70-8a9b-0c1d2e3f4a5b",
    "discount_id": null,
    "modified_at": "2026-09-29T08:06:40.000000Z",
    "past_due_at": null,
    "trial_start": null,
    "current_period_end": "2026-10-29T08:00:00.000000Z",
    "recurring_interval": "month",
    "cancel_at_period_end": true,
    "current_period_start": "2026-09-29T08:00:00.000000Z",
    "recurring_interval_count": 1,
    "customer_cancellation_reason": "too_expensive",
    "customer_cancellation_comment": null
  },
  "type": "subscription.canceled",
  "timestamp": "2026-09-29T08:06:40.000000Z"
}
```

## 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 Polar 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.
