SandboxPay API

A single-file hosted payment gateway for testing end-to-end payment flows. No real money, no credentials — just drop in the file and start integrating.

v1.0 REST / JSON https://apps.devnexi.com/sandbox/api

Quick Start

Three steps to accept your first test payment:

# Step 1 – Create a payment session
curl -s -X POST 'https://apps.devnexi.com/sandbox/api?action=initiate' \
  -H 'Content-Type: application/json' \
  -d '{
    "amount": 50.00,
    "currency": "USD",
    "reference": "ORD-001",
    "return_url": "https://yourapp.com/success",
    "callback_url": "https://yourapp.com/webhook",
    "merchant_name": "My Store"
  }'

# Response → { "success": true, "payment_url": "...", "session_id": "SPY-..." }
# Step 2 – Redirect customer to payment_url

# Step 3 – Verify after redirect
curl -s 'https://apps.devnexi.com/sandbox/api?action=verify&session_id=SPY-xxxx'
<?php
$r = json_decode(file_get_contents('https://apps.devnexi.com/sandbox/api?action=initiate', false,
    stream_context_create(['http' => [
        'method'  => 'POST',
        'header'  => 'Content-Type: application/json',
        'content' => json_encode([
            'amount'        => 50.00,
            'currency'      => 'USD',
            'reference'     => 'ORD-001',
            'return_url'    => 'https://yourapp.com/success',
            'callback_url'  => 'https://yourapp.com/webhook',
            'merchant_name' => 'My Store',
        ]),
    ]])
), true);

if ($r['success']) {
    header('Location: ' . $r['payment_url']);   // redirect customer
    exit;
}

// On return_url page — verify:
$v = json_decode(file_get_contents(
    'https://apps.devnexi.com/sandbox/api?action=verify&session_id=' . urlencode($_GET['session_id'] ?? '')
), true);

if ($v['status'] === 'success') { /* fulfil order */ }
// Step 1 – Initiate
const res = await fetch('https://apps.devnexi.com/sandbox/api?action=initiate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    amount: 50.00, currency: 'USD', reference: 'ORD-001',
    return_url: location.origin + '/success',
    merchant_name: 'My Store',
  }),
});
const data = await res.json();
if (data.success) window.location.href = data.payment_url;

// Step 3 – Verify on success page
const params = new URLSearchParams(location.search);
const v = await fetch(`https://apps.devnexi.com/sandbox/api?action=verify&session_id=${params.get('session_id')}`).then(r=>r.json());
if (v.status === 'success') console.log('Paid:', v.transaction_id);

Payment Flow

1. Your server
POST initiate
→ 2. Redirect customer
to payment_url
→ 3. sandbox/api?action=pay
card + OTP flow
→ 4. Webhook POST
to callback_url
→ 5. Customer lands
on return_url
→ 6. Your server
GET verify
ℹ️ Sessions expire after 1 hour. Records are kept for 24 hours for verify lookups. A completed session cannot be re-used — initiate a new session per payment attempt.

POST /sandbox/api?action=initiate

Creates a payment session. Returns a payment_url to redirect the customer to.

Request body

FieldTypeRequiredDescription
amountfloatrequiredCharge amount — minimum 0.01
currencystringrequired3-letter code — see supported list
return_urlstringrequiredRedirect here after successful payment
cancel_urlstringoptionalRedirect on cancel (defaults to return_url)
callback_urlstringoptionalWebhook endpoint — fired on completion
referencestringoptionalYour internal order / reference ID
descriptionstringoptionalPayment description shown to customer
customer_emailstringoptionalPre-fills email on payment page
merchant_namestringoptionalShown on payment page (default: Merchant)
merchant_idstringoptionalYour merchant ID (default: MER-0001)

Supported currencies

USD EUR GBP LKR AUD CAD SGD INR JPY AED

Example request

POST https://apps.devnexi.com/sandbox/api?action=initiate
Content-Type: application/json

{
  "amount": 150.00,
  "currency": "USD",
  "reference": "ORD-2024-001",
  "description": "Consultation Fee",
  "return_url": "https://yourapp.com/payment/success",
  "cancel_url": "https://yourapp.com/payment/cancel",
  "callback_url": "https://yourapp.com/webhooks/payment",
  "customer_email": "[email protected]",
  "merchant_name": "City Medical Centre",
  "merchant_id": "MER-CMC-001"
}

