# Remind customers about failed payments

Source: https://kirora.io/docs/api/recipe-failed-payments

Remind a customer once per failed bill, stop when it is paid or closed, and read what was recovered.

This recipe reminds a customer when a payment fails, stops as soon as that bill is paid or
closed, and reports what was recovered. It works from events alone, whatever your billing
system: a connected Stripe account sends the same events for you (see
[E-commerce events](https://kirora.io/docs/api/ecommerce-events#billing-events)). You create a journey that runs
once per bill, track two failed bills for one customer, pay one, and read the report.

The dashboard's **Failed payment** template builds a fuller version of this journey, with up
to three reminders over a week.

Every `POST` here carries an `Idempotency-Key`, so running a step twice is safe.

## Before you start

- **An API key** with `journeys:write`, `journeys:activate`, `journeys:read`,
  `contacts:write`, `contacts:read` and `events:write`. See
  [Authentication](https://kirora.io/docs/api/reference/authentication).
- **What activating an email journey needs:** a `from` address on a verified sending domain
  with a DMARC record, and the workspace's postal address. The reminders themselves are
  service messages (`transactional: true`): about the payment only, with no offer in them,
  so they need no marketing consent.
- **cURL and jq**, and `KIRORA_API_URL` and `KIRORA_API_KEY` set as in the
  [Quickstart](https://kirora.io/docs/api/quickstart).

Replace `mail.juniperkitchen.com` with your verified domain, and
`https://juniperkitchen.com/billing` with your billing page, in step 1.

## 1. Create the journey

The journey starts on `Payment Failed` and runs once per `invoice_id`
(`once_per_value`), so two bills owed at once are two runs and a repeat failure of the
same bill starts nothing. Each exit must share that `invoice_id`, so paying one bill ends
only its run, and `includeEarlierEvents` also counts a payment recorded before the failure
arrived. `minHoursBetweenSends: 24` sends a customer at most one reminder a day, however
many bills failed. The button goes to the bill's `payment_url`, or your billing page when
the event has none.

```sh
curl "$KIRORA_API_URL/v1/journeys" \
  --fail-with-body --silent --show-error -o journey.json \
  -H "Authorization: Bearer $KIRORA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: recipe-failed-payments-create-001" \
  -d '{
    "name": "Failed payment",
    "trigger": {
      "type": "event",
      "name": "Payment Failed",
      "reentry": { "mode": "once_per_value", "property": "invoice_id" }
    },
    "exitConditions": [
      { "type": "event", "name": "Payment Succeeded", "matchTriggerProperty": "invoice_id", "includeEarlierEvents": true },
      { "type": "event", "name": "Invoice Closed", "matchTriggerProperty": "invoice_id", "includeEarlierEvents": true }
    ],
    "minHoursBetweenSends": 24,
    "steps": [
      { "id": "wait-1-hour", "type": "wait", "duration": { "value": 1, "unit": "hours" } },
      {
        "id": "first-reminder",
        "type": "send",
        "channel": "email",
        "transactional": true,
        "content": {
          "subject": "Your payment didn'\''t go through",
          "from": "Juniper Kitchen <billing@mail.juniperkitchen.com>",
          "templateSnapshot": {
            "schemaVersion": 1,
            "blocks": [
              { "id": "title", "type": "heading", "text": "Your payment didn'\''t go through" },
              { "id": "body", "type": "text", "text": "We couldn'\''t take your payment of {{ event.properties.total }} {{ event.properties.currency }}. Pay it with the button below." },
              { "id": "pay", "type": "button", "text": "Pay now", "href": "{{ event.properties.payment_url | default: \"https://juniperkitchen.com/billing\" }}" },
              { "id": "footer", "type": "footer", "text": "{{ org.name }}\n{{ org.address }}", "unsubscribeLink": false, "locked": true }
            ],
            "theme": {}
          }
        },
        "nextStep": null
      }
    ]
  }'
JOURNEY_ID=$(jq -er '.data.id' journey.json)
```

Then activate it:

```sh
curl "$KIRORA_API_URL/v1/journeys/$JOURNEY_ID/activate" \
  --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $KIRORA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: recipe-failed-payments-activate-001" \
  -d '{}'
```

## 2. Create the customer

`delivered@example.com` is a [test address](https://kirora.io/docs/api/transactional#test-addresses): the email
goes through every check and reaches no inbox.

```sh
curl "$KIRORA_API_URL/v1/contacts/identify" \
  --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $KIRORA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: recipe-failed-payments-contact-001" \
  -d '{ "externalId": "customer-4821", "email": "delivered@example.com" }'
```

## 3. Track two failed bills

Send each failure with your own id for the bill in `invoice_id`, the amount still owed in
`total`, and one idempotency key per attempt:

```sh
for INVOICE in inv-1 inv-2; do
  curl "$KIRORA_API_URL/v1/events/track" \
    --fail-with-body --silent --show-error \
    -H "Authorization: Bearer $KIRORA_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $INVOICE-payment-failed-1" \
    -d '{
      "externalId": "customer-4821",
      "name": "Payment Failed",
      "properties": { "invoice_id": "'"$INVOICE"'", "total": 29.00, "currency": "USD", "attempt_count": 1 }
    }'
done
```

Each failure starts its run in the background, after the request. List the customer's
journeys: there are two runs of this journey, both `active`. If they aren't listed yet,
read again shortly.

```sh
curl "$KIRORA_API_URL/v1/contacts/customer-4821/journeys?idType=externalId" \
  --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $KIRORA_API_KEY"
```

## 4. Pay one bill

```sh
curl "$KIRORA_API_URL/v1/events/track" \
  --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $KIRORA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: inv-1-payment-succeeded" \
  -d '{
    "externalId": "customer-4821",
    "name": "Payment Succeeded",
    "properties": { "invoice_id": "inv-1", "total": 29.00, "currency": "USD" }
  }'
```

List the journeys again: the `inv-1` run has `exited` and the `inv-2` run is still
`active`. If the bill was settled another way (paid outside your gateway, voided or written
off), send `Invoice Closed` with its `invoice_id` and a `reason` instead. A bill closed this
way ends its reminders but isn't counted in `runsPaidWithin14Days` or `amountRecovered`;
send `Payment Succeeded` when the customer paid and you want it counted.

## 5. Read what was recovered

```sh
curl "$KIRORA_API_URL/v1/journeys/$JOURNEY_ID/metrics" \
  --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $KIRORA_API_KEY" | jq '.data.recovery'
```

`recovery` holds, per currency, `runsStarted` (2), `runsPaidWithin14Days` (1) and
`amountRecovered` (29). It is what was recovered **while** the journey ran, not
necessarily **because** of it: a gateway's own retries recover some payments anyway.

## If nothing happens

- **No run:** the event has no `invoice_id`, the bill was already paid or closed, or the
  journey was not `active` when the failure was tracked.
- **A run that does not end:** the paid or closed event carries a different `invoice_id`,
  or none.
- **A reminder sent later than expected:** another bill's reminder went to the same
  customer within the last 24 hours; it waits rather than being dropped.

## Next steps

- [E-commerce events](https://kirora.io/docs/api/ecommerce-events#billing-events): every billing event and its
  properties
- [Objects and rules](https://kirora.io/docs/api/models#journey-definitions): re-entry, exits and every step type
- [Campaigns and journeys](https://kirora.io/docs/api/campaigns-and-journeys#one-run-per-bill): one run per bill