> 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-updater.md).

# Pass updater

Choose the pass type or rewrite identifiers when a pass is created or updated, and react to installs and uninstalls, with runtime.wallet.passUpdater.

The pass updater gives a tenant script a say in the life of every pass. Two hooks run before a pass is saved and can change it: they choose the pass type and rewrite the identifiers. Four hooks are notifications that run after something happened: the pass was created, updated, installed in a wallet or removed from it. This page is the reference for `runtime.wallet.passUpdater`; it is the place to come back to when a pass gets the wrong pass type, when an installation does not reach the CRM, or when a hook seems to run more often than expected.

The pass updater acts on every pass of the tenant, whatever created it: a registration flow, the pass API, an import, a connector. An action that belongs to one registration flow is better placed in a [customer pipeline element](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/customer-pipeline-element.md). Data that the pass displays is better read by a [pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md) than written by a hook.

<details>

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

* A gift card program issues each gift card pass on the pass type that matches the card's product code, read from the identifiers sent at creation.
* A brand tells its CRM, in a customer field, whether the customer's pass is installed on Apple Wallet, Google Wallet or neither.
* A data warehouse receives a row every time a pass is created, with its pass type and creation date.
* A membership program moves a pass to another pass type when an identifier shows that the member changed level.

</details>

## Registration

The key is `runtime.wallet.passUpdater`. Registering it is enough: no configuration file refers to it.

```js
export default function (context) {
  context.register('runtime.wallet.passUpdater', {
    OnPassCreating: async (passType, identifiers) => null
  });
}
```

Unlike most endpoints, **every** registration of this key runs, so several files can each register their own pass updater with the hooks they need. They run one after the other, in registration order: the order of the `register` calls within a file, while the order between files is not defined. Hooks that depend on each other's results therefore belong in the same file.

## When it runs

| Hook                | Runs                                                                                      | Can change the pass |
| ------------------- | ----------------------------------------------------------------------------------------- | ------------------- |
| `OnPassCreating`    | Before a new pass is saved, inside the request or job that creates it                     | Yes                 |
| `OnPassCreated`     | After the pass is saved and its data is built, inside the same operation                  | No                  |
| `OnPassUpdating`    | Before every save of an existing pass                                                     | Yes                 |
| `OnPassUpdated`     | After every save of an existing pass, once the push to devices has been attempted         | No                  |
| `OnPassInstalled`   | When a device or account registers the pass (Apple device registration, Google save)      | No                  |
| `OnPassUninstalled` | When the last Apple device, or the last Google account, removes the pass from that wallet | No                  |

The next diagram shows the order around one save.

```mermaid
flowchart LR
  A[Request creates or updates a pass] --> B[Creating or Updating hook of each pass updater]
  B --> C[Platform saves the pass]
  C --> D[Update only: platform pushes the change to devices]
  D --> E[Created or Updated hook of each pass updater]
```

All hooks are awaited inside the operation that triggered them: a slow hook makes the pass creation request, the update or the wallet's registration call slower. The notification hooks of one event run at the same time as the platform's other handlers of that event, such as the connectors' own handlers, but the registered pass updaters themselves run one after the other.

{% hint style="warning" %}
A pass is saved more often than a brand usually expects. Besides explicit updates through the API, imports, push updates and connectors, recording a device registration or unregistration also saves the pass, so `OnPassUpdating` and `OnPassUpdated` also run when a pass is installed or removed. Update hooks must be cheap and idempotent.
{% endhint %}

## Handlers

Every hook is optional: a missing hook is skipped.

