Code libraries
Single-file clients you copy into your project. No AegisPay package to install, nothing to trust but code you can read.
The Node.js and Python clients are tested on every AegisPay release against the AEGIS1 test vectors. Run the Python self-test yourself:
python aegis1.py selftest aegis1-vectors.json.Node.js (18 or newer) #
No dependencies. Save as aegispay.mjs.
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;
}
}
}
Usage
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, // mch_...
keyId: process.env.AEGIS_KEY_ID, // key_...
privateKeyPem: readFileSync("/secure/aegispay_private.pem"),
platformKeys: { [process.env.AEGIS_PLATFORM_KEY_ID]: readFileSync("aegispay_platform_public.pem") },
});
const { status, body } = await aegis.createPayment(
{
amount: "150.00",
currency: "MYR",
method: "fpx",
merchant_reference: "ORDER-1001",
description: "Order #1001",
customer: { name: "Siti Aminah", email: "siti@example.com" },
return_url: "https://shop.example.com/orders/1001/return",
callback_url: "https://shop.example.com/aegis/webhook",
},
"order-1001-create", // Idempotency-Key: reuse it if you retry this same order
);
if (status === 201) {
// Send the payer's browser to body.checkout_url
}
Python (3.9 or newer) #
Needs pip install cryptography requests. Save as aegis1.py.
aegis1.py
"""
AegisPay AEGIS1 request signing / response + webhook verification (Python 3.9+).
pip install cryptography requests
Self-test against the published vectors:
python aegis1.py selftest ../../test-vectors/aegis1-vectors.json
"""
from __future__ import annotations
import base64
import hashlib
import json
import secrets
import sys
import time
from urllib.parse import parse_qsl, quote
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
REQUEST_LABEL = "AEGIS1-REQUEST-RSA-PSS-SHA256"
RESPONSE_LABEL = "AEGIS1-RESPONSE-RSA-PSS-SHA256"
WEBHOOK_LABEL = "AEGIS1-WEBHOOK-RSA-PSS-SHA256"
MAX_SKEW_SECONDS = 300
PSS = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32)
def sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def canonical_query(raw: str) -> str:
raw = raw[1:] if raw.startswith("?") else raw
if raw == "":
return ""
pairs = [
(quote(k, safe="-._~"), quote(v, safe="-._~"))
for k, v in parse_qsl(raw, keep_blank_values=True)
]
pairs.sort()
return "&".join(f"{k}={v}" for k, v in pairs)
def request_canonical(method, host, path, query, merchant_id, key_id, timestamp, nonce, idempotency_key, body: bytes) -> str:
return "\n".join([
REQUEST_LABEL, method.upper(), host.lower(), path, canonical_query(query),
merchant_id, key_id, timestamp, nonce, idempotency_key or "", sha256_hex(body),
])
def sign_request(private_key_pem: bytes, *, method, host, path, query="", merchant_id, key_id,
body: bytes = b"", idempotency_key: str | None = None) -> dict:
"""Returns the headers to send. `body` must be the EXACT bytes you send."""
key = serialization.load_pem_private_key(private_key_pem, password=None)
timestamp = str(int(time.time()))
nonce = secrets.token_urlsafe(24) # 32 chars, 192 bits
canonical = request_canonical(method, host, path, query, merchant_id, key_id, timestamp, nonce, idempotency_key, body)
headers = {
"X-Aegis-Merchant-Id": merchant_id,
"X-Aegis-Key-Id": key_id,
"X-Aegis-Timestamp": timestamp,
"X-Aegis-Nonce": nonce,
"X-Aegis-Signature": base64.b64encode(key.sign(canonical.encode(), PSS, hashes.SHA256())).decode(),
}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
return headers
def _verify(public_key, canonical: str, signature_b64: str) -> bool:
try:
public_key.verify(base64.b64decode(signature_b64, validate=True), canonical.encode(), PSS, hashes.SHA256())
return True
except (InvalidSignature, ValueError):
return False
def _fresh(timestamp: str, now: float | None) -> bool:
return abs((now if now is not None else time.time()) - int(timestamp)) <= MAX_SKEW_SECONDS
def _h(headers: dict, name: str) -> str:
for k, v in headers.items():
if k.lower() == name.lower():
return v
raise ValueError(f"missing header {name}")
def verify_response(platform_keys: dict, *, status: int, method: str, path: str, merchant_id: str,
request_nonce: str, headers: dict, body: bytes, now: float | None = None) -> bool:
"""platform_keys: {key_id: public_key}. request_nonce is the nonce YOU sent."""
key_id, ts = _h(headers, "X-Aegis-Key-Id"), _h(headers, "X-Aegis-Timestamp")
if key_id not in platform_keys or not _fresh(ts, now):
return False
canonical = "\n".join([
RESPONSE_LABEL, str(status), method.upper(), path, merchant_id, request_nonce,
key_id, ts, _h(headers, "X-Aegis-Nonce"), sha256_hex(body),
])
return _verify(platform_keys[key_id], canonical, _h(headers, "X-Aegis-Signature"))
def verify_webhook(platform_keys: dict, *, expected_merchant_id: str, headers: dict, body: bytes,
now: float | None = None) -> str | None:
"""Returns the event id if valid, else None. You must still de-duplicate on the event id."""
merchant_id, event_id = _h(headers, "X-Aegis-Merchant-Id"), _h(headers, "X-Aegis-Event-Id")
key_id, ts = _h(headers, "X-Aegis-Key-Id"), _h(headers, "X-Aegis-Timestamp")
if merchant_id != expected_merchant_id or key_id not in platform_keys or not _fresh(ts, now):
return None
canonical = "\n".join([WEBHOOK_LABEL, merchant_id, event_id, key_id, ts, sha256_hex(body)])
return event_id if _verify(platform_keys[key_id], canonical, _h(headers, "X-Aegis-Signature")) else None
# --------------------------------------------------------------------------- self-test
def _selftest(path: str) -> None:
v = json.load(open(path))
merchant_pub = serialization.load_pem_public_key(v["keys"]["merchant"]["public_key_pem"].encode())
platform = {v["keys"]["aegis_platform"]["key_id"]:
serialization.load_pem_public_key(v["keys"]["aegis_platform"]["public_key_pem"].encode())}
failures = 0
def check(name, cond):
nonlocal failures
print(("PASS " if cond else "FAIL ") + name)
failures += 0 if cond else 1
for c in v["canonical_query"]:
check(f"canonical_query {c['input']!r}", canonical_query(c["input"]) == c["canonical"])
for r in v["requests"]:
i, h = r["input"], r["input"]["headers"]
canonical = request_canonical(i["method"], i["host"], i["path"], i["query"], h["X-Aegis-Merchant-Id"],
h["X-Aegis-Key-Id"], h["X-Aegis-Timestamp"], h["X-Aegis-Nonce"],
h.get("Idempotency-Key", ""), i["body_utf8"].encode())
check(f"request {r['name']} canonical", canonical == r["expected"]["canonical_string"])
check(f"request {r['name']} signature", _verify(merchant_pub, canonical, h["X-Aegis-Signature"]))
# Our own signature must also verify (proves signing side, not just verifying).
priv = v["keys"]["merchant"]["private_key_pem"].encode()
hdrs = sign_request(priv, method="POST", host="api.aegispay8.com", path="/v1/payments",
merchant_id="mch_TEST0000000000000001", key_id="key_TEST0000000000000001",
body=b'{"a":1}', idempotency_key="idem_selftest_01")
canonical = request_canonical("POST", "api.aegispay8.com", "/v1/payments", "", hdrs["X-Aegis-Merchant-Id"],
hdrs["X-Aegis-Key-Id"], hdrs["X-Aegis-Timestamp"], hdrs["X-Aegis-Nonce"],
"idem_selftest_01", b'{"a":1}')
check("sign_request round-trip", _verify(merchant_pub, canonical, hdrs["X-Aegis-Signature"]))
rs = v["response"]
ri = rs["input"]
check("response", verify_response(platform, status=ri["status"], method=ri["request_method"],
path=ri["request_path"], merchant_id=ri["merchant_id"],
request_nonce=ri["request_nonce"], headers=ri["headers"],
body=ri["body_utf8"].encode(), now=rs["verify_at_unix"]))
check("response tampered", not verify_response(platform, status=ri["status"], method=ri["request_method"],
path=ri["request_path"], merchant_id=ri["merchant_id"],
request_nonce=ri["request_nonce"], headers=ri["headers"],
body=ri["body_utf8"].replace("pending", "succeeded").encode(),
now=rs["verify_at_unix"]))
wh = v["webhook"]
check("webhook", verify_webhook(platform, expected_merchant_id="mch_TEST0000000000000001",
headers=wh["input"]["headers"], body=wh["input"]["body_utf8"].encode(),
now=wh["verify_at_unix"]) == wh["input"]["headers"]["X-Aegis-Event-Id"])
check("webhook stale", verify_webhook(platform, expected_merchant_id="mch_TEST0000000000000001",
headers=wh["input"]["headers"], body=wh["input"]["body_utf8"].encode(),
now=wh["verify_at_unix"] + 3600) is None)
sys.exit(1 if failures else 0)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "selftest":
_selftest(sys.argv[2])
else:
print(__doc__)
Loading keys
from cryptography.hazmat.primitives import serialization
PRIVATE_KEY_PEM = open("/secure/aegispay_private.pem", "rb").read()
PLATFORM_KEYS = { # pinned: key_id -> AegisPay public key
"aegis_xxxxx": serialization.load_pem_public_key(open("aegispay_platform_public.pem", "rb").read()),
}See create a payment and webhooks for usage.
PHP (8.0 or newer) #
PHP's built-in openssl_sign() can't make RSA-PSS signatures, so this uses phpseclib 3. Check your canonical strings against the test vectors before going live.
aegispay.php
<?php
// composer require phpseclib/phpseclib:~3.0
// PHP's openssl_sign() cannot make RSA-PSS signatures, so use phpseclib 3.
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
const AEGIS_HOST = 'sandbox-api.aegispay8.com'; // production: api.aegispay8.com
function aegis_canonical_query(string $raw): string {
if ($raw === '') return '';
$pairs = [];
foreach (explode('&', $raw) as $part) {
if ($part === '') continue;
[$k, $v] = array_pad(explode('=', $part, 2), 2, '');
$pairs[] = [rawurlencode(urldecode($k)), rawurlencode(urldecode($v))];
}
usort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));
return implode('&', array_map(fn($p) => $p[0] . '=' . $p[1], $pairs));
}
/** Returns [headers, nonce]. $body must be the exact string you send. */
function aegis_sign(string $method, string $path, string $query, string $body, ?string $idemKey): array {
$merchantId = getenv('AEGIS_MERCHANT_ID');
$keyId = getenv('AEGIS_KEY_ID');
$timestamp = (string) time();
$nonce = rtrim(strtr(base64_encode(random_bytes(24)), '+/', '-_'), '=');
$canonical = implode("\n", [
'AEGIS1-REQUEST-RSA-PSS-SHA256', $method, AEGIS_HOST, $path, aegis_canonical_query($query),
$merchantId, $keyId, $timestamp, $nonce, $idemKey ?? '', hash('sha256', $body),
]);
$key = PublicKeyLoader::load(file_get_contents('/secure/aegispay_private.pem'))
->withPadding(RSA::SIGNATURE_PSS)->withHash('sha256')->withMGFHash('sha256')->withSaltLength(32);
$headers = [
'X-Aegis-Merchant-Id: ' . $merchantId,
'X-Aegis-Key-Id: ' . $keyId,
'X-Aegis-Timestamp: ' . $timestamp,
'X-Aegis-Nonce: ' . $nonce,
'X-Aegis-Signature: ' . base64_encode($key->sign($canonical)),
];
if ($idemKey !== null) $headers[] = 'Idempotency-Key: ' . $idemKey;
if ($body !== '') $headers[] = 'Content-Type: application/json';
return [$headers, $nonce];
}
// Create a payment
$body = json_encode([
'amount' => '150.00', 'currency' => 'MYR', 'method' => 'fpx', 'merchant_reference' => 'ORDER-1001',
'customer' => ['name' => 'Siti Aminah'], 'return_url' => 'https://shop.example.com/return',
], JSON_UNESCAPED_SLASHES);
[$headers] = aegis_sign('POST', '/v1/payments', '', $body, 'order-1001-create');
$ch = curl_init('https://' . AEGIS_HOST . '/v1/payments');
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true]);
$response = curl_exec($ch);
// Then verify the response signature before trusting it (see "Verify responses").
Other languages #
Any language with RSA-PSS (SHA-256, MGF1-SHA-256, salt 32) works: Java (RSASSA-PSS with PSSParameterSpec), Go (rsa.SignPSS with SaltLength: 32), C# (RSASignaturePadding.Pss; .NET uses salt = hash length = 32). Follow Signing requests and test against the vectors.