{
  "info": {
    "_postman_id": "6f0b3c52-2d7e-4c1a-9a51-3c8e5d1f7a20",
    "name": "1xHuay Scratcher - Merchant API",
    "description": "Merchant integration for 1xHuay Scratcher (seamless wallet). Full guide: /docs/integration on the merchant portal.\n\nImport this collection and one environment: **Sandbox** while you build and test, **Live** for production. Fill `api_key`, `callback_url` and `callback_secret` (portal > Integration) in the environment.\n\n- Folder 1 calls our Merchant API with your key.\n- Folder 2 sends our signed wallet callbacks to your callback URL, to test your wallet.",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "1. Your calls to us",
      "description": "Calls your server makes to the Merchant API. Sent with `Authorization: Bearer {{api_key}}` to `{{base_url}}`. See \"Your calls to us\" in the guide.",
      "auth": {
        "type": "bearer",
        "bearer": [
          {
            "key": "token",
            "value": "{{api_key}}",
            "type": "string"
          }
        ]
      },
      "item": [
        {
          "name": "Connection test",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('HTTP 200: both directions work', () => pm.response.to.have.status(200))",
                  "const body = pm.response.json()",
                  "pm.test('status OK', () => pm.expect(body.status).to.eql('OK'))",
                  "if (body.status !== 'OK') console.log('Connection test failed:', body.message)"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [],
            "url": "{{base_url}}/v1/connection-test",
            "description": "Sends a signed `connectionTest` to your callback URL and answers 200 when your server answered. 502 `CALLBACK_FAILED` says why it did not (`message`)."
          }
        },
        {
          "name": "List products",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('HTTP 200', () => pm.response.to.have.status(200))",
                  "const products = pm.response.json()",
                  "pm.test('an array of lots on sale', () => pm.expect(products).to.be.an('array'))",
                  "// Fill game_code / bet_amount for the wallet simulator from the first lot on sale.",
                  "const lot = Array.isArray(products) ? products.find(p => !p.soldOut) : null",
                  "if (lot && !pm.environment.get('game_code')) {",
                  "  pm.environment.set('game_code', lot.code)",
                  "  pm.environment.set('bet_amount', String(lot.price))",
                  "}",
                  "if (!lot) console.log('No lot on sale: put one on sale in the portal (Lots) before playing.')"
                ]
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [],
            "url": "{{base_url}}/v1/products",
            "description": "Your lots on sale. Optional: only needed to show our games in your own lobby."
          }
        },
        {
          "name": "Create session (launch a player)",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test('HTTP 200', () => pm.response.to.have.status(200))",
                  "const body = pm.response.json()",
                  "pm.test('launchUrl returned', () => pm.expect(body.launchUrl).to.be.a('string'))",
                  "if (body.launchUrl) {",
                  "  pm.environment.set('launch_url', body.launchUrl)",
                  "  console.log('Open within 120 seconds, once:', body.launchUrl)",
                  "}"
                ]
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"player\": {\n    \"id\": \"{{player_id}}\",\n    \"currency\": \"{{currency}}\",\n    \"lang\": \"th\",\n    \"displayName\": \"tester\"\n  },\n  \"returnUrl\": \"https://example.com/\"\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{base_url}}/v1/sessions",
            "description": "Answers `launchUrl`: redirect the player's browser to it at once. It works once, within 120 seconds; ask for a new one for every entry. Opening it sends `checkBalance` to your callback URL."
          }
        }
      ]
    },
    {
      "name": "2. Wallet simulator (our calls to you)",
      "description": "Sends the wallet callbacks Scratcher sends, signed with `{{callback_secret}}`, to `{{callback_url}}`, so you can build and test your wallet endpoint before (or without) playing a real game.\n\nRun them in order: placeBets starts a new ticket (`txn_id`, `ticket_id`), the later requests reuse it.\n\n**These move money in your wallet** for `{{player_id}}`. Point `callback_url` at a test wallet and a test player, never at real players.",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "// Builds and signs the request exactly as Scratcher signs its wallet callbacks:",
              "// X-Scratcher-Signature = hex HMAC-SHA256 of \"<timestamp>.<body>\" with callback_secret.",
              "const cryptoJs = require('crypto-js')",
              "const secret = pm.variables.get('callback_secret')",
              "if (!secret) throw new Error('Set callback_secret in the environment (portal > Integration > Callback secret > Reset).')",
              "",
              "let raw = pm.request.body.raw",
              "// {{new_txn_id}} / {{new_ticket_id}} start a new ticket; later requests reuse {{txn_id}} / {{ticket_id}}.",
              "if (raw.includes('{{new_txn_id}}')) {",
              "  pm.environment.set('txn_id', pm.variables.replaceIn('{{$guid}}'))",
              "  raw = raw.split('{{new_txn_id}}').join('{{txn_id}}')",
              "}",
              "if (raw.includes('{{new_ticket_id}}')) {",
              "  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'",
              "  let serial = ''",
              "  for (let i = 0; i < 16; i++) serial += chars[Math.floor(Math.random() * chars.length)]",
              "  pm.environment.set('ticket_id', (pm.variables.get('game_code') || 'TEST') + '-' + serial)",
              "  raw = raw.split('{{new_ticket_id}}').join('{{ticket_id}}')",
              "}",
              "",
              "const timestamp = Math.floor(Date.now() / 1000)",
              "const body = JSON.parse(pm.variables.replaceIn(raw))",
              "if ('timestamp' in body) body.timestamp = timestamp",
              "const compact = JSON.stringify(body)",
              "pm.request.body.update(compact)",
              "pm.request.headers.upsert({ key: 'X-Scratcher-Timestamp', value: String(timestamp) })",
              "pm.request.headers.upsert({",
              "  key: 'X-Scratcher-Signature',",
              "  value: cryptoJs.HmacSHA256(timestamp + '.' + compact, secret).toString(cryptoJs.enc.Hex)",
              "})",
              "pm.variables.set('sim_event', body.event || 'query')"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "// Every answer must be HTTP 200 with a JSON status (guide: \"Your answer\").",
              "const event = pm.variables.get('sim_event')",
              "const allowed = {",
              "  connectionTest: ['ok', 'user_not_found', 'user_suspended', 'insufficient_balance', 'duplicate'],",
              "  checkBalance: ['ok', 'user_not_found', 'user_suspended', 'invalid', 'error'],",
              "  placeBets: ['ok', 'duplicate', 'insufficient_balance', 'user_not_found', 'user_suspended', 'invalid', 'error'],",
              "  settleBets: ['ok', 'duplicate', 'user_not_found', 'user_suspended', 'invalid', 'error'],",
              "  cancelBets: ['ok', 'duplicate', 'user_not_found', 'user_suspended', 'invalid', 'error'],",
              "  voidSettled: ['ok', 'duplicate', 'insufficient_balance', 'user_not_found', 'user_suspended', 'invalid', 'error'],",
              "  query: ['ok', 'error']",
              "}[event] || []",
              "pm.test('HTTP 200 (a refusal is a status, never an HTTP error)', () => pm.response.to.have.status(200))",
              "let body = {}",
              "pm.test('JSON body', () => { body = pm.response.json() })",
              "pm.test('status is one of: ' + allowed.join(', '), () => pm.expect(allowed).to.include(body.status))",
              "if (event === 'checkBalance' && body.status === 'ok') {",
              "  pm.test('balance is a number', () => pm.expect(Number.isFinite(Number(body.balance))).to.be.true)",
              "}",
              "if (event === 'query' && body.status === 'ok') {",
              "  pm.test('placed is a boolean', () => pm.expect(body.placed).to.be.a('boolean'))",
              "}",
              "if (body.balance !== undefined) console.log(event, '->', body.status, 'balance', body.balance)"
            ]
          }
        }
      ],
      "item": [
        {
          "name": "connectionTest",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"connectionTest\",\n  \"provider\": \"scratcher\",\n  \"player\": \"00000000-0000-0000-0000-000000000000\",\n  \"currency\": \"\",\n  \"reference\": \"conn_{{$guid}}\",\n  \"txns\": [],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "Sent by Test connection. No money moves; any status except `invalid` / `error` counts as connected."
          }
        },
        {
          "name": "checkBalance",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"checkBalance\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"bal_{{$guid}}\",\n  \"txns\": [],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "Sent at login and when the game refreshes the balance. Answer `{\"status\":\"ok\",\"balance\":<number>}`."
          }
        },
        {
          "name": "placeBets (new ticket)",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"placeBets\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"pur_{{$guid}}\",\n  \"txns\": [\n    {\n      \"id\": \"{{new_txn_id}}\",\n      \"ticketId\": \"{{new_ticket_id}}\",\n      \"betAmount\": {{bet_amount}},\n      \"gameCode\": \"{{game_code}}\"\n    }\n  ],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "The player buys a ticket: take `betAmount`. Answer `insufficient_balance` when short. Starts a new `txn_id` / `ticket_id`."
          }
        },
        {
          "name": "placeBets (retry, same txn id)",
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json()",
                  "pm.test('a repeat answers duplicate or ok without moving money', () => pm.expect(['duplicate', 'ok']).to.include(body.status))"
                ]
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"placeBets\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"pur_{{$guid}}\",\n  \"txns\": [\n    {\n      \"id\": \"{{txn_id}}\",\n      \"ticketId\": \"{{ticket_id}}\",\n      \"betAmount\": {{bet_amount}},\n      \"gameCode\": \"{{game_code}}\"\n    }\n  ],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "The same placeBets again, as after a lost answer. You must not take the stake twice: answer `duplicate` (or `ok`)."
          }
        },
        {
          "name": "settleBets (winning ticket)",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"settleBets\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"{{ticket_id}}\",\n  \"txns\": [\n    {\n      \"id\": \"{{txn_id}}\",\n      \"ticketId\": \"{{ticket_id}}\",\n      \"payoutAmount\": {{payout_amount}},\n      \"gameCode\": \"{{game_code}}\"\n    }\n  ],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "The player opens a winning ticket: pay `payoutAmount`. Same `id` as its placeBets."
          }
        },
        {
          "name": "voidSettled (admin cancel, prize paid)",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"voidSettled\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"cancel_{{$guid}}\",\n  \"txns\": [\n    {\n      \"id\": \"{{txn_id}}\",\n      \"ticketId\": \"{{ticket_id}}\",\n      \"betAmount\": {{bet_amount}},\n      \"payoutAmount\": {{payout_amount}},\n      \"gameCode\": \"{{game_code}}\"\n    }\n  ],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "Our admin cancels a ticket whose prize was paid: take back `payoutAmount - betAmount`."
          }
        },
        {
          "name": "placeBets (second ticket, for cancelBets)",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"placeBets\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"pur_{{$guid}}\",\n  \"txns\": [\n    {\n      \"id\": \"{{new_txn_id}}\",\n      \"ticketId\": \"{{new_ticket_id}}\",\n      \"betAmount\": {{bet_amount}},\n      \"gameCode\": \"{{game_code}}\"\n    }\n  ],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "A new ticket that is never settled, so cancelBets has a stake to give back."
          }
        },
        {
          "name": "cancelBets (admin cancel, no prize paid)",
          "event": [],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"cancelBets\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"cancel_{{$guid}}\",\n  \"txns\": [\n    {\n      \"id\": \"{{txn_id}}\",\n      \"ticketId\": \"{{ticket_id}}\",\n      \"betAmount\": {{bet_amount}},\n      \"gameCode\": \"{{game_code}}\"\n    }\n  ],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "Our admin cancels a ticket that paid no prize (the second ticket): give back the stake you took with its placeBets."
          }
        },
        {
          "name": "Reconcile query",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "// The query URL is the callback URL with its last \"callback\" path segment replaced by \"query\".",
                  "// (The script sandbox has no URL class, so split off the path by hand.)",
                  "const callbackUrl = pm.variables.replaceIn('{{callback_url}}')",
                  "const hostEnd = callbackUrl.indexOf('/', callbackUrl.indexOf('://') + 3)",
                  "const tailAt = callbackUrl.search(/[?#]/)",
                  "const origin = hostEnd < 0 ? callbackUrl : callbackUrl.slice(0, hostEnd)",
                  "const path = hostEnd < 0 ? '' : callbackUrl.slice(hostEnd, tailAt < 0 ? undefined : tailAt)",
                  "const rest = tailAt < 0 ? '' : callbackUrl.slice(tailAt)",
                  "const parts = (path || '').split('/')",
                  "const index = parts.lastIndexOf('callback')",
                  "if (index < 0) throw new Error('callback_url has no /callback path segment, so Scratcher has no query URL for it')",
                  "parts[index] = 'query'",
                  "pm.request.url.update(origin + parts.join('/') + rest)"
                ]
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"providerTxnId\": \"{{txn_id}}\"\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "Sent when a placeBets got no usable answer. Answer `{\"status\":\"ok\",\"placed\":true|false}` for that `providerTxnId`. Goes to the query URL (`/callback` replaced by `/query`)."
          }
        },
        {
          "name": "Bad signature (must be refused)",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "// Runs after the folder script signed the request: replace the signature with a wrong one.",
                  "pm.request.headers.upsert({ key: 'X-Scratcher-Signature', value: '0'.repeat(64) })"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json()",
                  "pm.test('a bad signature is answered invalid', () => pm.expect(body.status).to.eql('invalid'))"
                ]
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"event\": \"checkBalance\",\n  \"provider\": \"scratcher\",\n  \"player\": \"{{player_id}}\",\n  \"currency\": \"{{currency}}\",\n  \"reference\": \"bal_{{$guid}}\",\n  \"txns\": [],\n  \"timestamp\": 0\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": "{{callback_url}}",
            "description": "A callback with a wrong signature. Your server must refuse it: `{\"status\":\"invalid\",\"message\":\"bad signature\"}`, and move no money."
          }
        }
      ]
    }
  ]
}
