> 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/pass-data-provider.md).

# Pass data provider

Fill a pass with data read from an external system each time it is built, and describe that data to the admin console, with passDataProvider.

A pass data provider script reads, from a system the tenant's brand owns (a CRM, an ERP, a ticketing platform, a recommendation engine), the values a pass displays: a points balance, a membership tier, a home store, the next event. The Wallet Crew runs it every time it builds the data of a pass, so the pass always reflects the external system without the brand having to push anything. This page is the reference for the endpoint `runtime.scriptable.passDataProvider.{scriptId}`; it is the place to come back to when a value does not appear on a pass, when a pass template refuses a script, or when a template variable has to be renamed.

A pass data provider is the right tool when the data lives elsewhere and must be read at display time. It is not the right tool to store a value once (write it into the pass's additional data through the pass API, a push update or an import instead), nor to react to an event such as an installation (see [Pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md)). It replaces the obsolete `runtime.scriptable.customerProvider.{scriptId}` endpoint; [Obsolete customerProvider script key](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/customer-provider-obsolete.md) explains the move. A pass type is shown as a pass template in the admin console; this page says pass type, as the configuration files do.

<details>

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

* A loyalty pass displays the customer's points and tier, read from the CRM with the customer id the pass carries.
* A membership pass shows a "VIP" label computed from the customer's yearly spend, and the pass template switches its colors on that label.
* An event ticket shows the seat and gate read from the ticketing platform's export API.
* A pass attaches the holder to a home store, so that the store data (address, opening hours) is resolved by The Wallet Crew from the store id the script returns.

</details>

## Registration

The script registers the key `runtime.scriptable.passDataProvider.{scriptId}`, where `{scriptId}` is a name chosen by the brand, for example `crm`. The same `scriptId` is then listed in the `dataProviders` of every pass type whose passes need the data, in `server/passes/<passType>.yml`:

```yaml
dataProviders:
  - provider: script
    scriptId: crm
```

An entry runs a tenant script when `provider` is `script`; other values of `provider` name the data providers published by The Wallet Crew and its connectors, and the pass template editor of the admin console offers them in a list. The entries of one pass type can mix connector providers and scripts.

The minimal skeleton is:

```js
export default function (context) {
  context.register('runtime.scriptable.passDataProvider.crm', {
    Fill: async (entity) => false
  });
}
```

{% hint style="warning" %}
The `scriptId` is matched exactly, and saving does not check that a script registers it: an entry with no matching registration counts as having found data (see [Handlers](https://docs.thewalletcrew.io/developers-guides/scripting/handlers.md#comparison-of-the-endpoints)). Comparing the key in the script with the `scriptId` in the YAML is the first check.
{% endhint %}

## When it runs

The Wallet Crew builds the data of a pass whenever it needs it: when the pass is created, when it generates the pass for a wallet (the Apple Wallet file a device downloads or refreshes, the Google Wallet object it writes), when an update asks for the pass metadata to be recomputed, when a preview is drawn and when the pass data is inspected. Each of these runs the pass type's `dataProviders`, and therefore the script, inside the request or job that triggered it. A script is not cached between two of these builds; caching an external answer is the job of the `Cache` option of [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md).

### The dataProviders rounds

The entries of `dataProviders` run in rounds, so that an entry can use what another one found.

1. In the first round, every entry runs at the same time, each on its own copy of the pass identifiers.
2. An entry that returns `true` has found its data and does not run again. An entry that returns `false` has found nothing yet.
3. If at least one entry found data in a round, a new round starts: every entry that has found nothing yet runs again, this time with the identifiers **and** everything the earlier rounds wrote.
4. The rounds stop as soon as a round finds nothing new, or as soon as an entry fails.

A script that needs a value written by another provider (for example a CRM id that a connector provider looks up from an email address) therefore returns `false` when that value is not there yet, and gets a second chance in the next round. The consequence is that `Fill` can be called more than once for the same build, which is one more reason to cache external calls.

When two entries write the same key, the value of the later round wins, and within one round the value of the entry listed later in `dataProviders`.

## Handlers

| Method     | Parameters | Returns                                 | Required |
| ---------- | ---------- | --------------------------------------- | -------- |
| `Fill`     | `entity`   | `boolean`, or a promise of it           | Required |
| `Describe` | none       | a description object, **synchronously** | Optional |

### Fill

`entity` is the flat dictionary the script reads from and writes to. For a pass build it starts with the pass identifiers, each under `id.<key>`: a pass carrying the identifier `crm.customerId` is read as `entity['id.crm.customerId']`. From the second round on, it also holds the keys written by the other entries in earlier rounds. It does not hold the pass's additional data. In the account API, the entity is the account being enrolled, with the submitted fields and whatever earlier providers found.

The script writes each value as a key of the entity (`entity['loyaltyPoints'] = 1200`; the bracket form works for every key). Assigning `null` removes a key, and a key whose value is `NaN` or `Infinity` is dropped with a warning. A provider cannot remove a key that another provider wrote: only what it writes or changes is collected from its copy. Reading conventions (identifiers, `debug.*` keys, dates and numbers) are described in [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md).

### Describe

`Describe` tells the admin console what the script reads and writes, so that the pass template editor can list the script's variables and identifiers before any pass has data. It is called synchronously: it must return the object directly, without `async`, without `await` and without calling `fetch`. A `Describe` that throws is logged as a warning and the script is then treated as describing nothing. It also runs during each pass build, to read the namespace and the roles.

The returned object uses camelCase keys:

| Key           | Type   | Meaning                                                                                         |
| ------------- | ------ | ----------------------------------------------------------------------------------------------- |
| `namespace`   | string | The namespace the script's keys are also published under. The `scriptId` when omitted or blank. |
| `identifiers` | array  | The pass identifiers the script reads, each `{ key, optional?, requiresSignature? }`.           |
| `fields`      | array  | The template variables the script writes, each `{ path, type?, description?, role? }`.          |

Each identifier has a `key`, written as the pass carries it, without the `id.` prefix (`crm.customerId`). `optional` (default `false`) says that the script can find its data without that identifier, so a pass does not have to carry it. `requiresSignature` (default `true`) says that a request naming this identifier must prove it may, with a signature or a secret; it should be set to `false` only for a value nobody can guess, such as a random token, and a key is exempted only when every provider that declares it says so. The proofs are those of the pass API, such as a `{key}.hmac` value computed with the tenant security secret, and a tenant can also list the key as an allowed unsigned identifier in its security configuration: see [Manage pass lifecycle with the API](https://docs.thewalletcrew.io/developers-guides/integration-guides/wallet/pass-lifecycle.md#creating-a-pass).

Entries without a `key` are ignored.

Each field has a `path`, the key as the script writes it (`loyaltyPoints`). `type` is one of `string`, `number`, `boolean`, `datetime`, `object` or `array` (not case-sensitive; an unknown or missing type reads as `string`). `description` is the text shown next to the variable in the admin console. `role` tells the platform what the value means, whatever its key:

| Role       | Meaning                                                                                                          |
| ---------- | ---------------------------------------------------------------------------------------------------------------- |
| `storeId`  | The id of the store the holder is attached to; The Wallet Crew resolves the store data from the tenant's stores. |
| `country`  | The holder's country, as an ISO 3166 two-letter code.                                                            |
| `postCode` | The holder's post code, which the store provider uses to find the nearest stores.                                |

When several providers write a value for the same role, the last non-empty one wins, later round first, then later entry. Fields without a `path` are ignored.

## Namespaces

A namespace keeps the keys of one provider apart from those of the others. Every key a script writes is published twice to the pass templates: under the key as written (`loyaltyPoints`) and under `{namespace}.{key}` (`crm.loyaltyPoints`). Pass identifiers (`id.*`) and `debug.*` keys are never namespaced. Templates that read the namespaced form keep working when another provider later writes a key of the same name, which is why it is the recommended form in new templates.

The namespace is the one `Describe` returns, otherwise the `scriptId`. When a pass type is saved, from the pass template editor or from the advanced configuration, every script entry of its `dataProviders` is checked, and the save is refused with the entry's position when:

* the namespace cannot be read by a template: it must be made of names of letters, digits and underscores, separated by dots, and no name may start with a digit;
* the namespace belongs to the platform: `id`, `debug`, and the names and groups of the data providers The Wallet Crew and its connectors publish;
* two different scripts of the same pass type publish under the same namespace.

A `scriptId` that contains a hyphen (`crm-data`) is a valid script id but not a valid namespace: a pass type that lists it is refused at save unless `Describe` returns a valid `namespace`, for example `crm_data` or `crm`. Camel case ids (`crmData`) avoid the problem.

## Return value

| Value returned by `Fill` | Meaning                                                                                                                                                                     |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `true`                   | The script found its data. It will not run again in the next rounds. In the account API, the customer counts as found.                                                      |
| `false`                  | The script found nothing, yet. It runs again in the next round if another entry found something. In the account API, the customer does not count as found by this provider. |

The keys written to the entity are kept whatever the return value. Returning `true` when nothing was found is a common mistake: it stops the script from getting the data of later rounds and, in the account API, makes an unknown customer look like a known one.

## Errors and edge cases

* **Fill throws or its promise rejects** (including a `fetch` that throws on a non-2xx answer, which is its default): the entry fails, the rounds stop, and the build of the pass fails. Depending on what asked for the data, a device cannot download or refresh the pass, a Google Wallet object is not written, or a creation request returns an error although the pass record has already been stored. A script that reads a system which may be down should therefore catch the failure, log it and return `false`, so that the pass is still built without the external values.
* **Fill is missing** from the registered object: the entry fails when it runs, as a thrown error would.
* **Describe is missing**: the script is published under its `scriptId` and declares no identifier and no field. Its values still reach the templates.
* **No script registers the key**: the entry runs nothing and counts as having found data (see the note in Registration).
* **Several files register the key**: the last registered wins, and the load order of files is not defined.
* **Both the pass data provider and the obsolete customer provider are registered for the same script id**: only the pass data provider runs.
* **Any script file of the tenant has a JavaScript error**: every script endpoint fails, this one included, until the file is fixed.

## Example

The script reads the customer from a CRM with a key kept in the tenant's secrets. A missing customer and an unavailable CRM are both soft failures: the script logs them and returns `false`, so the pass is still built, and the template shows its fallback.

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

const CRM_URL = 'https://crm.example.com/api/v2';

function describe() {
  return {
    namespace: 'crm',
    identifiers: [{ key: 'crm.customerId' }],
    fields: [
      { path: 'loyaltyPoints', type: 'number', description: 'Current points balance' },
      { path: 'tier', description: 'Membership tier: classic, silver or gold' },
      { path: 'memberSince', type: 'datetime', description: 'Date the customer joined' },
      { path: 'homeStoreId', role: 'storeId', description: 'Store the customer is attached to' }
    ]
  };
}

async function fill(entity) {
  const customerId = entity['id.crm.customerId'];
  if (!customerId) {
    return false;
  }

  const apiKey = await getSecret('CRM-API-KEY');
  if (!apiKey) {
    console.error('Secret CRM-API-KEY is not set: loyalty data is not available');
    return false;
  }

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

  if (response.StatusCode === 404) {
    console.warn(`Customer ${customerId} is unknown to the CRM`);
    return false;
  }
  if (response.StatusCode < 200 || response.StatusCode >= 300 || !response.ResponseText) {
    console.warn(`CRM lookup failed with status ${response.StatusCode}`);
    return false;
  }

  const customer = JSON.parse(response.ResponseText);
  entity['loyaltyPoints'] = customer.points ?? 0;
  entity['tier'] = customer.tier ?? null;
  entity['memberSince'] = customer.createdAt ?? null;
  entity['homeStoreId'] = customer.store?.id ?? null;
  return true;
}

export default function (context) {
  context.register('runtime.scriptable.passDataProvider.crm', {
    Fill: fill,
    Describe: describe
  });
}
```

The pass template then reads `crm.loyaltyPoints` and `crm.tier`, and the store data follows `homeStoreId` because the field declares the `storeId` role.

## Checking the result

The pass data inspection, `GET /api/{tenantId}/passes/{passId}/data` (pass read permission), builds the data of one pass exactly as a render does, without changing the pass, and reports every provider in order: whether it found data, did not, or failed, how long it took, why it failed, and the values it wrote under its namespace. It calls the external systems, like a real build. A failing provider does not fail this request, which makes it the quickest way to see an error that otherwise only shows as a pass that cannot be downloaded.

In the admin console, the pass template editor lists the scripts that can be added as data providers, with their namespace, and the fields their `Describe` declares. A script that does not appear in that list does not register a pass data provider key, or the tenant's scripts fail to load.

## Common pitfalls

* The script reads `entity.customerId` instead of `entity['id.customerId']`: pass identifiers always carry the `id.` prefix in the entity.
* `Describe` is declared `async`: it returns a promise instead of a description, and the editor shows no field for the script.
* A template reads the flat key, and a second provider added later writes the same key: the namespaced form avoids the clash.

## Use in the account API

The same script can also take part in the account API, which identifies and completes the customer during an enrolment, by being listed in the `customerProviders` entries of `server/account.yml`. These entries are live: only the endpoint named `customerProvider` is obsolete.

```yaml
customerProviders:
  - type: script
    scriptId: crm
```

The `customerProviders` entries run in the same kind of rounds as the `dataProviders` of a pass type, on one shared account. The entity is the account being enrolled, with the submitted fields and whatever earlier providers found. The result tells the platform whether the customer exists: at least one provider returning `true` means the customer was found, which is why `Fill` returns `false` for an unknown customer.

## FAQ

<details>

<summary><strong>Does the script need Describe?</strong></summary>

Not when its `scriptId` is a valid namespace. Without `Describe`, the values reach the templates under the key as written and under the `scriptId` namespace. `Describe` is what lets the pass template editor list the variables before a pass has them, assigns roles such as `storeId`, and chooses a namespace other than the `scriptId`. A hyphenated `scriptId` needs a `Describe` that returns a valid namespace, or the pass type is refused at save.

</details>

<details>

<summary><strong>Can two pass types use the same script with different settings?</strong></summary>

The script receives only the entity, not the pass type. A script that must behave differently per pass type is registered under two script ids, each listed by its own pass type, with the shared logic in helper functions of the same file.

</details>

<details>

<summary><strong>Is the data saved on the pass?</strong></summary>

No: the values are read at every build. A value that must survive an outage of the external system, or be used in scheduler filters, belongs in additional data or metadata instead. [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md#identifiers-additional-data-and-metadata) compares the places where a pass keeps data.

</details>


---

# 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/pass-data-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.
