# Testing

> Test your integration in the sandbox with test cards, the simulator and webhook tests, before you go live.

Source: https://docs.tappay.mn/testing/

## Sandbox {#sandbox}

The [sandbox](https://docs.tappay.mn/glossary.md#sandbox) is a separate environment with its own keys. You get a sandbox key after you sign in, as shown in [Get started](https://docs.tappay.mn/get-started.md). Each [production](https://docs.tappay.mn/glossary.md#production) merchant has one sandbox merchant, which the merchant team shares. TapPay deletes a sandbox that you do not use for 90 days. Sandbox keys start with `sk_test_` and `pk_test_`.

The sandbox has no ledger, no netting and no [payouts](https://docs.tappay.mn/glossary.md#payout). Webhooks are sent for real, so you can test your endpoint. A sandbox merchant cannot reach any [production](https://docs.tappay.mn/glossary.md#production) data.

Some operations do not work in the sandbox. The table shows what they return.

| Operation | Result | Concept |
| - | - | - |
| `integration.payouts.create` | `403` [EVT-201](https://docs.tappay.mn/errors.md#EVT-201) | Merchant API §4: no payouts in the sandbox |
| `integration.payouts.get` | `403` [EVT-201](https://docs.tappay.mn/errors.md#EVT-201) | Merchant API §4: no payouts in the sandbox |
| `integration.payouts.list` | `403` [EVT-201](https://docs.tappay.mn/errors.md#EVT-201) | Merchant API §4: no payouts in the sandbox |

A [report](https://docs.tappay.mn/glossary.md#report) of type `SETTLEMENT`, `PAYOUT` or `LEDGER` is accepted with `202`, but the sandbox has no such data, so the report has no real rows.

## Test cards {#test-cards}

The sandbox [simulator](https://docs.tappay.mn/glossary.md#simulator) knows only the card numbers below. Any other number is rejected with `422` [EVT-202](https://docs.tappay.mn/errors.md#EVT-202). Never use a real card number in the sandbox.

| Card number | Outcome | Failure code |
| - | - | - |
| `4242 4242 4242 4242` | Succeeded | |
| `4000 0000 0000 0002` | Declined | `CARD_DECLINED` · Card declined |
| `4000 0000 0000 9995` | Declined | `INSUFFICIENT_FUNDS` · Insufficient funds |
| `4000 0000 0000 0069` | Declined | `EXPIRED_CARD` · Expired card |
| `4000 0000 0000 0119` | Timeout (payment stays PROCESSING) | |

## Simulator {#simulator}

The [simulator](https://docs.tappay.mn/glossary.md#simulator) acts as the [customer](https://docs.tappay.mn/glossary.md#customer), the bank and the card network. It is available only with a sandbox key. The example below runs a complete [payment](https://docs.tappay.mn/glossary.md#payment): create an [invoice](https://docs.tappay.mn/glossary.md#invoice), show its QR, let the customer time out, and then settle the payment.

First create an invoice. The response has the `invoiceId` and the `intentId` that the next steps use.

```bash title="curl"
curl -sS -X POST "https://api.tappay.mn/api/v1/invoices" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{"terminalId":"YOUR_TERMINAL_ID","amount":1000,"description":"Order 1","orderId":"order-'"$(uuidgen)"'"}'
```

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const invoice = await tappay.invoices.create({
  body: {
    terminalId: 'YOUR_TERMINAL_ID',
    amount: 1000,
    description: 'Order 1',
    orderId: `order-${crypto.randomUUID()}`,
  },
});
console.log(JSON.stringify(invoice));
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$invoice = $tappay->invoices->create([
    'body' => [
        'terminalId' => 'YOUR_TERMINAL_ID',
        'amount' => 1000,
        'description' => 'Order 1',
        'orderId' => 'order-' . vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)) . '',
    ],
]);
echo json_encode($invoice);
```

```python title="Python"
import json
import uuid
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
invoice = client.invoices.create({
    "body": {
        "terminalId": "YOUR_TERMINAL_ID",
        "amount": 1000,
        "description": "Order 1",
        "orderId": "order-" + str(uuid.uuid4()) + "",
    },
})
print(json.dumps(invoice))
```

Show the [payment intent](https://docs.tappay.mn/glossary.md#payment-intent) as a QR code with the `present` operation, which creates a [presentation](https://docs.tappay.mn/glossary.md#presentation) for the [channel](https://docs.tappay.mn/glossary.md#channel).

```bash title="curl"
curl -sS -X POST "https://api.tappay.mn/api/v1/intents/INTENT_ID/present" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{"channel":"NODE_QR"}'
```

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const intent = await tappay.intents.present({ id: 'INTENT_ID', body: { channel: 'NODE_QR' } });
console.log(JSON.stringify(intent));
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$intent = $tappay->intents->present(['id' => 'INTENT_ID', 'body' => ['channel' => 'NODE_QR']]);
echo json_encode($intent);
```

```python title="Python"
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
intent = client.intents.present({"id": "INTENT_ID", "body": {"channel": "NODE_QR"}})
print(json.dumps(intent))
```

Now act as the customer. `integration.v1.simulateIntent` takes `channel: 'QR'` with an `outcome` of `SUCCEEDED`, `DECLINED` or `TIMEOUT`, or `channel: 'CARD'` with one of the [test cards](https://docs.tappay.mn/glossary.md#test-card). A `TIMEOUT` leaves the payment in `PROCESSING`.

```bash title="curl"
curl -sS -X POST "https://api.tappay.mn/api/v1/sandbox/intents/INTENT_ID/simulate" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{"channel":"QR","outcome":"TIMEOUT"}'
```

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const result = await tappay.sandbox.simulateIntent({ id: 'INTENT_ID', body: { channel: 'QR', outcome: 'TIMEOUT' } });
console.log(JSON.stringify(result));
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$result = $tappay->sandbox->simulateIntent(['id' => 'INTENT_ID', 'body' => ['channel' => 'QR', 'outcome' => 'TIMEOUT']]);
echo json_encode($result);
```

```python title="Python"
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
result = client.sandbox.simulate_intent({"id": "INTENT_ID", "body": {"channel": "QR", "outcome": "TIMEOUT"}})
print(json.dumps(result))
```

A `PROCESSING` payment can be completed by hand. `integration.v1.simulatePayment` takes `outcome` `SUCCEEDED` or `FAILED`. For a payment in any other status it returns `409` [EVT-204](https://docs.tappay.mn/errors.md#EVT-204).

```bash title="curl"
curl -sS -X POST "https://api.tappay.mn/api/v1/sandbox/payments/PAYMENT_ID/simulate" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{"outcome":"SUCCEEDED"}'
```

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const result = await tappay.sandbox.simulatePayment({ id: 'PAYMENT_ID', body: { outcome: 'SUCCEEDED' } });
console.log(JSON.stringify(result));
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$result = $tappay->sandbox->simulatePayment(['id' => 'PAYMENT_ID', 'body' => ['outcome' => 'SUCCEEDED']]);
echo json_encode($result);
```

```python title="Python"
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
result = client.sandbox.simulate_payment({"id": "PAYMENT_ID", "body": {"outcome": "SUCCEEDED"}})
print(json.dumps(result))
```

Other simulator operations cover the rest of the payment flow.

- `integration.v1.autoFinalizePayment` [finalizes](https://docs.tappay.mn/glossary.md#finalize) a [pre-auth](https://docs.tappay.mn/glossary.md#pre-auth) payment as if its finalize time had passed.
- `integration.v1.simulateEbarimt` sets the result of the tax [receipt](https://docs.tappay.mn/glossary.md#receipt), for example `REGISTERED`, `FAILED` or `MERCHANT_TIMEOUT`.
- `public.checkout.simulateEmbeddedSession` completes an embedded [checkout session](https://docs.tappay.mn/glossary.md#checkout-session) with a test card.

### Other sandbox flows {#other-flows}

These flows run in the sandbox with the same [secret key](https://docs.tappay.mn/glossary.md#secret-key). Each one needs a prior setup step noted below.

- Saving a [payment method](https://docs.tappay.mn/glossary.md#payment-method): create a [customer](https://docs.tappay.mn/glossary.md#customer), then a checkout session with `mode` `SETUP` and an embedded UI. Complete it with `public.checkout.simulateEmbeddedSession` and a test card. The payment method becomes `ACTIVE`.
- Direct [MIT](https://docs.tappay.mn/glossary.md#mit) charge: call `integration.v1.createPayment` with `customer` and `paymentMethod`. An amount above the MIT limit returns `RCR-055`. Your partner must enable MIT and set its limits first.
- [Pre-auth](https://docs.tappay.mn/glossary.md#pre-auth): create an invoice with `authorizationType` `PREAUTH`. Call `integration.v1.simulateIntent` with a test card and `preauthMode` `HOLD`. Then call `integration.v1.finalizePayment`. Your partner must enable pre-auth first.
- [CPM](https://docs.tappay.mn/glossary.md#cpm): send one of the test payloads below to `integration.cpm.create`. The result is fixed by the payload.

| Outcome | Payload |
| - | - |
| Payment succeeds | `hQVDUFYwMWEjTwfwVEFQUEFZUAZUQVBQQVljEN8BDU5LMDAwMDJUOVI2SDU=` |
| Payment fails (payment.failed) | `hQVDUFYwMWEjTwfwVEFQUEFZUAZUQVBQQVljEN8BDU5LMDAwMDJUOVI2SjY=` |

## Webhook testing {#webhook-testing}

Every simulated payment sends real [events](https://docs.tappay.mn/glossary.md#event) to your [webhook endpoint](https://docs.tappay.mn/glossary.md#webhook-endpoint). Make a payment with the simulator, wait for the [event](https://docs.tappay.mn/glossary.md#event) to arrive at your server, and check it as in the [webhook guide](https://docs.tappay.mn/guides/webhooks.md).

No server yet? Every sandbox merchant has a hosted webhook inbox that checks [signatures](https://docs.tappay.mn/glossary.md#signature) for you. See the [webhook inbox](https://docs.tappay.mn/playground.md#webhook-inbox), and send requests from the docs with [Try it](https://docs.tappay.mn/playground.md#try-it).

Read what TapPay stored with `integration.v1.listEvents`. Every event shows its `deliveryStatus`, so you can see which ones your server missed.

```bash title="curl"
curl -sS "https://api.tappay.mn/api/v1/events?limit=10" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27"
```

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const page = await tappay.events.list({ query: { limit: '10' } }).firstPage();
console.log(JSON.stringify(page));
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$page = $tappay->events->list(['query' => ['limit' => '10']])->firstPage();
echo json_encode(['data' => $page->data, 'hasMore' => $page->hasMore, 'nextCursor' => $page->nextCursor]);
```

```python title="Python"
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
page = client.events.list({"limit": "10"}).first_page()
print(json.dumps({"data": page.data, "has_more": page.has_more, "next_cursor": page.next_cursor}))
```

Send an event again with `integration.v1.resendEvent`. Pass an `endpointId` to send it only to one endpoint. Your server must handle a repeated event, so remember the event `id`.

```bash title="curl"
curl -sS -X POST "https://api.tappay.mn/api/v1/events/EVENT_ID/resend" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{}'
```

```js title="Node.js"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const event = await tappay.events.resend({ id: 'EVENT_ID', body: {} });
console.log(JSON.stringify(event));
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$event = $tappay->events->resend(['id' => 'EVENT_ID', 'body' => new stdClass()]);
echo json_encode($event);
```

```python title="Python"
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
event = client.events.resend({"id": "EVENT_ID", "body": {}})
print(json.dumps(event))
```

Always verify the [signature](https://docs.tappay.mn/glossary.md#signature) over the raw body, as shown below. The test reads the input from standard input and prints `valid` or `invalid`.

```bash title="curl"
# Standard tools only: sed/grep read the input, openssl signs (it takes the secret as an argument, so use it for a demo, not on a shared host).
verify_webhook() { # raw_body timestamp nonce signatures secret path
  local body_hash canonical expected now sig result=invalid
  body_hash=$(printf '%s' "$1" | openssl dgst -sha256 -hex | awk '{print $NF}')
  canonical=$(printf 'POST\n%s\n%s\n%s\n%s' "$6" "$2" "$3" "$body_hash")
  expected="v1=$(printf '%s' "$canonical" | openssl dgst -sha256 -hmac "$5" -binary | openssl base64 -A)"
  now=$(date +%s)
  if [ $(( now > $2 ? now - $2 : $2 - now )) -le 300 ]; then
    for sig in $(printf '%s' "$4" | tr ',' ' '); do
      [ "$sig" = "$expected" ] && result=valid
    done
  fi
  echo "$result"
}

input=$(cat)
pick() { printf '%s' "$input" | sed -E "s/.*\"$1\":\"(([^\"\\\\]|\\\\.)*)\".*/\1/"; }
raw_body=$(pick rawBody | sed -e 's/\\"/"/g' -e 's/\\\\/\\/g')
verify_webhook "$raw_body" "$(pick TapPay-Timestamp)" "$(pick TapPay-Nonce)" "$(pick TapPay-Signature)" "$TAPPAY_WEBHOOK_SECRET" "$(pick path)"
```

```js title="Node.js"
import { readFileSync } from 'node:fs';
import { TapPay, SignatureVerificationError } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
// rawBody must be the exact bytes you received, before any JSON parsing.
const { rawBody, headers, path } = JSON.parse(readFileSync(0, 'utf8'));
try {
  // During a rotation pass both secrets: the new one and the previous one.
  const secrets = [process.env.TAPPAY_WEBHOOK_SECRET, process.env.TAPPAY_WEBHOOK_SECRET_PREVIOUS].filter(Boolean);
  const event = tappay.webhooks.constructEvent(rawBody, headers, { secrets, path });
  console.log(event.id ? 'valid' : 'invalid');
} catch (e) {
  if (!(e instanceof SignatureVerificationError)) throw e;
  console.log('invalid');
}
```

```php title="PHP"
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;
use TapPay\Exception\SignatureVerificationError;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
// rawBody must be the exact bytes you received (file_get_contents('php://input')), before any JSON decoding.
$in = json_decode(file_get_contents('php://stdin'), true);
try {
    // During a rotation pass both secrets: the new one and the previous one.
    $secrets = array_values(array_filter([getenv('TAPPAY_WEBHOOK_SECRET'), getenv('TAPPAY_WEBHOOK_SECRET_PREVIOUS')]));
    $event = $tappay->webhooks->constructEvent($in['rawBody'], $in['headers'], ['secrets' => $secrets, 'path' => $in['path']]);
    echo $event->id ? 'valid' : 'invalid';
} catch (SignatureVerificationError $e) {
    echo 'invalid';
}
```

```python title="Python"
import json
import os
import sys
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
# raw_body must be the exact bytes you received, before any JSON parsing.
data = json.load(sys.stdin)
# During a rotation pass both secrets: the new one and the previous one.
secrets = [s for s in (os.environ.get("TAPPAY_WEBHOOK_SECRET"), os.environ.get("TAPPAY_WEBHOOK_SECRET_PREVIOUS")) if s]
try:
    event = client.webhooks.construct_event(data["rawBody"], data["headers"], secrets=secrets, path=data["path"])
    print("valid" if event.id else "invalid")
except tappay.SignatureVerificationError:
    print("invalid")
```
