# API integration guide

> Markdown version of https://www.paymentretryalert.com/docs/integration-guide/

An integration has four steps: store declined payments, receive retry alerts, match alerts to stored declines, and retry payments while reporting the outcomes. Build and test your integration in a test organisation before going live.

For every field and endpoint, see the [API reference](https://www.paymentretryalert.com/docs/api-reference.md). For how alerts work, see [how it works](https://www.paymentretryalert.com/docs/how-it-works.md).

## Before you start

You need a test organisation and an API key for it. Test organisations never send anything to Mastercard.

**In the dashboard** (https://app.paymentretryalert.com/, role: Anyone signed in. You become its Owner):

1. Open the organisation menu in the top bar and select **Create organisation**.
2. Enter an **Organisation name** and choose **Test** under **Mode**.
3. Select **Create organisation**. Test organisation names start with [TEST], and their enrolments never go to Mastercard.

Organisations are created in the dashboard. An API key always belongs to one organisation.

Create a key with `enrolments:write`, `alerts:write`, `events:read`, `webhook_endpoints:write` and `simulations:write`. Keep it on your server, for example in an environment variable called `PRA_API_KEY`.

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Developer):

1. Select **Developers** in the sidebar, then **Create API key**.
2. Enter a **Name**, such as the server that will use the key.
3. Under **Access**, choose **Full access**, **Read only** or **Custom**. Custom lists each scope by resource; a write scope, such as **Enrol and unenrol MIDs**, includes reading the same resource.
4. For the integration guide, tick **Enrol and unenrol MIDs**, **Report retry outcomes**, **Read events**, **Manage webhook endpoints and retry deliveries** and **Simulate enrolment statuses and alerts**.
5. Select **Create API key**. Copy the key into your secret store, then select **I copied the key**. The key is shown only once.

API keys are created in the dashboard. Call GET /me with a new key to check its organisation and scopes.

Every request sends the key and the API version. Check that the key works and belongs to your test organisation:

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/me" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05'
```

The response shows `organisation.mode` as `TEST`.

## 1. Store your declines

An alert tells you to retry a payment that declined earlier, so you need a record of that payment. Save each Mastercard payment on an enrolled MID that declines with response code `51` (insufficient funds) or `61` (exceeds withdrawal limit):

| Store | Compare with alert field |
| --- | --- |
| The MID the payment used | `enrolment_mid` |
| The network transaction ID of the declined authorisation (the Mastercard Banknet reference) | `network_transaction_id` |
| Amount and currency | `transaction_amount_in_cents`, `transaction_currency` |
| Card BIN and last four digits | `card_bin`, `card_last_four` |
| Decline time | `transaction_time` |
| Your own payment and customer IDs, and whether the payment has since been paid | Used to retry the payment |

Check that your payment provider gives you these details for each decline. If it does not include the network transaction ID or the card BIN, ask whether it can: you can match without them, but less reliably. Never store full card numbers.

Keep each record until the payment is paid or 30 days have passed. Mastercard watches a declined card for up to 30 days by default.

## 2. Enrol your MIDs

Alerts are sent only for enrolled MIDs. In your test organisation, create a test enrolment:

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Developer):

1. In your test organisation, select **Developers** in the sidebar.
2. In the **Simulator** section, select **Create test enrolment**.
3. Enter a test **MID** and select **Create test enrolment**. It starts as PENDING and never goes to Mastercard.

**With the API:**

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/enrolments" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: test-enrolment-001' \
  --data '{"mastercard_pop_mid":"123456789012345"}'
```

A test enrolment starts as `PENDING`. Set it to `ENABLED`, as Mastercard would once enrolment completes. Replace `enrl_REPLACE_WITH_ENROLMENT_ID` with the `id` from the response:

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Developer):

1. In **Developers**, find the test enrolment in the **Simulator** table and select **Change status**.
2. Choose `ENABLED` as the **New status**. For ACTION_REQUIRED, also enter a **Customer-facing message**.
3. Select **Change status**. An enrolment.updated event goes to your endpoints.

**With the API:**

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/simulations/enrolments/enrl_REPLACE_WITH_ENROLMENT_ID/status" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: test-enable-001' \
  --data '{"status":"ENABLED"}'
