> For the complete documentation index, see [llms.txt](https://docs.wynta.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.wynta.com/gamification.md).

# Gamification

## Gamification SDK: client integration

Embed the player's loyalty screen in an iframe. Your backend signs an authentication payload, and your frontend passes it to the iframe. The iframe handles authentication, API calls, and rendering.

### 1. Get integration details

Request these from the Wynta team:

* **Gamification UI URL** — the base URL for the iframe.
* **`client_id`** — your registered client identifier, linked to your site.
* **`client_secret`** — the signing secret. Keep it on your backend only.

Use HTTPS in production. You do not need to send `site_id`.

### 2. Backend: create a signed payload

Create an authenticated endpoint on your backend that returns `{ client_id, payload, hash }`. Use the logged-in player's ID from your server session.

#### Encoding and signing flow

Run all five steps on your backend:

```
Player claims → JSON string → UTF-8 bytes → Base64 string = payload
                                               │
                           client_secret + HMAC-SHA256
                                               │
                                       lowercase hex = hash

Return { client_id, payload, hash } to your frontend
```

1. **Build the claims object.** Include `user_id`, `timestamp` (current Unix seconds), and `transaction_id` (a new UUID for this attempt).
2. **Convert the object to a JSON string.** Use `JSON.stringify(claims)` in Node.js. For the fixed example below, the exact string is:

   ```
   {"user_id":"player_123","timestamp":1789430400,"transaction_id":"550e8400-e29b-41d4-a716-446655440000"}
   ```
3. **Encode that string as Base64.** Convert the JSON string to UTF-8 bytes, then encode those bytes using standard Base64, keeping any trailing `=` padding and adding no line breaks. This produces the `payload` field:

   ```
   eyJ1c2VyX2lkIjoicGxheWVyXzEyMyIsInRpbWVzdGFtcCI6MTc4OTQzMDQwMCwidHJhbnNhY3Rpb25faWQiOiI1NTBlODQwMC1lMjliLTQxZDQtYTcxNi00NDY2NTU0NDAwMDAifQ==
   ```

   Base64 is reversible encoding, not encryption. It does not hide the player's ID.
4. **Sign the Base64 string.** Use HMAC-SHA256 with your `client_secret` as the key and the exact `payload` string from step 3 as the message. Convert the resulting digest to lowercase hexadecimal to create `hash`. Do not sign the raw JSON, decode the payload before signing, or include the surrounding JSON quotes.
5. **Return the request body.** Add your `client_id` alongside the unchanged `payload` and `hash`. The frontend passes this object to the iframe without re-encoding it. The secret is never included in the body.

#### Node.js implementation

```ts
import { createHmac, randomUUID } from 'node:crypto';

function createSdkAuthBody(userId: string, clientId: string, clientSecret: string) {
  const claims = {
    user_id: userId,
    timestamp: Math.floor(Date.now() / 1000),
    transaction_id: randomUUID(),
  };
  const json = JSON.stringify(claims);            // Object → JSON string
  const bytes = Buffer.from(json, 'utf8');        // JSON string → UTF-8 bytes
  const payload = bytes.toString('base64');       // UTF-8 bytes → Base64 string
  // Sign the exact Base64 string and return the digest as lowercase hex.
  const hash = createHmac('sha256', clientSecret).update(payload).digest('hex');

  return { client_id: clientId, payload, hash };
}
```

Example response using the dummy secret `example_secret`:

```json
{
  "client_id": "game_server",
  "payload": "eyJ1c2VyX2lkIjoicGxheWVyXzEyMyIsInRpbWVzdGFtcCI6MTc4OTQzMDQwMCwidHJhbnNhY3Rpb25faWQiOiI1NTBlODQwMC1lMjliLTQxZDQtYTcxNi00NDY2NTU0NDAwMDAifQ==",
  "hash": "4a8146401a72ea20fcab4091e5ae14db13d41aaf1955ba18de43b5b0047f0fab"
}
```

The `payload` decodes to:

```json
{
  "user_id": "player_123",
  "timestamp": 1789430400,
  "transaction_id": "550e8400-e29b-41d4-a716-446655440000"
}
```

The hash is `HMAC-SHA256(example_secret, payload)` in hex. These values are illustrative; use your registered credentials, the current timestamp, and a new transaction ID for actual requests.

Requirements:

* Sign the **Base64 string**, using HMAC-SHA256, and return the hash as hex.
* Generate the payload when requested; do not cache it. The default timestamp window is **60 seconds**, so keep your server clock accurate.
* Generate a new `transaction_id` and timestamp for every attempt, including retries.
* Return only the signed body to the frontend; never return `client_secret`.

### 3. Frontend: embed and authenticate

Register the message listener **before loading the iframe**. When it sends `PAGE_LOADED`, fetch a fresh signed body from your backend and reply with `SDK_AUTH_PAYLOAD`.

```html
<div id="gamification"></div>
<script>
  const gamificationUiUrl = 'https://<gamification-ui-host>';
  const gamificationUiOrigin = new URL(gamificationUiUrl).origin;
  const iframe = document.createElement('iframe');
  iframe.title = 'Loyalty progress';

  async function handleMessage(event) {
    if (event.origin !== gamificationUiOrigin) return;
    if (event.source !== iframe.contentWindow) return;
    if (event.data?.type !== 'PAGE_LOADED') return;

    try {
      // Replace this URL with your authenticated backend endpoint from step 2.
      const response = await fetch('/api/gamification/auth-payload', {
        method: 'POST',
        credentials: 'same-origin',
        cache: 'no-store',
      });
      if (!response.ok) throw new Error('Unable to authenticate gamification');
      const body = await response.json();

      iframe.contentWindow.postMessage(
        { type: 'SDK_AUTH_PAYLOAD', body },
        gamificationUiOrigin,
      );
    } catch (error) {
      console.error(error); // Show a retry option in your application's UI.
    }
  }

  window.addEventListener('message', handleMessage);
  iframe.src = `${gamificationUiUrl}/user-loyalty-points`;
  document.getElementById('gamification').appendChild(iframe);
  // Remove the message listener when your embedding component unmounts.
</script>
```

Do not put authentication data in the iframe URL. Always validate both `event.origin` and `event.source`, and send the reply to the exact iframe origin.

| Direction              | Message                                                            |
| ---------------------- | ------------------------------------------------------------------ |
| Iframe → your frontend | `{ type: 'PAGE_LOADED' }`                                          |
| Your frontend → iframe | `{ type: 'SDK_AUTH_PAYLOAD', body: { client_id, payload, hash } }` |

`PAGE_LOADED` means the iframe mounted; it does not confirm authentication or data loading. There is currently no ready/success message. The iframe displays its own loading and error states. Your client does not call the SDK auth endpoint or manage the player token.

### Troubleshooting

If iframe authentication returns `401 Invalid request`, check:

* The client is active and `client_id` / `client_secret` are correct.
* The HMAC signs the exact Base64 payload string.
* The timestamp is in Unix **seconds** and within the allowed window (default 60 seconds).
* The `transaction_id` has not already been used.

To retry, reload the iframe and let the handshake request a newly signed payload.

## Delight: client integration

Show a reward game (spin wheel, flip cards, chest or scratch card) to a player after a qualifying deposit. Your page loads the Wynta Web SDK, checks the deposit, and plays the game. The prize is picked on Wynta's servers and credited to the player's account.

| When            | You do                                                                           | What happens                                     |
| --------------- | -------------------------------------------------------------------------------- | ------------------------------------------------ |
| Setup           | Load the SDK and call `Wynta.init()`                                             | The player is signed in                          |
| After a deposit | After a successful deposit, call `Wynta.checkDelight()`                          | Wynta says whether the deposit unlocked a reward |
| On click        | If `applicable`, show your own button. On click, call `Wynta.playDelight(check)` | The game opens over your page                    |
| After the game  | Nothing                                                                          | The player plays and the prize is credited       |

> **Before you start:** your page needs the Web SDK loaded and signed in with `Wynta.init()`, which uses your `client_id` and a signed payload from your backend. That setup is the same as in [Gamification SDK: client integration](https://docs.wynta.com/gamification).

### 1. After a deposit: check for a reward

Call `Wynta.checkDelight` only after your own system has confirmed the deposit. Pass the **deposit's transaction id**, the same one your deposit event carries.

```js
const check = await Wynta.checkDelight({ transactionId: 'dep_8324_1793275781879' });
```

It returns one of two shapes:

```js
// No reward for this deposit
{ applicable: false, reason: 'no_matching_rule' }

// A reward was unlocked
{
  applicable: true,
  rewardId: 15,
  status: 'unlocked',
  gameUrl: 'https://…/delight/#token=…',   // used by the SDK; you don't read it
  expiresAt: Date,                          // the player can play until this time
  ui: { title: 'REWARD UNLOCKED', subtitle: 'Tap to reveal your surprise' }
}
```

When `applicable` is `false`, `reason` is one of:

| reason                | Meaning                                                              | What to do                                 |
| --------------------- | -------------------------------------------------------------------- | ------------------------------------------ |
| `deposit_not_found`   | The deposit isn't recorded yet, or the id is wrong                   | Retry up to 3 times, about 2 seconds apart |
| `no_active_rule`      | The site has no active Delight                                       | Nothing                                    |
| `no_matching_rule`    | The deposit doesn't meet any rule (amount, promo code, player group) | Nothing                                    |
| `daily_limit_reached` | The player reached the rule's daily limit                            | Nothing                                    |
| `no_prize_available`  | Every prize is sold out, or no prize fits this deposit amount        | Nothing                                    |
| `already_claimed`     | This deposit's reward was already played                             | Nothing                                    |
| `expired`             | The time to claim has passed                                         | Nothing                                    |

Asking again about the same deposit returns the same reward, so it is safe to call again after a page refresh.

### 2. Show your button and play the game

The SDK does not draw a button. Build your own and fill it from `check.ui`. When the player clicks, pass the **same `check` object** to `Wynta.playDelight`:

```js
if (check.applicable) {
  const btn = document.querySelector('#delight-btn');
  btn.querySelector('.title').textContent = check.ui.title;
  btn.querySelector('.sub').textContent = check.ui.subtitle;
  btn.hidden = false;

  btn.onclick = async () => {
    btn.disabled = true;
    try {
      const result = await Wynta.playDelight(check);
      if (result) btn.hidden = true;     // played; null means the player closed it without playing
    } catch (e) {
      handleDelightError(e);             // see the error table below
    } finally {
      btn.disabled = false;
    }
  };
}
```

The SDK opens the game in an iframe over your page, shows it once loaded, closes it when the game ends, and shows a "You won" popup. You do not create the iframe or call any other API. It resolves with:

```js
{
  rewardId: 15,
  game: 'spin_wheel',      // 'spin_wheel' | 'flip_cards' | 'chest' | 'scratch_card'
  prize: { key: 'b1', label: '₹750 Bonus', type: 'bonus', amount: 750 },   // type: 'bonus' | 'loyalty_points'
  status: 'pending',       // 'pending' while the prize is being added, then 'credited'
  playedAt: '2026-11-05T10:15:00Z'
}
```

Optional second argument: `{ theme: { name, mode }, showReward: false, loadTimeoutMs }`. Use `showReward: false` to skip the SDK popup and show your own from `result.prize`.

#### Errors

`playDelight` rejects with a `DelightError`. Check `e.code`:

| code             | Meaning                                        | Suggested handling                            |
| ---------------- | ---------------------------------------------- | --------------------------------------------- |
| `not_applicable` | The `check` you passed has `applicable: false` | Don't call `playDelight` in that case         |
| `expired`        | The time to claim has passed                   | Hide the button                               |
| `already_played` | This reward is already open or played          | Hide the button                               |
| `load_timeout`   | The game page didn't load in time              | Show "Try again"                              |
| `delight_failed` | Any other failure                              | Show "Try again"; contact Wynta if it repeats |

`checkDelight` can reject with `PlayerNotAuthenticatedError` (call `init()` first), `PlayerAuthExpiredError` (the 15-minute token expired; sign in again with `Wynta.init()`) or `ApiError` (see its `status` and `code`).

### 3. How the prize is awarded

When the player taps, the server picks the prize and credits it to their account, as bonus cash or loyalty points. You make no call for this. `result.status` is `pending` at first and becomes `credited` within moments. If you show the player's balance, refresh it after the game closes.

### Complete example

```html
<button id="delight-btn" hidden><strong class="title"></strong> <span class="sub"></span></button>
<script src="https://<gamification-ui-host>/wynta-sdk.umd.js"></script>
<script>
  let ready;
  function initWynta() {
    ready ??= (async () => {
      const res = await fetch('/api/wynta-auth', { credentials: 'same-origin', cache: 'no-store' });
      const { client_id, payload, hash } = await res.json();
      await Wynta.init({
        clientId: client_id, payload, hash,
        authServiceUrl: 'https://<auth-service-host>',
        gamificationApiUrl: 'https://<gamification-api-host>',
      });
    })();
    return ready;
  }

  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

  // Call when your deposit is confirmed, and again when the player returns to the page.
  async function onDepositSuccess(depositId) {
    await initWynta();

    let check;
    for (let i = 0; i < 3; i++) {
      check = await Wynta.checkDelight({ transactionId: depositId });
      if (check.applicable || check.reason !== 'deposit_not_found') break;
      await sleep(2000);                     // the deposit may not be recorded yet
    }
    if (!check.applicable) return;

    const btn = document.querySelector('#delight-btn');
    btn.querySelector('.title').textContent = check.ui.title;
    btn.querySelector('.sub').textContent = check.ui.subtitle;
    btn.hidden = false;

    btn.onclick = async () => {
      btn.disabled = true;
      try {
        const result = await Wynta.playDelight(check, { theme: { name: 'stone', mode: 'dark' } });
        if (result) btn.hidden = true;
      } catch (e) {
        if (e.code === 'expired' || e.code === 'already_played') btn.hidden = true;
        else alert('Could not open the reward. Please try again.');
      } finally {
        btn.disabled = false;
      }
    };
  }
</script>
```

### Before you go live

* Call `checkDelight` only after the deposit is **confirmed**, and again when the player returns to the page. The same deposit returns the same reward until it is played or expires.
* Keep your button visible until `check.expiresAt`, or until the reward is played.
* Don't build the iframe yourself, and never decide or show a prize yourself. Only the server knows it.
* Test a matching deposit (the button appears and the prize is credited), a non-matching one (`no_matching_rule`), a repeat check of the same deposit (`already_claimed`), and closing the game before playing (`playDelight` resolves `null`, and the button reopens it).

### Troubleshooting

| Symptom                                           | Likely cause                                                                                                                                                                                                                              |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `init()` fails, for example `401 Invalid request` | The client is inactive or `client_id` / `client_secret` is wrong; the HMAC isn't over the exact Base64 string; the timestamp isn't Unix **seconds** or is outside the 60-second window; or the sign-in `transaction_id` was already used. |
| `checkDelight` always returns `deposit_not_found` | The deposit id doesn't match the one in the deposit event, or the event hasn't reached Wynta.                                                                                                                                             |
| `checkDelight` returns `no_prize_available`       | The rule has no fallback prize and every prize is sold out or over its share-of-deposit limit for this deposit amount. Ask Wynta to check the prize limits.                                                                               |
| Clicking the button does nothing                  | The game's domain is blocked by your CSP `frame-src`, or the game page isn't deployed.                                                                                                                                                    |
| `PlayerAuthExpiredError`                          | More than 15 minutes since `init()`. Sign in again.                                                                                                                                                                                       |
| The browser blocks a request (CORS)               | Ask Wynta to allow your site's domain.                                                                                                                                                                                                    |

To retry a failed sign-in, fetch a newly signed payload and call `init()` again. For anything else, send the Wynta team the `rewardId`, the time of the attempt and the error code.

###

###

###
