Sandbox quickstart

From zero to a completed test payment. Every step uses the sandbox, so no real money moves.

1. Sign in to the sandbox dashboard #

Open sandbox.aegispay8.com with the invite you received, choose a password, and set up two-factor authentication (Google Authenticator, Microsoft Authenticator, 1Password…). Your merchant ID (mch_…) is shown at the bottom of the menu.

2. Create your key pair (on your server) #

bash
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out aegispay_private.pem
openssl pkey -in aegispay_private.pem -pubout -out aegispay_public.pem
chmod 600 aegispay_private.pem
cat aegispay_public.pem   # paste THIS one into the dashboard
Only aegispay_public.pem ever leaves your server. If you paste a private key into the dashboard, it is refused and you must treat it as leaked and make a new pair.

3. Register the public key #

  1. Dashboard → API keys → paste aegispay_public.pem, enter your 2FA code, Continue.
  2. The dashboard shows a one-line openssl command containing a one-time challenge. Run it on your server, where the private key is.
  3. Paste the Base64 output back. The key becomes active and you get its key ID (key_…).

This proves you hold the private key. Nobody can register a key that isn't theirs.

4. Save AegisPay's public key #

Responses and webhooks are signed by AegisPay. Fetch the sandbox key once and save it in your config. This is called pinning.

bash
curl -s https://sandbox-api.aegispay8.com/v1/platform-keys

Save public_key_pem as aegispay_platform_public.pem and note its key_id. Compare it with the key shown in the dashboard the first time.

.env
# .env on your server (never commit this file)
AEGIS_MERCHANT_ID=mch_xxxxxxxxxxxxxxxxxxxx
AEGIS_KEY_ID=key_xxxxxxxxxxxxxxxxxxxx
AEGIS_PLATFORM_KEY_ID=aegis_xxxxx
AEGIS_PRIVATE_KEY_PATH=/secure/aegispay_private.pem
AEGIS_PLATFORM_KEY_PATH=./aegispay_platform_public.pem

5. Copy the client and make your first calls #

Save this as aegispay.mjs. It signs requests, verifies every response, and verifies webhooks. It needs only Node.js 18+. Python and PHP versions are in Code libraries.

aegispay.mjs
// aegispay.mjs: AegisPay AEGIS1 client for Node.js 18+. No dependencies.
// Signs requests, verifies every response, and verifies webhooks.
import { constants, createHash, createPrivateKey, createPublicKey, randomBytes, sign, verify } from "node:crypto";

const PSS = { padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 };
const MAX_SKEW_SECONDS = 300;
const sha256 = (data) => createHash("sha256").update(data).digest("hex");

/** Header lookup that works with fetch Headers, Express req.headers, or a plain object. */
function header(headers, name) {
  if (typeof headers.get === "function") return headers.get(name) ?? "";
  const key = Object.keys(headers).find((k) => k.toLowerCase() === name.toLowerCase());
  const v = key === undefined ? "" : headers[key];
  return Array.isArray(v) ? "" : String(v ?? ""); // a duplicated header is never valid
}

export function canonicalQuery(raw = "") {
  const enc = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
  return [...new URLSearchParams(raw)]
    .map(([k, v]) => [enc(k), enc(v)])
    .sort(([a, b], [c, d]) => (a < c ? -1 : a > c ? 1 : b < d ? -1 : b > d ? 1 : 0))
    .map(([k, v]) => `${k}=${v}`)
    .join("&");
}

export function requestCanonical({ method, host, path, query = "", merchantId, keyId, timestamp, nonce, idempotencyKey = "", body = "" }) {
  return [
    "AEGIS1-REQUEST-RSA-PSS-SHA256", method.toUpperCase(), host.toLowerCase(), path, canonicalQuery(query),
    merchantId, keyId, timestamp, nonce, idempotencyKey ?? "", sha256(body),
  ].join("\n");
}

export class AegisPay {
  /**
   * baseUrl:       "https://sandbox-api.aegispay8.com" (sandbox) or "https://api.aegispay8.com" (production)
   * privateKeyPem: YOUR private key (keep it on your server only)
   * platformKeys:  { "<key_id>": "<AegisPay public key PEM>" }, pinned in your config
   */
  constructor({ baseUrl, merchantId, keyId, privateKeyPem, platformKeys, now = () => Date.now() }) {
    this.baseUrl = baseUrl;
    this.merchantId = merchantId;
    this.keyId = keyId;
    this.privateKey = createPrivateKey(privateKeyPem);
    this.platformKeys = Object.fromEntries(Object.entries(platformKeys).map(([id, pem]) => [id, createPublicKey(pem)]));
    this.now = now;
  }

  createPayment(input, idempotencyKey) {
    return this.request("POST", "/v1/payments", input, { idempotencyKey });
  }

  getPayment(paymentId) {
    return this.request("GET", `/v1/payments/${encodeURIComponent(paymentId)}`);
  }

  ping() {
    return this.request("GET", "/v1/ping");
  }