```

You enrol your live MIDs when you [go live](#7-go-live).

## 3. Receive alerts

Each alert arrives as an `alert.created` event. Receive events in one of two ways:

- **Webhooks:** we send each event to your HTTPS endpoint when it happens.
- **Polling:** you ask `GET /events` for new events, which it returns once they are at least 30 seconds old.

An alert is most useful soon after it arrives, so webhooks are the faster option. You can also use both, and poll to catch anything your endpoint missed.

An `alert.created` event looks like this:

```json
{
  "id": "evt_example_alert_created",
  "object": "event",
  "type": "alert.created",
  "api_version": "2026-10-05",
  "organisation_mode": "TEST",
  "created_at": "2026-10-20T10:00:00.000Z",
  "data": {
    "object": {
      "id": "alrt_example",
      "object": "alert",
      "organisation_id": "org_example",
      "enrolment_id": "enrl_example",
      "enrolment_mid": "123456789012345",
      "card_scheme": "MASTERCARD",
      "notification_type": "RETRY_NOW",
      "transaction_time": "2026-10-19T08:30:00.000Z",
      "transaction_amount_in_cents": 2150,
      "transaction_currency": "USD",
      "network_transaction_id": "EXAMPLE123",
      "card_bin": "512345",
      "card_last_four": "1234",
      "retry_outcome": null,
      "created_at": "2026-10-20T10:00:00.000Z"
    }
  }
}
```

The same event can reach you more than once, through a webhook retry or through both webhooks and polling. Use the event's `id` to act on each event only once.

### Option A: webhooks

Register the public HTTPS URL that will receive events. The URL must accept `POST` without redirecting.

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Developer):

1. Select **Webhooks** in the sidebar, then **Add endpoint**.
2. Enter the public **URL** of your receiver. It must start with https:// and cannot be changed later.
3. Under **Events**, choose `alert.created` and `alert.updated`. Add `enrolment.updated` to hear when an enrolment changes status.
4. Select **Add endpoint** and store the **Signing secret**. You can show it again on the endpoint page with **Reveal**.

**With the API:**

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/webhook-endpoints" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: create-endpoint-001' \
  --data '{"url":"https://payments.example.com/webhooks/paymentretryalert","event_types":["alert.created","alert.updated"]}'
```

The response includes the endpoint's signing secret, which starts with `whsec_`. Store it with your API key. The API returns it only when you create the endpoint; the dashboard can show it again.

For each request your endpoint receives:

1. Check the signature, as shown below. Reject the request with `400` if it does not match.
2. Respond with any `2xx` status within 15 seconds. If matching and retrying take longer, respond first and do them afterwards.

A response other than `2xx`, a redirect or a timeout counts as a failed attempt. We retry after about 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, up to 6 attempts in total.

To check a signature:

1. Read the raw request body, before parsing it as JSON, and the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers.
2. Reject the request if `webhook-timestamp` is more than 5 minutes from your server's clock.
3. Remove `whsec_` from the signing secret and base64-decode the rest. That is the key.
4. Compute HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>` with the key, and base64-encode it.
5. Accept the request if any `v1,` value in `webhook-signature` matches, using a constant-time comparison.

Signatures follow [Standard Webhooks](https://www.standardwebhooks.com/), so its libraries work too.

**Node.js:**

```javascript
import { createHmac, timingSafeEqual } from 'node:crypto';

// secret: the endpoint's whsec_ signing secret. headers: lower-case header
// names, as in Node's request.headers. body: the raw request body (Buffer).
export function verifyWebhook(secret, headers, body, toleranceSeconds = 300) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (!id || !/^\d+$/.test(timestamp ?? '') || !signatures) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;

  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  const expected = createHmac('sha256', key).update(`${id}.${timestamp}.`).update(body).digest();

  return signatures.split(' ').some((signature) => {
    if (!signature.startsWith('v1,')) return false;
    const supplied = Buffer.from(signature.slice(3), 'base64');
    return supplied.length === expected.length && timingSafeEqual(supplied, expected);
  });
}
```

**Python:**

```python
import base64
import hashlib
import hmac
import time


def verify_webhook(secret: str, headers, body: bytes, tolerance: int = 300) -> bool:
    """secret: the endpoint's whsec_ signing secret. headers: a case-insensitive
    mapping, such as Flask's request.headers. body: the raw request body."""
    msg_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    signatures = headers.get("webhook-signature", "")
    if not msg_id or not (timestamp.isascii() and timestamp.isdigit()):
        return False
    if abs(time.time() - int(timestamp)) > tolerance:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    return any(
        signature.startswith("v1,") and hmac.compare_digest(signature[3:], expected)
        for signature in signatures.split()
    )
```

**PHP:**

```php
<?php

