Skip to content

Search docs

Jump between documentation pages.

Browse docs

Accept payments with PayTabs in DaloyJS

PayTabs is a MENA-region payment gateway with coverage of Mada, KNET, BenefitPay, STC Pay, OmanNet, cards, and Apple Pay. This guide uses the paytabs_pt2 npm package (2.0.x, published by PayTabs) from a DaloyJS server, wrapped to feel like a normal async API.

What you should know up front

  • The package is callback-based with positional array arguments. We wrap it once in Promise-returning functions with named arguments, so route handlers stay clean.
  • Regions are not interchangeable. The package (2.0.12) maps these region codes to PayTabs hosts: ARE, SAU, OMN, JOR, EGY, KWT, MAR, IRQ, QAT, and GLOBAL. Use the region your profile lives in; the wrong one fails authentication even when the key is right.
  • It's a redirect flow. createPaymentPage returns a redirect_url, the customer pays there and comes back to your return URL. The callback URL receives the server-side IPN, and that (plus a query) is the only signal you mark an order paid on.
  • The amount comes from your order. The browser sends an order id and billing details, never a price. See never trust client amounts.
  • IPN signature is HMAC-SHA256. PayTabs signs the entire raw callback body with your profile Server Key and sends the hex digest in the Signature header.
  • Use tran_type: "sale" for direct capture, "auth" for an authorisation you capture later, and tran_class: "ecom" for normal online checkouts.

1. Provision

  1. Sign in to the PayTabs merchant dashboard.
  2. Developers -> Profile to grab your Profile ID and Server Key. Note your Region.
  3. Enable the payment methods you need (Mada, KNET, BenefitPay, and STC Pay need explicit activation, some need extra paperwork).

2. Install

bash
pnpm add paytabs_pt2

3. Environment variables

.envbash
PAYTABS_PROFILE_ID=12345
PAYTABS_SERVER_KEY=SXXXXXXXXX-JXXXXXXXXX-LXXXXXXXXX
PAYTABS_REGION=ARE                  # ARE | SAU | OMN | JOR | EGY | KWT | MAR | IRQ | QAT | GLOBAL
APP_URL=https://your-app.example.com

4. Plugin

src/plugins/paytabs.tsts
import PayTabs from "paytabs_pt2";
import { verifyWebhookSignature } from "@daloyjs/core";
import type { App } from "@daloyjs/core";

PayTabs.setConfig(
  process.env.PAYTABS_PROFILE_ID!,
  process.env.PAYTABS_SERVER_KEY!,
  process.env.PAYTABS_REGION!,
);

export interface PayTabsResponse {
  tran_ref?: string;
  redirect_url?: string;
  payment_result?: { response_status: string; response_code: string; response_message: string };
  cart_id?: string;
  cart_amount?: string;
  cart_currency?: string;
  [k: string]: unknown;
}

/** Billing or shipping contact, in the order the package's positional arrays expect. */
export interface PayTabsContact {
  name: string;
  email: string;
  phone: string;   // include country code, e.g. "971500000000"
  street: string;
  city: string;
  state: string;
  country: string; // ISO 3166-1 alpha-2, e.g. "AE"
  zip: string;
  ip: string;      // trusted client IP, or "" when unknown
}

export interface PayTabsClient {
  createPaymentPage(input: {
    cart: { id: string; amount: string; currency: string; description: string };
    customer: PayTabsContact;
    shipping?: PayTabsContact;
    type?: "sale" | "auth";
    lang?: "ar" | "en";
  }): Promise<PayTabsResponse>;

  /** Query a transaction's current state (PT2 /payment/query). */
  queryTransaction(tranRef: string): Promise<PayTabsResponse>;

  /** Follow-up refund against a captured sale (PT2 /payment/request, tran_type "refund"). */
  refund(input: { tranRef: string; amount: string; currency: string; cartId: string; description: string }): Promise<PayTabsResponse>;

  verifyIpnSignature(rawBody: string, signatureHeader: string | null): Promise<boolean>;
}

const contact = (c: PayTabsContact) => [c.name, c.email, c.phone, c.street, c.city, c.state, c.country, c.zip, c.ip];

