> 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/customer-pipeline-element.md).

# Customer pipeline element

Run custom code as a step of a customer registration flow, for example to create the customer in a CRM before the pass is issued.

A customer registration flow is the ordered list of steps The Wallet Crew runs when an enrolment form is submitted with a flow: create the pass, send an email, call a connector. The customer pipeline element lets a tenant script be one of those steps. It receives the account being registered, can call any system the brand owns, and can write values back to the account, such as the id the CRM just assigned, for the following steps to use. This page is the reference for `runtime.scriptable.customerPipelineElement.{scriptId}`.

The pipeline element is the right tool when an action belongs to one registration flow: pushing a new member to an ERP, subscribing them to a newsletter, reserving a welcome offer. An action that must happen for every pass, whatever created it, belongs in the `OnPassCreated` hook of the [pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md). Rejecting invalid input is the job of the [account validator](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/account-validator.md), which runs before any step.

<details>

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

* A retailer creates the customer in its CRM during enrolment and stores the returned customer id as an identifier, so that the pass created by the next step carries it.
* A brand subscribes the customer to its marketing platform when the consent box is ticked.
* A ticketing integration attaches the registration to an existing order before the pass is issued.

</details>

## Registration

The script registers `runtime.scriptable.customerPipelineElement.{scriptId}`, and a flow of `server/flows.yml` lists a step of type `script` with the same `scriptId`:

```yaml
flows:
  - type: userRegistration
    name: loyalty
    steps:
      - type: script
        scriptId: crmSignup
      - type: pass
        passType: loyalty
      - type: mail
        mailTemplate: welcome
```

The flow name is the value of the `flow` query parameter of the enrolment request (`POST /api/{tenantId}/customer?flow=loyalty`). A flow name starts with a lowercase letter and is made of 2 to 50 letters, digits, underscores or hyphens.

The minimal skeleton is:

```js
export default function (context) {
  context.register('runtime.scriptable.customerPipelineElement.crmSignup', {
    CreateOrUpdate: async (entity) => {}
  });
}
```

## When it runs

The steps run one after the other, in the order of the flow, inside the enrolment request. By the time the flow starts, the request has passed validation (including the [account validator](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/account-validator.md)) and the identity checks of the tenant's account configuration. The script step therefore sees the account as submitted, completed with whatever the customer providers found, and every step after it sees what the script wrote, because all steps share the same account. When the last step has run, The Wallet Crew emits the customer upserted event and returns the account to the caller.

## Handlers

| Method           | Parameters | Returns               | Required           |
| ---------------- | ---------- | --------------------- | ------------------ |
| `CreateOrUpdate` | `entity`   | nothing, or a promise | No-op when missing |

`entity` is the account: a flat dictionary keyed by field name (`entity.email`, `entity.firstName`), with identifiers under `id.<key>` (`entity['id.crm.customerId']`). Writing a key adds or changes a value for the following steps; assigning `null` removes it. A key written under `id.<key>` becomes an identifier of the pass that a later `pass` step creates. Conventions for keys, dates and numbers are described in [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md).

## Return value

The return value is ignored; only what the script writes to `entity` matters. An `async` handler is awaited before the next step starts.

## Errors and edge cases

* **The handler throws or its promise rejects**: the error is logged, the remaining steps do not run (no pass is created by a later `pass` step, no email is sent), the customer upserted event is not emitted, and the enrolment request fails.
* **CreateOrUpdate is missing** from the registered object: the step does nothing, silently.
* **No script registers the key**: the step does nothing, silently. A misspelt `scriptId` therefore looks like a script that ran without effect.
* **Several files register the key**: the last registered wins, and the load order of files is not defined.
* **A step type that does not exist**: the flow fails when it reaches that step.

{% hint style="warning" %}
The account returned to the caller of the enrolment request contains every key the steps wrote, except `debug.*` keys. A token, an internal reference or an API answer written to the entity is therefore visible to the person who submitted the form. Keep such values in local variables, or under a `debug.` key when they must be kept for diagnosis.
{% endhint %}

## Example

The step creates the customer in a CRM, or finds the existing one, and stores the CRM id as a pass identifier. The CRM answers 409 when the email already exists, so the script then reads the existing customer instead. A failure stops the flow on purpose: issuing a pass without a CRM id would leave a pass the CRM cannot match.

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

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

// A consent may arrive as a boolean or as text, depending on the form.
function toBoolean(value) {
  return value === true || ['true', 'on', '1', 'yes'].includes(String(value).toLowerCase());
}

async function crmHeaders() {
  const apiKey = await getSecret('CRM-API-KEY');
  if (!apiKey) {
    throw new Error('Secret CRM-API-KEY is not set');
  }
  return { 'X-Api-Key': apiKey };
}

async function createOrUpdate(entity) {
  if (entity['id.crm.customerId']) {
    return;
  }

  const headers = await crmHeaders();
  const created = await fetch(`${CRM_URL}/customers`, {
    Method: 'POST',
    Headers: headers,
    Body: {
      email: entity.email,
      firstName: entity.firstName ?? null,
      lastName: entity.lastName ?? null,
      marketingOptIn: toBoolean(entity.optIn)
    },
    ThrowOnError: false
  });

  let customer;
  if (created.StatusCode === 201) {
    customer = JSON.parse(created.ResponseText);
  } else if (created.StatusCode === 409) {
    const existing = await fetch(`${CRM_URL}/customers?email=${encodeURIComponent(entity.email)}`, { Headers: headers });
    customer = JSON.parse(existing.ResponseText);
  } else {
    throw new Error(`CRM refused the customer with status ${created.StatusCode}`);
  }

  entity['id.crm.customerId'] = String(customer.id);
}

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

{% hint style="info" %}
`fetch` retries a POST on a transient failure, so the creation endpoint should be idempotent, as here where a second creation of the same email answers 409 and is resolved by a lookup. See [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md) for the retry rules.
{% endhint %}

## Checking the result

Submitting the form of the flow, or calling `POST /api/{tenantId}/customer?flow=<name>` with test data, returns the account as the steps left it: the identifiers the script wrote are in the response, and the pass created by a later `pass` step carries them, which the pass list of the admin console shows. When the request fails, the error the script threw is recorded in the platform's monitoring together with the name of the step.

## Common pitfalls

* The script step is listed after the `pass` step, so the pass is created before the identifier exists.
* The script throws when an optional system (a newsletter platform) is down, which blocks every enrolment; catching and logging the error lets the registration continue.
* A consent value may arrive as a boolean or as text, depending on the form: the script normalizes it before mapping it to the external system, and checks the mapping in both directions.

## FAQ

<details>

<summary><strong>Can one script be used in several flows?</strong></summary>

Yes. Every flow that lists a `script` step with the same `scriptId` runs the same handler. A script that must behave differently per flow is registered under two script ids, with shared helpers in the same file.

</details>

<details>

<summary><strong>Does the step run when an existing customer re-registers?</strong></summary>

It runs every time the flow runs. The handler checks what the account already carries (an identifier found by a customer provider, for example) to decide between creating and updating, as the example does.

</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/customer-pipeline-element.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.