  /** Sends a signed request. Returns { status, body } only if AegisPay's response signature is valid. */
  async request(method, pathAndQuery, bodyObj, { idempotencyKey } = {}) {
    const url = new URL(pathAndQuery, this.baseUrl);
    const body = bodyObj === undefined ? "" : JSON.stringify(bodyObj); // serialise ONCE: these exact bytes are signed and sent
    const timestamp = String(Math.floor(this.now() / 1000));
    const nonce = randomBytes(24).toString("base64url");
    const canonical = requestCanonical({
      method, host: url.hostname, path: url.pathname, query: url.search.slice(1),
      merchantId: this.merchantId, keyId: this.keyId, timestamp, nonce, idempotencyKey, body,
    });
    const headers = {
      "X-Aegis-Merchant-Id": this.merchantId,
      "X-Aegis-Key-Id": this.keyId,
      "X-Aegis-Timestamp": timestamp,
      "X-Aegis-Nonce": nonce,
      "X-Aegis-Signature": sign("sha256", Buffer.from(canonical), { key: this.privateKey, ...PSS }).toString("base64"),
    };
    if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
    if (body) headers["Content-Type"] = "application/json";

    const res = await fetch(url, { method, headers, body: body || undefined, redirect: "error" });
    const raw = Buffer.from(await res.arrayBuffer());
    if (!this.verifyResponse({ status: res.status, method, path: url.pathname, requestNonce: nonce, headers: res.headers, body: raw })) {
      // Do NOT trust this response. The outcome is unknown: retry with the same Idempotency-Key, or re-query.
      throw new Error("AegisPay response signature is invalid");
    }
    return { status: res.status, body: raw.length ? JSON.parse(raw.toString("utf8")) : null };
  }

  verifyResponse({ status, method, path, requestNonce, headers, body }) {
    const keyId = header(headers, "X-Aegis-Key-Id");
    const timestamp = header(headers, "X-Aegis-Timestamp");
    const canonical = [
      "AEGIS1-RESPONSE-RSA-PSS-SHA256", String(status), method.toUpperCase(), path, this.merchantId, requestNonce,
      keyId, timestamp, header(headers, "X-Aegis-Nonce"), sha256(body),
    ].join("\n");
    return this.#check(keyId, timestamp, canonical, header(headers, "X-Aegis-Signature"));
  }

  /**
   * Verify a webhook. `rawBody` must be the exact bytes received (a Buffer), not re-serialised JSON.
   * Returns the parsed event, or null if it must be rejected (respond 401).
   */
  verifyWebhook(headers, rawBody) {
    const merchantId = header(headers, "X-Aegis-Merchant-Id");
    const eventId = header(headers, "X-Aegis-Event-Id");
    const keyId = header(headers, "X-Aegis-Key-Id");
    const timestamp = header(headers, "X-Aegis-Timestamp");
    if (merchantId !== this.merchantId) return null;
    const canonical = ["AEGIS1-WEBHOOK-RSA-PSS-SHA256", merchantId, eventId, keyId, timestamp, sha256(rawBody)].join("\n");
    if (!this.#check(keyId, timestamp, canonical, header(headers, "X-Aegis-Signature"))) return null;
    const event = JSON.parse(Buffer.from(rawBody).toString("utf8"));
    return event.id === eventId ? event : null;
  }

  #check(keyId, timestamp, canonical, signatureB64) {
    const key = this.platformKeys[keyId]; // only pinned keys, never a key the message names for itself
    if (!key || !/^\d{10}$/.test(timestamp)) return false;
    if (Math.abs(this.now() / 1000 - Number(timestamp)) > MAX_SKEW_SECONDS) return false;
    try {
      return verify("sha256", Buffer.from(canonical), { key, ...PSS }, Buffer.from(signatureB64, "base64"));
    } catch {
      return false;
    }
  }
}
try.mjs
// try.mjs  (run: node --env-file=.env try.mjs)
import { readFileSync } from "node:fs";
import { AegisPay } from "./aegispay.mjs";

const aegis = new AegisPay({
  baseUrl: "https://sandbox-api.aegispay8.com",
  merchantId: process.env.AEGIS_MERCHANT_ID,
  keyId: process.env.AEGIS_KEY_ID,
  privateKeyPem: readFileSync(process.env.AEGIS_PRIVATE_KEY_PATH),
  platformKeys: { [process.env.AEGIS_PLATFORM_KEY_ID]: readFileSync(process.env.AEGIS_PLATFORM_KEY_PATH) },
});

// 1. Is my signing right?
console.log(await aegis.ping());

// 2. Create a RM 1.00 FPX test payment
const ref = "TEST-" + Date.now();
const { status, body } = await aegis.createPayment(
  { amount: "1.00", method: "fpx", merchant_reference: ref, customer: { name: "Test Payer" } },
  ref + "-create",
);
console.log(status, body);
console.log("Open this in your browser to pay:", body.checkout_url);

ping should print authenticated: true. If you get AUTH_FAILED, see debugging signatures.

6. Pay with the test bank #

  1. Open the checkout_url. On the FPX bank list choose SBI Bank A (sometimes labelled Test Bank 1).
  2. On the bank simulator, enter any user ID and password (e.g. 1234 / 1234), choose an account, and approve.
  3. You're sent back to your return_url (or a thank-you page if you didn't give one).
  4. Within seconds the payment becomes succeeded. Check it in the dashboard under Payments, or with aegis.getPayment(id).
Real-bank entries on the sandbox bank list can't complete. Use the test bank. If a test payment is left on the bank list it expires after its expires_at time; create a new one with a new merchant_reference.

7. Receive the webhook #

Set your webhook URL under Settings → Webhooks (or send callback_url with each payment), then follow Webhooks to verify and process events. The dashboard's Webhooks page shows every delivery attempt and lets you resend one.