> 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/recipes.md).

# Recipes

Script patterns for common needs, written in full or pointing to the page that holds the example.

Most scripts are variations of a short list of patterns. Starting from a pattern that already handles the failure modes of its extension point is faster and safer than starting from a blank file, because the failure modes differ between extension points: a throw in a pass data provider fails the render, a throw in a pass updater notification is only logged, a throw in an email engine fails the send. Recipes 4 and 8 combine several features and are written in full here. The others point to the page that holds their example, so that each example exists once. Hosts, secrets and field names are fictitious and have to be replaced.

The registration key, the wiring and the full reference of each extension point are on the [endpoint pages](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints.md). The recipes assume the rules of [How scripts run](https://docs.thewalletcrew.io/developers-guides/scripting/how-scripts-run.md) and [Handlers](https://docs.thewalletcrew.io/developers-guides/scripting/handlers.md).

| # | Goal                                                            | Extension point                                                                                                               |
| - | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| 1 | Read data from an API protected by OAuth 2.0 client credentials | [Pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md)               |
| 2 | Choose the pass type when a pass is created                     | [Pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md)                           |
| 3 | Mirror install and uninstall events into a CRM                  | [Pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md)                           |
| 4 | Push a registration to a CRM and map a consent flag             | [Customer pipeline element](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/customer-pipeline-element.md) |
| 5 | Update passes from a paged API on a schedule                    | [Push updates](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/push-updates.md)                           |
| 6 | Send transactional emails through another provider              | [Email engine](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-engine.md)                           |
| 7 | Choose, or skip, the enrolment confirmation email               | [Email challenge template](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-challenge-template.md)   |
| 8 | Derive a business segment from data another provider read       | [Pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md)               |
| 9 | Authenticate with a token endpoint that needs a custom exchange | [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md)                                           |

## 1. Read data from an OAuth-protected API

The complete example, a pass data provider that reads a CRM protected by the OAuth 2.0 client credentials grant, with the secrets, a cache keyed by the customer id and a soft failure, is on [fetch authentication](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.md#example-client-credentials-in-a-pass-data-provider).

## 2. Choose the pass type when a pass is created

The example, a lookup table with a neutral fallback in `OnPassCreating`, is the first example of the [pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md#choosing-the-pass-type-at-creation).

## 3. Mirror installs and uninstalls into a CRM

The example, with one field per wallet and an idempotent `PUT`, is the second example of the [pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md#reporting-installations-to-a-crm). The identifier is read as `identifiers['crm.customerId']`, keyed without the `id.` prefix, like everywhere else.

## 4. Push a registration to a CRM and map a consent flag

The goal is to create or update the customer in an external system as soon as the enrolment flow reaches the step. The script is a step of a flow, so its error fails the step; the example therefore lets a failure of the CRM reach the flow deliberately, since an enrolment that silently skipped the CRM would leave the two systems out of step. The consent may arrive on the account as a boolean or as text, and it is an enumeration in the CRM; the mapping is written once, in both directions, to avoid an inversion.

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

const CONSENT_TO_CRM = { true: 'opt_in', false: 'opt_out' };

// A consent can arrive as text: 'n' is truthy, so the text is compared, never tested for truthiness.
function toBoolean(value) {
  return value === true || value === 'true' || value === 'y' || value === 'yes';
}

async function createOrUpdate(entity) {
  const apiKey = await getSecret('CRM-API-KEY');
  const consent = toBoolean(entity['consents_email']);

  const response = await fetch(`https://crm.example.com/api/contacts/${encodeURIComponent(entity['email'])}`, {
    Method: 'PUT',
    Headers: { 'X-Api-Key': apiKey },
    Body: {
      email: entity['email'],
      firstName: entity['firstName'] ?? '',
      marketing: CONSENT_TO_CRM[consent],
    },
  });

  if (!response.ResponseText) {
    throw new Error(`CRM answered ${response.StatusCode} with an empty body`);
  }
  const contact = JSON.parse(response.ResponseText);
  entity['id.crm.contactId'] = String(contact.id);
}

export default function (context) {
  context.register('runtime.scriptable.customerPipelineElement.crmContact', {
    CreateOrUpdate: createOrUpdate,
  });
}
```

The step is added to the flow in `server/flows.yml`:

```yaml
flows:
  - type: userRegistration
    name: default
    steps:
      - type: script
        scriptId: crmContact
```

Notes. `ThrowOnError` is left at its default of `true`, so a non-success status throws and fails the step; a flow that must not depend on the CRM catches the failure and logs it instead. The contact id is written back on the entity as `id.crm.contactId` for the steps that follow in the flow. The consent key is `consents_email`, which may arrive as a boolean or as text, depending on the form (see [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md#key-conventions)). The consent mapping is a single object, so the inverse mapping, when needed, is derived from it rather than rewritten, and truthiness is never relied on for strings such as `'n'`. A flow step with no script registered under its `scriptId` does nothing, without an error.

## 5. Update passes from a paged API on a schedule

The example, a paged API read with a hard cap and a logged truncation, is on [Push updates](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/push-updates.md#example), with the `server/scheduler.yml` task.

## 6. Send transactional emails through another provider

The example, which renders the template with `buildEmail` and forwards the result, is on the [email engine](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-engine.md#example) page, with the `server/emails.yml` setting.

## 7. Choose, or skip, the enrolment confirmation email

The examples, a choice by customer and a choice by language, are on the [email challenge template](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-challenge-template.md#example) page.

## 8. Derive a business segment from data another provider read

The goal is to compute a label that layouts and filters can use, from values other providers wrote. The providers of a pass type run in rounds, as described in [Pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md#the-dataproviders-rounds). The segment provider therefore returns `false` until its input exists.

```js
async function fill(entity) {
  const points = entity['points'];
  if (points === undefined) {
    return false;
  }

  entity['label'] = points >= 1000 ? 'vip' : points >= 200 ? 'regular' : 'new';
  return true;
}

function describe() {
  return {
    namespace: 'memberSegment',
    fields: [{ path: 'label', description: 'Member segment: vip, regular or new' }],
  };
}

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

The entry is listed after the provider that writes `points`:

```yaml
dataProviders:
  - provider: script
    scriptId: memberLookup
  - provider: script
    scriptId: memberSegment
```

Notes. A template reads `memberSegment.label`. The entity of a later round holds the keys as the other providers wrote them (`points`), not their namespaced form. The provider does not call any remote system, so it needs neither a cache nor a soft failure, but it keeps returning `false` rather than `true` when it computed nothing. The first round runs both providers side by side, so the segment provider necessarily finds nothing there; it computes in the second round, after `memberLookup` has found data. Without a provider that finds data in the first round, no second round happens.

## 9. Authenticate through a token endpoint with a custom exchange

The example, a `CustomBearer` token retriever for a token endpoint that is not a standard OAuth 2.0 one, is on [fetch authentication](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.md#example-custombearer-with-a-custom-token-exchange).

## FAQ

<details>

<summary><strong>Where do the secret names come from?</strong></summary>

They are chosen when the secrets are created in the admin console, and have to follow the [secret key rules](https://docs.thewalletcrew.io/developers-guides/scripting/modules/secrets.md#keys). Names such as `CRM-API-KEY` in the examples are placeholders.

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