> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/benefit-provider.md).

# Benefit provider

Keep the benefits of a pass in step with a read-only external system, with runtime.benefit.benefitProvider, its GetBenefits handler and its validation rules.

A benefit provider script returns, for one pass, the complete set of benefits an external system holds for the holder: vouchers, offers, a welcome gift. The Wallet Crew compares that set with the benefits the pass already has, adds the new ones, updates the changed ones and removes those that are no longer returned. It is the tool for a system that can only be read. This page is the reference for `runtime.benefit.benefitProvider`.

Three tools grant benefits, and the choice depends on who starts the exchange:

* The system **can call The Wallet Crew**: use the benefit API.
* **The Wallet Crew issues** the benefit from a benefit template, and only its code comes from a script: use the [benefit code generator](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/benefit-code-generator.md).
* The system **can only be read**: use this endpoint.

<details>

<summary><strong>Real-world examples</strong></summary>

* A retailer lists the vouchers a customer holds in its promotion platform, and the pass shows them as benefits.
* A partner program returns the offers a member is entitled to, with their activation and expiry dates.
* A brand lets its CRM own the redemption: it reports how many times each benefit was used, and the pass shows the remaining balance.

</details>

## Registration

The key is `runtime.benefit.benefitProvider`. Registering it is enough: no configuration file refers to it, and from then on it applies to every pass of the tenant that is not itself a benefit.

```js
export default function (context) {
  context.register('runtime.benefit.benefitProvider', {
    GetBenefits: async (passId, passType, identifiers) => undefined
  });
}
```

## When it runs

The sync runs when a pass is created and on every update that recomputes the pass metadata. It does not run for the passes that carry a benefit id identifier (the passes that carry a benefit), so it never runs recursively.

A distributed lock per pass prevents two syncs of the same pass at once during a burst of updates. A sync waits up to one minute for the lock; when it is not obtained, the sync is skipped and a warning is logged.

Because the script runs on every metadata recompute, a call to the external system uses the `Cache` option of [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md).

## Handlers

| Method        | Parameters                          | Returns                           | Required |
| ------------- | ----------------------------------- | --------------------------------- | -------- |
| `GetBenefits` | `passId`, `passType`, `identifiers` | a promise of an array of benefits | Required |

`GetBenefits` must be an `async` function: the platform reads its result as a promise, so a plain function that returns an array fails, and the failure is handled like a thrown error (see below). It is required: a missing method would skip every pass.

* `passId` is the id of the pass and `passType` its pass type.
* `identifiers` is an object of the pass identifiers, keyed without the `id.` prefix: a pass carrying `crm.customerId` is read as `identifiers['crm.customerId']`.

## Return value

The result is the **complete set** of benefits of the pass, as an array of objects with camelCase keys.

| Returned              | Effect                                                                                      |
| --------------------- | ------------------------------------------------------------------------------------------- |
| An array of benefits  | The pass gets exactly these benefits. A benefit supplied earlier and now absent is removed. |
| `[]`                  | Every benefit supplied by the script is removed.                                            |
| `undefined` or `null` | A warning is logged and nothing changes.                                                    |

A benefit that comes back after it was removed is revived, not duplicated. The benefits are stored with `origin.generator` set to `script`.

### The benefit object