// $secret: the endpoint's whsec_ signing secret. $headers: getallheaders().
// $body: the raw request body, file_get_contents('php://input').
function verify_webhook(string $secret, array $headers, string $body, int $tolerance = 300): bool
{
    $headers = array_change_key_case($headers, CASE_LOWER);
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $signatures = $headers['webhook-signature'] ?? '';
    if ($id === '' || !ctype_digit($timestamp) || abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }

    $key = base64_decode(substr($secret, strlen('whsec_')));
    $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key, true));

    foreach (explode(' ', $signatures) as $signature) {
        if (str_starts_with($signature, 'v1,') && hash_equals($expected, substr($signature, 3))) {
            return true;
        }
    }

    return false;
}
```

**Go:**

```go
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// VerifyWebhook checks a PaymentRetryAlert signature. secret is the endpoint's
// whsec_ signing secret; body is the raw request body.
func VerifyWebhook(secret string, header http.Header, body []byte) bool {
	id := header.Get("webhook-id")
	timestamp := header.Get("webhook-timestamp")
	seconds, err := strconv.ParseUint(timestamp, 10, 63)
	if id == "" || err != nil {
		return false
	}
	if age := time.Since(time.Unix(int64(seconds), 0)); age > 5*time.Minute || age < -5*time.Minute {
		return false
	}

	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + timestamp + "."))
	mac.Write(body)
	expected := mac.Sum(nil)

	for _, signature := range strings.Fields(header.Get("webhook-signature")) {
		value, ok := strings.CutPrefix(signature, "v1,")
		if !ok {
			continue
		}
		if supplied, err := base64.StdEncoding.DecodeString(value); err == nil && hmac.Equal(supplied, expected) {
			return true
		}
	}

	return false
}
```

### Option B: poll the API

To start, ask for the newest event that is at least 30 seconds old. Replace `TIMESTAMP` with the current UTC time minus 30 seconds, such as `2026-10-20T10:00:00Z`:

```bash
curl --fail-with-body --get "https://api.paymentretryalert.com/v1/events" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  --data-urlencode 'limit=1' \
  --data-urlencode 'created_at_lte=TIMESTAMP'
```

Save the `id` of the returned event as your cursor. If `items` is empty, try again later. Then, for example once a minute, ask for the alerts created after the cursor:

```bash
curl --fail-with-body --get "https://api.paymentretryalert.com/v1/events" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  --data-urlencode 'type=alert.created' \
  --data-urlencode 'starting_after=evt_REPLACE_WITH_CURSOR' \
  --data-urlencode 'limit=100'
```

Events come back oldest first. Handle them in order, then save the last event's `id` as the new cursor. If a page has 100 events, ask again straight away; if it is empty, keep the cursor and wait. Do not send `offset` or `sort` with `starting_after`.

## 4. Match the alert to a decline

Find the stored decline that the alert refers to, using the alert's `data.object`:

1. Look only at stored declines for the alert's `enrolment_mid` that have not been paid.
2. If `network_transaction_id` is not empty and matches one stored decline, that is the payment.
3. Otherwise, look for a decline with the same card BIN, last four digits, amount and currency. If exactly one matches, that is the payment.
4. If nothing matches, or several declines do, do not retry automatically. Review the alert, or report it as `NOT_ATTEMPTED`.

For example, in JavaScript:

```javascript
// alert: the event's data.object. declines: your stored declines.
function findDecline(alert, declines) {
  const unpaid = declines.filter((d) => d.mid === alert.enrolment_mid && !d.paid);

  if (alert.network_transaction_id) {
    const byId = unpaid.filter((d) => d.networkTransactionId === alert.network_transaction_id);
    if (byId.length === 1) return byId[0];
  }

  if (!alert.card_last_four || alert.transaction_amount_in_cents === null) return null;
  const byCard = unpaid.filter(
    (d) =>
      d.cardBin === alert.card_bin &&
      d.cardLastFour === alert.card_last_four &&
      d.amountMinorUnits === alert.transaction_amount_in_cents &&
      d.currency === alert.transaction_currency
  );
  return byCard.length === 1 ? byCard[0] : null;
}
```

When you compare the fields:

- `transaction_amount_in_cents` is in the currency's minor units: `2150` is USD 21.50 but JPY 2,150. It is `null` when the amount is unknown; never treat that as zero.
- Fields that are unavailable are empty strings. Keep identifiers as strings, so leading zeros survive.
- Mastercard does not start a new watch when the same card declines again for the same MID and amount within the watch period. If you retried on your own schedule and stored several declines for one payment, treat them as one payment.

## 5. Retry and report the outcome

Retry the matched payment through your payment provider, with your existing credentials. Charge it only once: skip the retry if the payment has been paid since, or if you have already retried it for this alert. Your provider's idempotency key helps if a retry request times out.

Then report what happened. Replace `alrt_REPLACE_WITH_ALERT_ID` with the alert's `id`:

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner, Developer or Standard user):

1. Select **Alerts** in the sidebar and open the alert.
2. Under **Retry outcome**, select **Retry succeeded**, **Retry failed** or **Did not retry**.
3. The outcome saves straight away. You can change it later.

**With the API:**

```bash
curl --fail-with-body -X PATCH "https://api.paymentretryalert.com/v1/alerts/alrt_REPLACE_WITH_ALERT_ID" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  -H 'Content-Type: application/json' \
  --data '{"retry_outcome":"SUCCEEDED"}'