| Method              | Required | Parameters                                                             | Returns                                 |
| ------------------- | -------- | ---------------------------------------------------------------------- | --------------------------------------- |
| `OnPassCreating`    | No       | `passType`, `identifiers`                                              | `{ PassType?, Identifiers? }` or `null` |
| `OnPassCreated`     | No       | `passId`, `passType`, `identifiers`, `creationDate`                    | nothing                                 |
| `OnPassUpdating`    | No       | `passId`, `passType`, `identifiers`                                    | `{ PassType?, Identifiers? }` or `null` |
| `OnPassUpdated`     | No       | `passId`, `passType`, `identifiers`                                    | nothing                                 |
| `OnPassInstalled`   | No       | `passId`, `passType`, `identifiers`, `device`, `additionalInformation` | nothing                                 |
| `OnPassUninstalled` | No       | `passId`, `passType`, `identifiers`, `device`, `additionalInformation` | nothing                                 |

The parameters are:

* `passId`: the id of the pass (its serial number).
* `passType`: the pass type name, as in `server/passes/<passType>.yml`. In `OnPassCreating` it can be `null` or empty when the caller did not give one; the hook can then supply it.
* `identifiers`: the pass identifiers as an object keyed **without** the `id.` prefix: a pass carrying `crm.customerId` is read as `identifiers['crm.customerId']`.
* `creationDate`: when the creation event occurred, as a date object that has the usual `Date` methods (`toISOString()`, `getTime()`), but is not an instance of `Date`.
* `device`: the wallet, as a **number**: `0` for Apple Wallet, `2` for Google Wallet. Comparing it with the strings `"apple"` or `"google"` never matches.
* `additionalInformation`: camelCase objects, described below.

For `OnPassInstalled`, `additionalInformation` is:

```js
{
  registrationInformation: { activeRegistrationCount: 1, totalRegistrationCount: 3 },
  registrationSource: { tags: ['newsletter'], medium: 'email', origin: 'https://www.example.com/wallet', userAgent: 'Mozilla/5.0 ...' }
}
```

`registrationInformation` counts registrations after the event: for Apple Wallet, a registration is one device (a new phone or a paired watch is a new registration); for Google Wallet, it is one Google account (a pass shared to several accounts has one registration per account, and several devices of one account count once). `activeRegistrationCount` is the number of current registrations, `totalRegistrationCount` the number ever recorded. `totalRegistrationCount` never decreases: for a pass installed, removed and installed again, it reads 1, 1 and 2 at the three events, while `activeRegistrationCount` reads 1, 0 and 1. Both counts cover the two wallets together: an `activeRegistrationCount` of `0` means that the pass is no longer installed anywhere. `registrationSource` describes where the installation came from: `tags` and `medium` as set on the add-to-wallet entry point, `origin` (by default the URL of the page with the add-to-wallet button) and `userAgent` of that page. Each of its members can be `null`, for example when a pass was installed through sharing or a phone transfer.

For `OnPassUninstalled`, `additionalInformation` holds `registrationInformation` only. The hook runs per wallet, each time the last device (or Google account) of that wallet removes the pass; an `activeRegistrationCount` above `0` then means that an installation in the other wallet is still active.

## Return value

Only `OnPassCreating` and `OnPassUpdating` change the pass, through the object they return, whose keys are PascalCase:

| Returned                        | Effect                                                                                               |
| ------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `null`, `undefined`, or nothing | No change.                                                                                           |
| `{ PassType: 'gold' }`          | The pass gets that pass type. An empty string or `null` keeps the current one.                       |
| `{ Identifiers: { ... } }`      | The object **replaces all** identifiers of the pass. `{ Identifiers: {} }` removes every identifier. |
| `{ PassType, Identifiers }`     | Both changes.                                                                                        |

To add one identifier, the hook returns every identifier it knows plus the new key, for example `{ Identifiers: { ...identifiers, 'crm.segment': 'vip' } }`; returning only the new key would drop the others. Spread works on the `identifiers` argument, while `Object.keys` throws on it. When several pass updaters are registered, each one receives the pass type and identifiers as the previous one left them.

The notification hooks return nothing; a returned value is ignored.

## Errors and edge cases