Success response 200 OK

{
  "success": true,
  "session_id": "SPY-A1B2C3D4E5F6",
  "payment_url": "https://apps.devnexi.com/sandbox/api?action=pay&session=SPY-A1B2C3D4E5F6&currency=USD&ref=ORD-2024-001",
  "amount": 150.00,
  "currency": "USD",
  "expires_at": "2024-01-15T11:30:00+00:00"
}

GET /sandbox/api?action=session

Returns session details to pre-fill the hosted payment form. Called automatically by the hosted payment UI — you rarely need this directly.

Query parameters

ParameterTypeRequiredDescription
idstringrequiredSession ID returned from initiate

Success response 200 OK

{
  "success": true,
  "session_id": "SPY-A1B2C3D4E5F6",
  "amount": 150.00,
  "currency": "USD",
  "reference": "ORD-2024-001",
  "description": "Consultation Fee",
  "merchant_name": "City Medical Centre",
  "merchant_id": "MER-CMC-001",
  "return_url": "https://yourapp.com/payment/success",
  "cancel_url": "https://yourapp.com/payment/cancel",
  "customer_email": "[email protected]",
  "expires_at": "2024-01-15T11:30:00+00:00"
}
⚠️ Returns 410 Gone if the session is already completed or has expired.

POST /sandbox/api?action=complete

Records a payment result and fires the webhook. Called automatically by the hosted payment UI — no need to call this from your integration.

Request body

FieldTypeRequiredDescription
session_idstringrequiredSession ID
transaction_idstringrequiredGenerated transaction ID
statusstringrequiredsuccess · failed · cancelled
brandstringoptionalCard brand (Visa, Mastercard…)
last4stringoptionalLast 4 digits of card
emailstringoptionalCustomer email
reasonstringoptionalDecline reason (for failed)

GET /sandbox/api?action=verify

Look up a payment result. Call this from your server-side after the customer lands on your return_url.

Query parameters

ParameterTypeDescription
session_idstringSession ID (use this if you have it)
transaction_idstringTransaction ID (alternative)

Success response 200 OK

{
  "success": true,
  "session_id": "SPY-A1B2C3D4E5F6",
  "transaction_id": "TXN-9F8E7D6C5B4A",
  "reference": "ORD-2024-001",
  "amount": 150.00,
  "currency": "USD",
  "status": "success",
  "brand": "Visa",
  "last4": "4242",
  "method": "card",
  "reason": null,
  "created_at": "2024-01-15T10:30:00+00:00",
  "completed_at": "2024-01-15T10:32:45+00:00"
}

Status values

StatusMeaning
pendingSession created, payment not yet attempted
successPayment completed successfully
failedCard declined or error occurred
cancelledCustomer clicked Cancel

Webhooks

When a payment completes, SandboxPay POSTs a JSON payload to your callback_url with a signature header.

Request headers

HeaderDescription
Content-Typeapplication/json
X-SandboxPay-SignatureHMAC-SHA256 hex — see verification below

Payload

{
  "event": "payment.success",           // payment.success · payment.failed · payment.cancelled
  "session_id": "SPY-A1B2C3D4E5F6",
  "transaction_id": "TXN-9F8E7D6C5B4A",
  "reference": "ORD-2024-001",
  "amount": 150.00,
  "currency": "USD",
  "status": "success",
  "brand": "Visa",
  "last4": "4242",
  "method": "card",
  "reason": null,
  "completed_at": "2024-01-15T10:32:45+00:00"
}

Signature verification (PHP)

The signature is HMAC-SHA256(raw_body, session_id). Always verify before acting on the webhook.

<?php
// webhooks/payment.php

$raw     = file_get_contents('php://input');
$payload = json_decode($raw, true);

