> 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-code-generator.md).

# Benefit code generator

Compute the code of each benefit issued from a benefit template whose code mode is custom, with runtime.scriptable.benefitTemplateCodeGenerator.

A benefit template can give the benefits it issues a code that staff scan or type: the same code for everyone, a random code drawn from a pattern, or a code computed by a script. The last option, the custom code mode, runs a short script each time a benefit is issued from the template, typically to reserve a unique code in a partner system or to build a code from the brand's own rules. This page explains how that script is written, stored and run; the endpoint behind it is `runtime.scriptable.benefitTemplateCodeGenerator.{templateId}`.

The custom mode is the right tool when each benefit needs a code that only another system can produce. When the codes can be random, the autogenerated mode does the same without a script; when the codes of an external system's own benefits must be shown, the [benefit provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/benefit-provider.md) returns them with each benefit.

<details>

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

* A welcome offer reserves a single-use promotion code in the e-commerce platform for each new member.
* A partner program draws a voucher number from the partner's code pool.
* A brand builds codes with its own prefix and check digit, so that its point-of-sale system can validate them.

</details>

## Registration

Unlike the other endpoints, this one is not written as a file. The script is the **body of a function**, entered in the code settings of the benefit template, in the admin console or through the benefit template API, with the code mode set to custom:

```json
{
  "code": {
    "valueMode": "custom",
    "script": "return `WELCOME-${Math.floor(Math.random() * 2176782336).toString(36).padStart(6, '0').toUpperCase()}`;"
  }
}
```

The `script` member is required in the custom mode; the optional `format` member chooses how the code is rendered: `ean13`, `code128`, `qrCode`, `pdf417`, `aztec`, `dataMatrix`, `code39`, or `raw` for text only. When the benefit template is saved, The Wallet Crew wraps the body into a script file, `server/scripts/benefit-template-code-{templateId}.js`, which registers `runtime.scriptable.benefitTemplateCodeGenerator.{templateId}` with the body as its `Generate` handler:

```js
export default function (context) {
  context.register("runtime.scriptable.benefitTemplateCodeGenerator.welcome-offer", {
    Generate: async function () {
      // the body entered on the benefit template
    }
  });
}
```

The file is rewritten each time the benefit template is saved and deleted when the template leaves the custom mode or is deleted. It should not be edited by hand, and no other file should register the same key.

## When it runs

`Generate` runs each time a benefit is issued from the benefit template to a pass that does not hold one yet, inside the operation that grants it: a scheduled task or campaign, an import row with a benefit template, an API call. Re-applying the template to a pass that already holds its benefit updates that benefit without calling the script.

## Handlers

| Method     | Parameters | Returns                         | Required |
| ---------- | ---------- | ------------------------------- | -------- |
| `Generate` | none       | a promise of a string or `null` | Required |

The body runs inside an `async` function: it ends with `return`, and can use `await` with the globals, such as [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md) and `console`. It receives no information about the pass or the customer. Because it is a function body and not a file, it cannot contain `import` statements.

## Return value

| Returned              | Effect                                                                          |
| --------------------- | ------------------------------------------------------------------------------- |
| A string              | The benefit is issued with that code, rendered in the template's code `format`. |
| `null` or `undefined` | The benefit is issued without a code.                                           |

## Errors and edge cases

* **The body throws or its promise rejects** (including a `fetch` that throws on a non-2xx answer, its default): the benefit is not issued to that pass, and the operation that granted it reports the error.
* **The body does not parse**: the benefit template is still saved, and the admin console warns about the syntax error. The generated file then breaks **every** script of the tenant, not only this one, until the body is fixed. Test the body on a copy of the benefit template before saving it on a live one.
* **The file is missing**, for example after a manual deletion: a warning is logged and benefits are issued without a code.
* **The code mode is changed away from custom**: the file is deleted and the script no longer runs.

## Example

The body reserves a unique code in a promotion platform. The platform answers `201` with the code; any other answer throws, so that no benefit is issued without the code the holder needs.

```js
const response = await fetch('https://promotions.example.com/api/pools/welcome/codes', {
  Method: 'POST',
  Headers: { 'X-Client': 'wallet' },
  ThrowOnError: false
});

if (response.StatusCode !== 201 || !response.ResponseText) {
  throw new Error(`Code reservation failed with status ${response.StatusCode}`);
}

const reservation = JSON.parse(response.ResponseText);
return reservation.code;
```

{% hint style="info" %}
`fetch` retries a POST on transient failures, so a retried reservation can reserve two codes and use one. A pool that accepts an idempotency key, or a code built locally from the brand's rules, avoids wasting codes.
{% endhint %}

## Checking the result

Granting the benefit template to a test pass, then listing the pass's benefits with `GET /api/{tenantId}/passes/{passId}/benefits`, shows the generated code on the new benefit. A benefit issued without a code means the body returned nothing; a benefit that is not issued at all means it threw, which the platform's monitoring records with the error.

## Common pitfalls

* The body has no `return`, so every benefit is issued without a code.
* A code computed from `Date.now()` alone collides when two benefits are issued in the same millisecond. Add a random part, as the registration example does, or reserve the code in a system that guarantees uniqueness.

## FAQ

<details>

<summary><strong>Can the body read a secret?</strong></summary>

The body cannot contain `import` statements, so modules such as `twc/secrets` are not available to it. A partner system that needs a credential is called from a system the brand controls, or the code is built without a credential.

</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/benefit-code-generator.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.