// Exported so job handlers (which run outside a request) can use it too.
export const paytabsClient: PayTabsClient = {
  createPaymentPage(input) {
    return new Promise((resolve, reject) => {
      PayTabs.createPaymentPage(
        ["all"],                                  // payment methods enabled on the profile
        [input.type ?? "sale", "ecom"],
        [input.cart.id, input.cart.currency, input.cart.amount, input.cart.description],
        contact(input.customer),
        contact(input.shipping ?? input.customer),
        [
          `${process.env.APP_URL}/webhooks/paytabs`,                                              // callback (IPN)
          `${process.env.APP_URL}/checkout/paytabs/return?order=${encodeURIComponent(input.cart.id)}`, // return
        ],
        input.lang ?? "en",
        (response: PayTabsResponse) => {
          if (response?.redirect_url && response.tran_ref) resolve(response);
          else reject(new Error("paytabs createPaymentPage failed"));
        },
      );
    });
  },

  queryTransaction(tranRef) {
    return new Promise((resolve, reject) => {
      PayTabs.validatePayment(tranRef, (response: PayTabsResponse) => {
        if (response?.tran_ref && response.payment_result) resolve(response);
        else reject(new Error("paytabs query failed"));
      });
    });
  },

  refund({ tranRef, amount, currency, cartId, description }) {
    return new Promise((resolve, reject) => {
      PayTabs.queryTransaction(
        [tranRef, "refund", "ecom"],
        [cartId, currency, amount, description],
        (response: PayTabsResponse) => {
          if (response?.payment_result?.response_status === "A") resolve(response);
          else reject(new Error("paytabs refund failed"));
        },
      );
    });
  },

  verifyIpnSignature(rawBody, signatureHeader) {
    if (!signatureHeader) return Promise.resolve(false);
    return verifyWebhookSignature({
      payload: rawBody,
      signature: signatureHeader, // hex HMAC-SHA256 of the entire body
      secret: process.env.PAYTABS_SERVER_KEY!,
      algorithm: "sha256",
    });
  },
};

// Call with the root app, not through app.register(): a decoration made
// inside a registered plugin is visible only to that plugin's own routes.
export function paytabsPlugin(app: App) {
  app.decorate("paytabs", paytabsClient);
}

declare module "@daloyjs/core" {
  interface AppState {
    paytabs: PayTabsClient;
  }
}

In the package, the misleadingly named queryTransaction(transaction[], cart[], cb) posts a follow-up transaction (refund, capture, void) to /payment/request, while validatePayment(tranRef, cb) is the actual status query. The wrapper gives them honest names.

5. Create a payment page

Payment page flow
CustomerDaloyJS routePayTabs
  1. 01requestCustomerDaloyJS routePOST /checkout/paytabs{ orderId, billing } only
  2. 02requestDaloyJS routePayTabscreatePaymentPagecart amount from the order, callback + return URLs
  3. 03responseDaloyJS routeCustomerReturn redirect_url201 { tranRef, redirectUrl }
  4. 04asyncCustomerPayTabsPays on the hosted page, returns via the return URLreturn URL is a UX hint, not proof
The server loads the cart amount and currency from the order and resolves the client IP from the trusted proxy configuration. The return URL renders a confirmation only; the signed IPN is what marks an order paid.

The route relies on the shared app wiring, including behindProxy, and the overview's orders and money modules. The client IP comes from resolveClientIp(), which only trusts X-Forwarded-For hops your behindProxy setting declares; reading the header directly lets any caller choose their own IP.

src/routes/checkout-paytabs.tsts
import { z } from "zod";
import { resolveClientIp } from "@daloyjs/core";
import { paytabsPlugin } from "../plugins/paytabs.ts";
import { orders } from "../orders.ts";
import { formatMinor } from "../money.ts";

const BEHIND_PROXY = { hops: 1 } as const; // same value you pass to new App({ behindProxy })

paytabsPlugin(app);

const Billing = z.object({
  name: z.string().min(1).max(80),
  email: z.email(),
  phone: z.string().min(7).max(20),
  street: z.string().max(120),
  city: z.string().max(60),
  state: z.string().max(60),
  country: z.string().length(2),
  zip: z.string().max(20),
}).strict();

app.post(
  "/checkout/paytabs",
  {
    operationId: "createPayTabsPaymentPage",
    request: {
      body: z.object({ orderId: z.string().min(1).max(80), billing: Billing }).strict(),
    },
    responses: {
      201: {
        description: "redirect to PayTabs",
        body: z.object({ tranRef: z.string(), redirectUrl: z.url() }),
      },
    },
  },
  async ({ body, request, state }) => {
    const order = await orders.forCheckout(body.orderId, state.session.get<string>("userId"));
    // Never fall back to a made-up address such as 0.0.0.0.
    const ip = resolveClientIp(request, BEHIND_PROXY) ?? "";

    const response = await state.paytabs.createPaymentPage({
      cart: {
        id: order.id,
        amount: formatMinor(order.amountMinor, order.currency), // server-side total
        currency: order.currency,
        description: `Order ${order.id}`,
      },
      customer: { ...body.billing, ip },
    });

    return { status: 201, body: { tranRef: response.tran_ref!, redirectUrl: response.redirect_url! } };
  },
);

