# Chargebee refund issued notifications on your phone

> Get a low-priority push notification when a Chargebee payment is refunded, with the amount, customer and reason.

- Company: Chargebee (https://www.justpush.io/recipes/chargebee)
- Event: `payment_refunded` (payment_refunded)
- Tags: Payments & billing, Refunds
- Install: https://studio.justpush.io/recipes/chargebee/payment-refunded
- Web page: https://www.justpush.io/recipes/chargebee/payment-refunded

## 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 payment_refunded and save the webhook.
5. Under **Events to Send**, pick only `payment_refunded` (Chargebee selects All Events by default). Chargebee sends `refund_initiated` when a direct-debit refund starts; this recipe ignores that event.
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 customer 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 → payment_refunded
// Fires when a payment is fully or partially refunded to the customer.
// Docs: https://apidocs.chargebee.com/docs/api/events/webhook/payment_refunded
//
// Paste this into a JustPush Studio integration and add a Chargebee webhook for the
// "payment_refunded" event pointing at the integration's endpoint URL.
// Add ?site=your-site to the URL to get a button that opens the customer in Chargebee.

// Chargebee amounts are whole numbers in the currency's smallest unit (2900 = €29.00),
// except for zero-decimal currencies such as JPY, where 500 means ¥500. This is Chargebee's
// own list: https://www.chargebee.com/docs/billing/2.0/site-configuration/supported-currencies
const ZERO_DECIMAL = new Set(["clp", "isk", "jpy", "krw", "mga", "pyg", "vnd", "xaf", "xof", "xpf"])

// Chargebee's built-in credit note reasons (credit_note.reason_code). "other" says nothing, so it's left out.
const REASONS = {
    product_unsatisfactory: "product unsatisfactory",
    service_unsatisfactory: "service unsatisfactory",
    order_change: "order changed",
    order_cancellation: "order cancelled",
    subscription_change: "subscription changed",
    subscription_cancellation: "subscription cancelled",
    subscription_pause: "subscription paused",
    waiver: "waiver",
    fraudulent: "fraudulent",
    chargeback: "chargeback",
    write_off: "write-off",
}

function money(amount, currency) {
    // Don't invent a figure when the event doesn't carry one.
    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 }).format(value)
    } catch {
        return `${value} ${code.toUpperCase()}`
    }
}

// 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)
}

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 !== "payment_refunded" ||
        (event.object !== undefined && event.object !== "event") ||
        !event.content?.transaction ||
        typeof event.content.transaction !== "object"
    ) {
        console.log(`Ignoring Chargebee event "${text(event.event_type) ?? "unknown"}"`)
        return null
    }

    const { transaction, customer } = event.content
    const creditNote = event.content.credit_note && typeof event.content.credit_note === "object" ? event.content.credit_note : {}
    // The event's transaction is the refund itself, so its amount is what went back.
    const amount =
        money(transaction.amount, transaction.currency_code) ??
        money(creditNote.amount_refunded, creditNote.currency_code)
    const who = customerName(customer)
    // Your own reason code wins; otherwise Chargebee's built-in reason.
    const reason = text(creditNote.create_reason_code) ?? pick(REASONS, creditNote.reason_code, null)
    // Card and direct-debit refunds can take a few days at the gateway.
    const pending = transaction.status === "in_progress" ? ". Still processing at the gateway." : ""

    return {
        title: "↩️ Refund issued",
        message:
            (amount ? `${amount} refunded` : "A payment was refunded") +
            (who ? ` to ${who}` : "") +
            (reason ? ` — ${reason}` : "") +
            pending,
        topic: "Chargebee",
        priority: -1, // Low — you (or a teammate) most likely issued it yourself
        buttons: link(adminUrl(request, "customers", transaction.customer_id ?? customer?.id), "View customer"),
    }
}
```

## Chargebee payment_refunded webhook payload (sample)

```json
{
  "id": "ev_test_payment_refunded",
  "user": "admin@example.com",
  "object": "event",
  "source": "admin_console",
  "content": {
    "invoice": {
      "id": "1042",
      "total": 2900,
      "object": "invoice",
      "status": "paid",
      "amount_paid": 2900,
      "customer_id": "cus_test_16BjpLU3",
      "currency_code": "EUR"
    },
    "customer": {
      "id": "cus_test_16BjpLU3",
      "email": "jane@example.com",
      "object": "customer",
      "last_name": "Doe",
      "first_name": "Jane"
    },
    "credit_note": {
      "id": "CN-7",
      "type": "refundable",
      "total": 1500,
      "object": "credit_note",
      "status": "refunded",
      "customer_id": "cus_test_16BjpLU3",
      "reason_code": "service_unsatisfactory",
      "currency_code": "EUR",
      "amount_refunded": 1500,
      "amount_available": 0,
      "reference_invoice_id": "1042"
    },
    "transaction": {
      "id": "txn_test_16BjpLU5",
      "date": 1790584200,
      "type": "refund",
      "amount": 1500,
      "object": "transaction",
      "status": "success",
      "gateway": "stripe",
      "customer_id": "cus_test_16BjpLU3",
      "currency_code": "EUR",
      "payment_method": "card",
      "refunded_txn_id": "txn_test_16BjpLU3",
      "subscription_id": "sub_test_16BjpLU3",
      "masked_card_number": "************4242"
    },
    "subscription": {
      "id": "sub_test_16BjpLU3",
      "object": "subscription",
      "status": "active",
      "currency_code": "EUR"
    }
  },
  "event_type": "payment_refunded",
  "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.