$sig      = $_SERVER['HTTP_X_SANDBOXPAY_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $raw, $payload['session_id'] ?? '');

if (!hash_equals($expected, $sig)) {
    http_response_code(401);
    exit('Invalid signature');
}

if ($payload['event'] === 'payment.success') {
    // fulfil order using $payload['reference']
    error_log('Paid: ' . $payload['reference'] . ' — ' . $payload['transaction_id']);
}

http_response_code(200);
echo 'OK';
✅ Webhook delivery has a 5-second timeout. Respond with HTTP 200 quickly — do heavy work asynchronously. Webhook fires once; there is no automatic retry in sandbox mode.

Test Cards

Use any of these numbers on the demo payment page. Any future expiry date, any 3-digit CVV, any cardholder name.

🔑 OTP / 3DS code is always 123456
4242 4242 4242 4242
Visa
✓ Approved
5555 5555 5555 4444
Mastercard
✓ Approved
3782 8224 6310 005
Amex
✓ Approved (4-digit CVV)
6011 1111 1111 1117
Discover
✓ Approved
4111 1111 1111 1111
Visa
✓ Classic test card
4000 0000 0000 0002
Visa
✗ Card declined
5105 1051 0510 5100
Mastercard
✗ Insufficient funds

Error Reference

HTTPerrorCause
400amount must be ≥ 0.01.Invalid or missing amount
400Unsupported currency. Allowed: …Currency not in allowed list
400return_url is required.Missing return_url field
400return_url must be a valid URL.Malformed URL
400session_id, transaction_id and status are required.Incomplete complete request
400Invalid status.Status not in success/failed/cancelled
400session_id or transaction_id is required.Missing verify parameter
404Session not found or expired.Unknown session ID
404Transaction not found.Unknown transaction ID
405POST required.Wrong HTTP method on POST-only endpoint
409Session already completed.Duplicate complete attempt
410Session already completed.Session is in non-pending state
410Session has expired. Please return to the merchant and try again.1-hour TTL elapsed

Code Examples

Full PHP integration

<?php
define('SANDBOXPAY_API', 'https://apps.devnexi.com/sandbox/api');

function spInitiate(array $p): array {
    $ctx = stream_context_create(['http' => [
        'method'  => 'POST',
        'header'  => 'Content-Type: application/json',
        'content' => json_encode($p),
        'timeout' => 10,
    ]]);
    return json_decode(@file_get_contents(SANDBOXPAY_API . '?action=initiate', false, $ctx), true) ?? [];
}

function spVerify(string $sessionId): array {
    return json_decode(@file_get_contents(
        SANDBOXPAY_API . '?action=verify&session_id=' . urlencode($sessionId)
    ), true) ?? [];
}

// checkout.php — redirect customer to payment page
$r = spInitiate([
    'amount'        => 75.00,
    'currency'      => 'LKR',
    'reference'     => 'ORD-' . time(),
    'return_url'    => 'https://yourapp.com/order/complete',
    'cancel_url'    => 'https://yourapp.com/cart',
    'callback_url'  => 'https://yourapp.com/webhooks/payment',
    'merchant_name' => 'My Store',
]);
if (!empty($r['success'])) {
    header('Location: ' . $r['payment_url']);
    exit;
}
die('Payment initiation failed: ' . ($r['error'] ?? 'unknown'));

// order/complete.php — verify result
$v = spVerify($_GET['session_id'] ?? '');
match ($v['status'] ?? '') {
    'success'   => markOrderPaid($v['reference'], $v['transaction_id']),
    'failed'    => showDeclinedPage($v['reason']),
    'cancelled' => redirectToCart(),
    default     => showErrorPage(),
};

Full JavaScript / fetch

const API = 'https://apps.devnexi.com/sandbox/api';

async function pay({ amount, currency, reference, merchantName }) {
  const r = await fetch(API + '?action=initiate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      amount, currency, reference,
      return_url:   window.location.origin + '/success',
      cancel_url:   window.location.origin + '/cart',
      merchant_name: merchantName,
    }),
  }).then(r => r.json());

  if (!r.success) throw new Error(r.error);
  window.location.href = r.payment_url;
}

// On /success page
async function verifyPayment() {
  const sid = new URLSearchParams(location.search).get('session_id');
  if (!sid) return;
  const v = await fetch(`${API}?action=verify&session_id=${sid}`).then(r => r.json());
  if (v.status === 'success') {
    document.querySelector('#result').textContent = `Paid ✓  ${v.transaction_id}`;
  }
}

verifyPayment();

Live Demo

Create a real session against this server and open the payment page in a new tab.

Response