| Member                                               | Type          | Meaning                                                                                                                                                |
| ---------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `origin.externalId`                                  | string        | Required. A stable identifier, unique across the tenant. It is the identity used to compare the returned benefits with the existing ones.              |
| `origin.processId`                                   | string        | Optional. The benefit template id, when the benefit relates to a template.                                                                             |
| `type`                                               | string        | `OneTime` (default), `MultiUse` or `Unlimited`.                                                                                                        |
| `category`                                           | string        | A category. `Other` by default.                                                                                                                        |
| `priority`, `tags`                                   | number, array | Optional ordering and tags.                                                                                                                            |
| `content.title`, `content.description`               | object        | Each is `{ default, localizations }`.                                                                                                                  |
| `appearance.images`                                  | array         | Each `{ slot, url }`: `slot` is `Main` or `Thumbnail`, `url` is `{ default, localizations }` with absolute `http` or `https` URLs. One image per slot. |
| `links`                                              | object        | Keyed by link type (`CallToAction`, `Website`, ...), each `{ title, link }`.                                                                           |
| `data.content`                                       | string        | Free-form text.                                                                                                                                        |
| `behavior.target`                                    | number        | The allowance of a `MultiUse` benefit. `1` by default.                                                                                                 |
| `behavior.mode`                                      | array         | Where the benefit appears. `ShowOnBenefitListPage` only by default; `[]` shows the benefit nowhere.                                                    |
| `code.value`, `code.format`                          | string        | The code and its format. `Code128` by default.                                                                                                         |
| `activationDate`, `deactivationDate`, `deletionDate` | string        | ISO 8601 strings. A JavaScript `Date` object is refused.                                                                                               |
| `passType`                                           | string        | Creates a standalone pass for the benefit.                                                                                                             |
| `usedQuantity`                                       | number        | When set, the external system owns the redemption: the balance is the allowance minus `usedQuantity`, and the value must only grow.                    |

The platform owns the benefit id, the balance movements and `origin.generator`: a script does not set them.

## Errors and edge cases

* **`GetBenefits` throws or its promise rejects**: the error is swallowed and the pass keeps its benefits as they are.
* **`GetBenefits` returns `undefined` or `null`**: a warning is logged and nothing changes. To remove every benefit, return `[]`.
* **A benefit has an unknown category, code format, mode, link type or image slot**: the value is replaced by its default, or ignored, and logged.
* **A benefit has an unknown `type`, or an unreadable date** (a JavaScript `Date` object, or a day-first or month-first string): the **whole result is refused**.
* **The lock is not obtained**: the sync is skipped with a warning.
* **No script registers the key**: nothing happens.
* **Several files register the key**: the last registered wins, and the load order of files is not defined.
* **The pass carries a benefit id identifier**: the provider does not run for it.

Each sync logs one line with the number of benefits supplied, inserted, updated, retired, uses recorded, and benefits without a free slot.

## Example

The script reads the vouchers of a customer in a partner API. A failure of the API returns `undefined`, so that the pass keeps its benefits instead of losing them. Dates are ISO strings, and the `externalId` is the voucher number.

```js
import { getSecret } from 'twc/secrets';

const API_URL = 'https://vouchers.example.com/api/customers';

async function getBenefits(passId, passType, identifiers) {
  const customerId = identifiers['crm.customerId'];
  if (!customerId) {
    return undefined;
  }

  const apiKey = await getSecret('VOUCHER-API-KEY');
  if (!apiKey) {
    console.error('Secret VOUCHER-API-KEY is not set: benefits are not synchronized');
    return undefined;
  }

  const response = await fetch(`${API_URL}/${encodeURIComponent(customerId)}/vouchers`, {
    Headers: { 'X-Api-Key': apiKey },
    ThrowOnError: false,
    Cache: { CacheKey: `vouchers|${customerId}`, DurationInMs: 5 * 60 * 1000 }
  });

  if (response.StatusCode !== 200 || !response.ResponseText) {
    console.warn(`Voucher lookup answered ${response.StatusCode}: the benefits are left as they are`);
    return undefined;
  }

  const vouchers = JSON.parse(response.ResponseText).items ?? [];
  return vouchers.map((voucher) => ({
    origin: { externalId: `voucher-${voucher.number}` },
    type: 'OneTime',
    content: { title: { default: voucher.title } },
    code: { value: voucher.number },
    activationDate: voucher.validFrom,
    deactivationDate: voucher.validUntil
  }));
}

export default function (context) {
  context.register('runtime.benefit.benefitProvider', {
    GetBenefits: getBenefits
  });
}
```

An empty `items` array returns `[]`, which removes the benefits the script supplied earlier: that is the intended effect when the customer holds no voucher any more.

## Checking the result

`GET /api/{tenantId}/passes/{passId}/benefits` lists the benefits of a test pass. The platform's monitoring records one line per sync, which tells how many benefits were inserted, updated or retired, and a warning when a result was ignored.

## Common pitfalls

* The `externalId` changes from one call to the next, so benefits are removed and created again.
* A call to the external system without a `Cache`, repeated on every metadata recompute.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/benefit-provider.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