6. IPN webhook

IPN verification
PayTabsDaloyJS routeJob worker
  1. 01requestPayTabsDaloyJS routePOST /webhooks/paytabsSignature header (HMAC-SHA256 hex) over raw body
  2. 02noteDaloyJS routeDaloyJS routeverifyWebhookSignature with the Server Keyconstant-time compare
  3. 03responseDaloyJS routePayTabs401 when the signature does not match{ error: 'bad signature' }
  4. 04asyncDaloyJS routeJob workerenqueue keyed by tran_ref + status, then 200worker re-queries and compares with the order
Verify the HMAC-SHA256 signature over the raw body with your Server Key, dedupe on the transaction reference plus status, then re-query the transaction in the worker and fulfil only when response_status is 'A' and the amount matches.
src/webhooks/paytabs.tsts
import { z } from "zod";
import { readBodyLimited, safeJsonParse, jobIdempotencyKey } from "@daloyjs/core";
import type { PayTabsResponse } from "../plugins/paytabs.ts";

app.post(
  "/webhooks/paytabs",
  {
    operationId: "paytabsIpn",
    responses: {
      200: { description: "ok", body: z.object({ ok: z.literal(true) }) },
      401: { description: "bad signature", body: z.object({ error: z.string() }) },
    },
  },
  async ({ request, state }) => {
    const raw = new TextDecoder().decode(await readBodyLimited(request, 1_048_576));
    if (!(await state.paytabs.verifyIpnSignature(raw, request.headers.get("signature")))) {
      return { status: 401, body: { error: "bad signature" } };
    }

    const event = safeJsonParse(raw) as PayTabsResponse;
    const status = event.payment_result?.response_status; // "A" authorised, "H" hold, "P" pending, "V" voided, "E" error, "D" declined
    if (event.tran_ref && status) {
      await app.jobs!.enqueue({
        name: "paytabs.transaction",
        payload: { tranRef: event.tran_ref, status },
        idempotencyKey: jobIdempotencyKey({ name: "paytabs.transaction", key: `${event.tran_ref}:${status}` }),
      });
    }
    return { status: 200, body: { ok: true as const } };
  },
);
src/jobs/paytabs.tsts
import type { JobHandler } from "@daloyjs/core";
import { paytabsClient } from "../plugins/paytabs.ts";
import { orders } from "../orders.ts";
import { toMinor } from "../money.ts";

export const handlePayTabsTransaction: JobHandler<{ tranRef: string }> = async ({ job }) => {
  const tx = await paytabsClient.queryTransaction(job.payload.tranRef);
  if (tx.payment_result?.response_status !== "A" || !tx.cart_id) return;
  await orders.markPaid(tx.cart_id, {
    amountMinor: toMinor(tx.cart_amount!, tx.cart_currency!),
    currency: tx.cart_currency!,
    providerRef: job.payload.tranRef,
  });
};
// Register it in your single app.useJobs() call (see the payments overview).

7. Refunds and capture

Expose refunds only through a protected refund route. The plugin call:

ts
await state.paytabs.refund({
  tranRef: order.providerRef!,
  amount: formatMinor(amountMinor, order.currency), // never more than captured minus refunded
  currency: order.currency,
  cartId: order.id,
  description: "Customer request",
});

Capturing an authorisation (tran_type: "auth") is the same follow-up call with "capture" instead of "refund". PayTabs' docs do not describe an idempotency key for follow-up transactions, so serialise refunds per order in your database before calling.

Runtimes

paytabs_pt2 is a CommonJS package built on axios. It runs on Node hosts (long-lived Node, Vercel Node.js functions, AWS Lambda, Azure Functions); other runtimes are not verified. For Cloudflare Workers or Vercel Edge, call the PT2 REST endpoints directly with fetch, as noted above. See the runtime table.

Errors

On failure, payment_result.response_code and response_message describe the gateway outcome. Log them and surface declines through problem+json with your own message; do not pass PayTabs' text to end users, because declines often include scheme-specific text the customer cannot act on.

Modernisation notes

  • Wrap the package in one plugin. The positional-array signatures are easy to typo and harder to grep for than named-object arguments.
  • Verify the IPN signature, always. Don't fall back to "the IP is from PayTabs"; HMAC over the raw body is the verification PayTabs documents.
  • Fulfil on IPN plus a query, not on the return URL. The customer can close the tab mid-3DS.
  • Consider the REST API directly if you need edge runtimes or multiple profiles; a short resilientFetch wrapper gives you the same shape.

See also the payments overview, Tap Payments guide, Adyen guide, and problem+json errors.

Edit this page on GitHub

Last updated