# UserID

## User ID Setup Guide

### Overview

When using the **UserID & Webhook** campaign type, your system must send a unique `userid` value to identify each game player. This userid is included in the webhook data sent back to your server after each game play.

***

### How It Works

1. Your website generates or retrieves a `userid` for the current user
2. Your website passes the `userid` to the game via URL parameter
3. The user plays the game
4. Our system sends the game result (including the `userid`) to your Webhook URL

```
Your Website                          Branded Mini-Games
    |                                        |
    |-- userid (via URL parameter) --------->|
    |                                        |  User plays the game
    |<-- Webhook POST (userid + result) -----|
```

***

### Passing the User ID

Add the `userid` parameter to the game URL when embedding it on your website:

```html
<iframe src="https://branded.mini-games.io/?php=landing@game&campaign_no=YOUR_CAMPAIGN_NO&userid=USER_ID_HERE"
        width="100%" height="600" frameborder="0">
</iframe>
```

***

### Option 1: Using Your Existing User System (Recommended)

If your website already has a sign-up/login system, use the existing user identifier.

**Examples:**

* Database user ID (e.g., `12345`)
* Username (e.g., `james`)
* Email address (e.g., `james@example.com`)
* Registration number or member ID

```jsx
// Example: Next.js / React
function GameEmbed({ campaignNo, userId }) {
  const gameUrl = `https://branded.mini-games.io/?php=landing@game&campaign_no=${campaignNo}&userid=${userId}`;

  return (
    <iframe src={gameUrl} width="100%" height="600" frameBorder="0" />
  );
}

// Usage
<GameEmbed campaignNo="43292" userId={session.user.id} />
```

```html
<!-- Example: HTML / JavaScript -->
<iframe id="game-frame" width="100%" height="600" frameborder="0"></iframe>
<script>
  const userId = getCurrentUser().id; // from your auth system
  document.getElementById('game-frame').src =
    `https://branded.mini-games.io/?php=landing@game&campaign_no=43292&userid=${userId}`;
</script>
```

**Advantages:**

* Reliable user tracking across devices and sessions
* Webhook data can be matched to your user database
* No duplicate users

***

### Option 2: Generate a Random ID (No Sign-up Required)

If your website does not have a user system, you can generate a unique ID and store it in the browser.

```javascript
// Generate or retrieve userid
let userid = localStorage.getItem('game_userid');
if (!userid) {
    userid = crypto.randomUUID();
    // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"
    localStorage.setItem('game_userid', userid);
}

// Set the game iframe URL
document.getElementById('game-frame').src =
    `https://branded.mini-games.io/?php=landing@game&campaign_no=43292&userid=${userid}`;
```

**Advantages:**

* No sign-up system needed
* Quick to implement
* Returning users keep the same ID

**Limitations:**

* If the user clears browser data or uses incognito mode, a new ID is generated
* Cannot track the same user across different devices or browsers
* Not suitable when accurate user identification is required

***

### Webhook Response Data

After each game play, the following data is sent to your Webhook URL via POST:

| Parameter  | Description                                 | Example                       |
| ---------- | ------------------------------------------- | ----------------------------- |
| `userid`   | Unique user identifier sent by your system  | `james` or `f47ac10b-58cc...` |
| `tx_id`    | Unique transaction ID for each game play    | `234234`                      |
| `time`     | Date and time when the user played the game | `2025-04-10 06:39:23`         |
| `score`    | Score the user achieved                     | `3500`                        |
| `playtime` | Play duration in seconds                    | `20`                          |

#### Return Code

Your server must return one of the following codes after receiving the webhook:

| Code | Description                                                     |
| ---- | --------------------------------------------------------------- |
| `S`  | Success                                                         |
| `F`  | Failure. You may include a reason, e.g., `F: Score is missing.` |

***

### Which Option Should I Choose?

|                           | Option 1: Existing User System                      | Option 2: Random ID                     |
| ------------------------- | --------------------------------------------------- | --------------------------------------- |
| **Best for**              | Loyalty programs, rewards, personalized experiences | Promotions, contests, casual engagement |
| **User tracking**         | Accurate, cross-device                              | Browser-only, may create duplicates     |
| **Implementation**        | Requires existing auth system                       | Simple, no backend needed               |
| **Webhook data matching** | Can match to your user database                     | Limited to browser session              |

***

### Integration with WordPress

If your website runs on WordPress, you can automatically pass the logged-in user's ID to the game iframe using plugins.

#### Recommended Plugins

| Plugin                                                                                                         | Description                                                                 |
| -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| [Advanced iFrame](https://wordpress.org/plugins/advanced-iframe/)                                              | Supports `url_forward_parameter` to forward URL parameters to the iframe    |
| [Pass URL Parameters to Embedded iFrame](https://wordpress.org/plugins/pass-url-parameters-to-embeded-iframe/) | Automatically appends URL parameters to any iframe with `id="rwcGetParams"` |

#### Example: Passing WordPress User ID

Add this to your theme's `functions.php` to create a shortcode that outputs the game iframe with the current user's ID:

```php
function bmg_game_iframe($atts) {
    $atts = shortcode_atts(['campaign_no' => ''], $atts);
    $user_id = get_current_user_id();
    if (!$user_id) return '<p>Please log in to play.</p>';

    $url = 'https://branded.mini-games.io/?php=landing@game'
         . '&campaign_no=' . esc_attr($atts['campaign_no'])
         . '&userid=' . $user_id;

    return '<iframe src="' . esc_url($url) . '" width="100%" height="600" frameborder="0"></iframe>';
}
add_shortcode('bmg_game', 'bmg_game_iframe');
```

Then use the shortcode in any page or post:

```
[bmg_game campaign_no="43292"]
```

***

### Integration with Auth Services (No Existing User System)

If your website does not have a user system, you can use a third-party authentication service to add signup/login and obtain a user ID.

#### Recommended Services

| Service                                                    | Features                                                            | Free Tier        |
| ---------------------------------------------------------- | ------------------------------------------------------------------- | ---------------- |
| [Clerk](https://clerk.com/)                                | Embeddable signup/login components, social login, instant `user.id` | Up to 10,000 MAU |
| [Firebase Auth](https://firebase.google.com/products/auth) | Google/social login widget, `uid` per user, JS SDK                  | Unlimited free   |
| [Supabase Auth](https://supabase.com/auth)                 | Open-source, email/social/magic link login, `user.id` via JS SDK    | 50,000 MAU free  |
| [Auth0](https://auth0.com/)                                | Universal Login widget, social login, Management API                | Up to 25,000 MAU |

#### Example: Firebase Auth

```html
<script src="https://www.gstatic.com/firebasejs/11.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/11.0/firebase-auth-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/ui/7.0/firebase-ui-auth.js"></script>
<link rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/7.0/firebase-ui-auth.css">