* **A hook throws or its promise rejects**: the error is logged with the name of the event, the changes of that script are not applied, the other registered pass updaters still run, and the operation continues. A failing hook never blocks a creation, an update or an installation.
* **A hook is missing**: it is skipped.
* **No pass updater is registered**: nothing runs.
* **`OnPassCreating` returns nothing in one branch and `null` in another**: both mean "no change", so the behavior is consistent; returning `{}` is also "no change". Only `{ Identifiers: {} }` clears identifiers.
* **A hook calls the platform's own REST API to change the pass it is called for**: this triggers another update, and therefore the hooks again. Changes to the pass belong in the return value of `OnPassCreating` or `OnPassUpdating`.

## Example

### Choosing the pass type at creation

The gift card number sent at creation starts with a product code, and a lookup table gives the pass type for each code. Unknown codes keep the pass type the caller asked for.

```js
const PASS_TYPE_BY_PRODUCT = {
  GC10: 'giftcard-classic',
  GC50: 'giftcard-premium',
  EGC: 'giftcard-digital'
};

async function onPassCreating(passType, identifiers) {
  const cardNumber = identifiers['pos.giftCardId'];
  if (!cardNumber) {
    return null;
  }

  const productCode = cardNumber.split('-')[0];
  const mapped = PASS_TYPE_BY_PRODUCT[productCode];
  return mapped ? { PassType: mapped } : null;
}

export default function (context) {
  context.register('runtime.wallet.passUpdater', {
    OnPassCreating: onPassCreating
  });
}
```

### Reporting installations to a CRM

The CRM keeps one field per wallet. The script uses `PUT`, which can be repeated safely when `fetch` retries a transient failure, and logs a failure instead of throwing, since a throw would only be logged anyway.

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

const WALLETS = { 0: 'appleWallet', 2: 'googleWallet' };

async function reportWalletStatus(identifiers, device, status) {
  const customerId = identifiers['crm.customerId'];
  const field = WALLETS[device];
  if (!customerId || !field) {
    return;
  }

  const apiKey = await getSecret('CRM-API-KEY');
  const response = await fetch(`https://crm.example.com/api/v2/customers/${encodeURIComponent(customerId)}/fields/${field}`, {
    Method: 'PUT',
    Headers: { 'X-Api-Key': apiKey },
    Body: { value: status },
    ThrowOnError: false
  });
  if (response.StatusCode < 200 || response.StatusCode >= 300) {
    console.warn(`CRM refused the ${field} status of customer ${customerId}: ${response.StatusCode}`);
  }
}

export default function (context) {
  context.register('runtime.wallet.passUpdater', {
    OnPassInstalled: (passId, passType, identifiers, device) => reportWalletStatus(identifiers, device, 'installed'),
    OnPassUninstalled: (passId, passType, identifiers, device) => reportWalletStatus(identifiers, device, 'uninstalled')
  });
}
```

`OnPassUninstalled` runs only when the last device or account of that wallet removed the pass, so the field of that wallet can be set at once. A single CRM field for both wallets would instead test `additionalInformation.registrationInformation.activeRegistrationCount === 0`, which counts both wallets.

## Checking the result

A pass created through the API or a test enrolment shows its pass type and identifiers in the pass list of the admin console, and `GET /api/{tenantId}/passes/{passId}` returns them; a pass type chosen by `OnPassCreating` appears there. The platform also records, at information level, every pass type or identifier change a pass updater makes, and at error level every hook that failed, with the name of the event; The Wallet Crew support can look these up. For notification hooks, the external system is the place to check: a test installation on a device should produce the expected call.

## Common pitfalls

* `device` compared with a string instead of `0` or `2`.
* `Identifiers` returned with only the new key, which erases the others.
* An update hook that calls an external system on every save, including the saves of device registrations, and overloads it.
* A pass updater split across two files whose hooks expect to run in a given order.

## FAQ

<details>

<summary><strong>Why does OnPassInstalled run again for a customer who already has the pass?</strong></summary>

Each new registration fires it: a second device, a watch, a reinstall after removal, or, for Google Wallet, another Google account. `registrationInformation.totalRegistrationCount` tells a first installation (1) from a later one: it never decreases, so a reinstall after a removal reports 2.

</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-updater.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.