```

| Outcome | When |
| --- | --- |
| `SUCCEEDED` | The retry succeeded. |
| `FAILED` | You retried and it failed. |
| `NOT_ATTEMPTED` | You did not retry, for example because no decline matched. |

An alert with no outcome after 5 days becomes `NOT_ATTEMPTED`. You can change an outcome later; each change sends an `alert.updated` event.

## 6. Test with a simulated alert

Store a declined payment in your provider's test environment, then simulate an alert with the same details. The enrolment must be `ENABLED` or `IN_PROGRESS`:

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Developer):

1. In **Developers**, find an enrolment that is IN_PROGRESS or ENABLED in the **Simulator** table and select **Simulate alert**.
2. Optionally set the **Currency**, **Amount** and **Payment declined at** to match a declined test payment. The card BIN, last four digits and network transaction ID are generated; to set them, use the API.
3. Select **Simulate alert**. The alert appears under **Alerts**, and an alert.created event goes to your endpoints.

**With the API:**

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/simulations/enrolments/enrl_REPLACE_WITH_ENROLMENT_ID/alerts" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: test-alert-001' \
  --data '{"transaction_amount_in_cents":2150,"transaction_currency":"USD","card_bin":"512345","card_last_four":"1234","network_transaction_id":"test-payment-001"}'
```

Fields you leave out get test values. A `transaction_time` you send must be within the last 30 days.

Check that your integration received the event, matched the decline, retried it and reported the outcome. With webhooks, the endpoint's deliveries show each attempt and your response status:

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Developer):

1. Select **Webhooks** in the sidebar and open your endpoint.
2. In **Deliveries**, open a delivery to see each attempt with its response status and the request body.
3. Select **Resend** to send a delivery again. While a retry is planned, **Retry now** sends it straight away.

**With the API:**

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/webhook-endpoints/whep_REPLACE_WITH_ENDPOINT_ID/deliveries" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05'
```

To check duplicate handling, resend a delivery with `POST /webhook-deliveries/{id}/retry` and confirm that your integration does not retry the payment again.

## 7. Go live

Repeat the setup in a live organisation:

1. Create a live organisation and start its subscription. Live MIDs are enabled only once the subscription is active.
2. Create a live API key with only the scopes your production code uses. Simulations work only in test organisations.
3. If you use webhooks, register a live endpoint. It has its own signing secret.
4. Enrol your live MIDs. Each moves to `ENABLED` when Mastercard completes enrolment.

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner or Billing manager):

1. In your live organisation, select **Overview** in the sidebar.
2. Under **Get started**, select **Subscribe** and complete checkout.
3. You can manage the subscription and invoices later under **Billing**.

Subscriptions are managed in the dashboard.

**In the dashboard** (https://app.paymentretryalert.com/, role: Owner):

1. Select **Enrolments** in the sidebar, then **Enrol MID**.
2. Enter the **MID** your acquirer gave you.
3. Select **Enrol MID**. The status shows on the page while Mastercard processes the enrolment.
4. Live MIDs are enabled only once the organisation has an active subscription.

**With the API:**

```bash
curl --fail-with-body "https://api.paymentretryalert.com/v1/enrolments" \
  -H "Authorization: Bearer $PRA_API_KEY" \
  -H 'PaymentRetryAlert-Version: 2026-10-05' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: enrol-live-mid-001' \
  --data '{"mastercard_pop_mid":"YOUR_LIVE_MID"}'
```

Check that `GET /me` with the live key shows `LIVE`, and that test events never reach your live payment credentials.

## Troubleshooting

| Symptom | Check |
| --- | --- |
| `401` or `403` | The API key, its scopes and the organisation's mode. Simulations need a test organisation. |
| `429` | Wait for the number of seconds in `Retry-After`. All keys of an organisation share its limits. |
| No webhook arrives | The endpoint was active before the event happened, and it subscribes to `alert.created`. New endpoints do not receive earlier events; poll `GET /events` for them. |
| Signature check fails | The secret belongs to this endpoint, you check the raw body before parsing it, any proxy passes the body and headers unchanged, and your server clock is correct. |
| Deliveries time out | Your endpoint responds within 15 seconds and is reachable over public HTTPS. |
| Endpoint disabled | Repeated failures disable an endpoint. Fix the cause, select **Enable** on the endpoint page, and resend the deliveries you need. Poll `GET /events` for events from while it was disabled. |
| An alert matches no decline | Compare the MID, network transaction ID, card details, amount and currency with the decline you stored. |

When contacting support, include the organisation ID, event ID, delivery ID and the time of the attempt. Never send API keys, signing secrets or full card numbers.