<div id="firebaseui-auth-container"></div>
<iframe id="game-frame" width="100%" height="600" frameborder="0" style="display:none"></iframe>

<script>
  firebase.initializeApp({ /* your Firebase config */ });

  const ui = new firebaseui.auth.AuthUI(firebase.auth());
  ui.start('#firebaseui-auth-container', {
    signInOptions: [
      firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      firebase.auth.EmailAuthProvider.PROVIDER_ID
    ],
    callbacks: {
      signInSuccessWithAuthResult: function(authResult) {
        const uid = authResult.user.uid;
        const frame = document.getElementById('game-frame');
        frame.src = `https://branded.mini-games.io/?php=landing@game&campaign_no=43292&userid=${uid}`;
        frame.style.display = 'block';
        return false;
      }
    }
  });
</script>
```

#### Example: Supabase Auth

```html
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>

<div id="auth-section">
  <input type="email" id="email" placeholder="Email">
  <input type="password" id="password" placeholder="Password">
  <button onclick="signUp()">Sign Up</button>
  <button onclick="signIn()">Sign In</button>
</div>
<iframe id="game-frame" width="100%" height="600" frameborder="0" style="display:none"></iframe>

<script>
  const supabase = supabase.createClient('YOUR_SUPABASE_URL', 'YOUR_ANON_KEY');

  async function signUp() {
    const { data } = await supabase.auth.signUp({
      email: document.getElementById('email').value,
      password: document.getElementById('password').value
    });
    if (data.user) loadGame(data.user.id);
  }

  async function signIn() {
    const { data } = await supabase.auth.signInWithPassword({
      email: document.getElementById('email').value,
      password: document.getElementById('password').value
    });
    if (data.user) loadGame(data.user.id);
  }

  function loadGame(userId) {
    document.getElementById('auth-section').style.display = 'none';
    const frame = document.getElementById('game-frame');
    frame.src = `https://branded.mini-games.io/?php=landing@game&campaign_no=43292&userid=${userId}`;
    frame.style.display = 'block';
  }
</script>
```

#### Which Service Should I Choose?

|                   | Clerk                | Firebase Auth          | Supabase Auth                  | Auth0                 |
| ----------------- | -------------------- | ---------------------- | ------------------------------ | --------------------- |
| **Easiest setup** | Best                 | Good                   | Good                           | Moderate              |
| **Pre-built UI**  | Yes (React, JS)      | Yes (FirebaseUI)       | No (build your own)            | Yes (Universal Login) |
| **Social login**  | Google, GitHub, etc. | Google, Facebook, etc. | Google, GitHub, etc.           | 60+ providers         |
| **Best for**      | React/Next.js sites  | Any website            | Developers wanting open-source | Enterprise needs      |
