Skip to content

Search docs

Jump between documentation pages.

Browse docs

Accept payments with Tap Payments in DaloyJS

Tap Payments is a leading acquirer for the GCC and wider MENA region. It is how you accept KNET (Kuwait), Mada (Saudi), Benefit / BenefitPay (Bahrain), STC Pay, plus cards, Apple Pay, Google Pay, and BNPL methods. There is no first-party Node SDK; you integrate against the REST API with fetch, which also means the integration runs on every DaloyJS runtime.

What you should know up front

  • Bearer auth, secret key in the backend only. Authorization: Bearer sk_test_... or sk_live_.... Public keys (pk_*) are for the frontend SDKs.
  • It's a redirect flow. You create a charge, Tap returns transaction.url, you redirect the customer. They come back via your redirect.url with ?tap_id=chg_xxx. That is a UX hint, not proof of payment.
  • The server picks the amount, currency, and payment source. The browser sends only an order id. See never trust client amounts.
  • Idempotency is a body field. Tap deduplicates on reference.idempotent for charges, authorizations, and refunds, for 24 hours. Derive it from your order id.
  • Webhooks carry a hashstring header: an HMAC-SHA256 (hex) over a specific concatenation of charge fields, keyed with your secret key. Verify it on every request, then refetch the charge.
  • Amounts are decimals with the currency's precision. Tap takes amount as a number, and the hashstring rounds it to the currency's decimals: 2 for most currencies, 3 for KWD, BHD, OMR, and JOD.
CurrencyDecimalsExample x_amount
SAR, AED, QAR, EGP, USD, EUR, GBP210.00
KWD, BHD, OMR, JOD310.000

1. Provision

  1. Create an account at tap.company and sign in to the dashboard.
  2. Grab your Merchant ID, plus Test/Live Secret Keys (sk_*) and Public Keys (pk_*).
  3. Enable the payment methods you need (KNET, Mada, Benefit, and so on); some require contacting Tap support.
  4. Your charges pass a post.url, so Tap posts webhooks for each charge to your DaloyJS server.

2. Environment variables

.envbash
TAP_SECRET_KEY=sk_test_replace_me        # sk_live_... in production
TAP_PUBLIC_KEY=pk_test_replace_me        # ships to the browser SDKs
APP_URL=https://your-app.example.com

3. Plugin (no SDK: fetch-based)

src/plugins/tap.tsts
import { resilientFetch, safeJsonParse, verifyWebhookSignature } from "@daloyjs/core";
import type { App } from "@daloyjs/core";
import { currencyDecimals } from "../money.ts";

const BASE = "https://api.tap.company/v2";

// Per-attempt timeout; only idempotent methods are retried by default.
const tapFetch = resilientFetch({ timeoutMs: 15_000, retries: 2 });

type ChargeStatus =
  | "INITIATED" | "ABANDONED" | "CANCELLED" | "FAILED" | "DECLINED"
  | "RESTRICTED" | "CAPTURED" | "AUTHORIZED" | "VOID" | "TIMEDOUT" | "UNKNOWN";

export interface TapCharge {
  id: string;
  status: ChargeStatus;
  amount: number;
  currency: string;
  reference?: { transaction?: string; order?: string; gateway?: string; payment?: string; idempotent?: string };
  transaction?: { url?: string; created?: string };
  metadata?: Record<string, string>;
}

async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await tapFetch(`${BASE}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${process.env.TAP_SECRET_KEY}`,
      "Content-Type": "application/json",
    },
  });
  const text = await res.text();
  const body = text ? (safeJsonParse(text) as { errors?: Array<{ code?: string }> }) : null;
  if (!res.ok) {
    // Keep Tap's error codes for logs; callers map this to a generic problem+json.
    throw Object.assign(new Error(`tap ${res.status}`), { status: res.status, code: body?.errors?.[0]?.code });
  }
  return body as T;
}

// Field order and names follow https://developers.tap.company/docs/webhook
function buildHashString(c: TapCharge): string {
  const amount = Number(c.amount).toFixed(currencyDecimals(c.currency));
  return (
    `x_id${c.id}` +
    `x_amount${amount}` +
    `x_currency${c.currency}` +
    `x_gateway_reference${c.reference?.gateway ?? ""}` +
    `x_payment_reference${c.reference?.payment ?? ""}` +
    `x_status${c.status}` +
    `x_created${c.transaction?.created ?? ""}`
  );
}

export interface TapClient {
  createCharge(input: {
    amount: number;
    currency: string;
    description: string;
    orderId: string;
    idempotent: string;
    customer: { first_name: string; email?: string };
  }): Promise<TapCharge>;
  getCharge(id: string): Promise<TapCharge>;
  refund(input: { chargeId: string; amount: number; currency: string; reason: string; idempotent: string }): Promise<{ id: string; status: string }>;
  verifyWebhookHash(charge: TapCharge, hashstring: string | null): Promise<boolean>;
}

// Exported so job handlers (which run outside a request) can use it too.
export const tapClient: TapClient = {
  createCharge({ amount, currency, description, orderId, idempotent, customer }) {
    return call<TapCharge>("/charges", {
      method: "POST",
      body: JSON.stringify({
        amount,
        currency,
        description,
        reference: { transaction: orderId, order: orderId, idempotent },
        customer,
        source: { id: "src_all" }, // hosted page with every enabled method; chosen by the server
        post: { url: `${process.env.APP_URL}/webhooks/tap` },
        redirect: { url: `${process.env.APP_URL}/checkout/tap/return?order=${encodeURIComponent(orderId)}` },
        metadata: { orderId },
      }),
    });
  },

  getCharge(id) {
    return call<TapCharge>(`/charges/${encodeURIComponent(id)}`);
  },

  refund({ chargeId, amount, currency, reason, idempotent }) {
    return call("/refunds", {
      method: "POST",
      body: JSON.stringify({
        charge_id: chargeId,
        amount,
        currency,
        reason,
        reference: { idempotent },
        post: { url: `${process.env.APP_URL}/webhooks/tap` },
      }),
    });
  },

  async verifyWebhookHash(charge, hashstring) {
    if (!hashstring) return false;
    return verifyWebhookSignature({
      payload: buildHashString(charge),
      signature: hashstring, // lowercase hex
      secret: process.env.TAP_SECRET_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 tapPlugin(app: App) {
  app.decorate("tap", tapClient);
}

declare module "@daloyjs/core" {
  interface AppState {
    tap: TapClient;
  }
}

The field order and the amount rounding inside buildHashString are the parts Tap is strict about. Keep them pinned to their webhook docs: x_gateway_reference is reference.gateway, x_payment_reference is reference.payment, and x_created is transaction.created, each empty when missing. verifyWebhookSignature() compares the hex digest in constant time.

4. Create a hosted charge

Hosted charge flow
CustomerDaloyJS routeTap
  1. 01requestCustomerDaloyJS routePOST /checkout/tap{ orderId } only
  2. 02requestDaloyJS routeTapPOST /v2/chargesamount from the order, reference.idempotent, src_all
  3. 03responseDaloyJS routeCustomerReturn transaction.url201 { redirectUrl }
  4. 04asyncCustomerTapPays on the hosted page, returns with ?tap_id=chg_xxxredirect is a UX hint, not proof
The server loads the amount and currency from the order, picks the payment source, and sends an order-derived reference.idempotent so a retry cannot create a second charge.

The route relies on the shared app wiring (session, scoped csrf() and rateLimit()) and the overview's orders and money modules.

src/routes/checkout-tap.tsts
import { z } from "zod";
import { tapPlugin } from "../plugins/tap.ts";
import { orders } from "../orders.ts";
import { formatMinor } from "../money.ts";

tapPlugin(app);

app.post(
  "/checkout/tap",
  {
    operationId: "createTapCharge",
    request: {
      body: z.object({ orderId: z.string().min(1).max(80) }).strict(),
    },
    responses: {
      201: {
        description: "redirect to Tap",
        body: z.object({ chargeId: z.string(), redirectUrl: z.url() }),
      },
    },
  },
  async ({ body, state }) => {
    const userId = state.session.get<string>("userId");
    const order = await orders.forCheckout(body.orderId, userId);
    const charge = await state.tap.createCharge({
      amount: Number(formatMinor(order.amountMinor, order.currency)), // e.g. 1.250 KWD
      currency: order.currency,
      description: `Order ${order.id}`,
      orderId: order.id,
      idempotent: `${order.id}-v${order.version}`,
      customer: { first_name: "Customer" }, // load the name and email from your user record
    });
    const url = charge.transaction?.url;
    if (!url) throw new Error("Tap did not return a redirect URL");
    return { status: 201, body: { chargeId: charge.id, redirectUrl: url } };
  },
);

5. Webhook

Webhook verification
TapDaloyJS routeJob worker
  1. 01requestTapDaloyJS routePOST /webhooks/taphashstring header over ordered fields
  2. 02noteDaloyJS routeDaloyJS routeRebuild the hash string, verifyWebhookSignatureHMAC-SHA256 hex, constant-time compare
  3. 03responseDaloyJS routeTap401 when the hash does not match{ error: 'bad hashstring' }
  4. 04asyncDaloyJS routeJob workerenqueue keyed by charge id + status, then 200worker refetches and compares with the order
Recompute the hashstring with Tap's field order and currency rounding, reject mismatches with 401, dedupe on the charge id plus status, then refetch the charge in the worker so a replayed or out-of-order delivery cannot flip an order.
src/webhooks/tap.tsts
import { z } from "zod";
import { readBodyLimited, safeJsonParse, jobIdempotencyKey } from "@daloyjs/core";
import type { TapCharge } from "../plugins/tap.ts";

app.post(
  "/webhooks/tap",
  {
    operationId: "tapWebhook",
    responses: {
      200: { description: "ok", body: z.object({ ok: z.literal(true) }) },
      401: { description: "bad hash", body: z.object({ error: z.string() }) },
    },
  },
  async ({ request, state }) => {
    const raw = new TextDecoder().decode(await readBodyLimited(request, 1_048_576));
    const charge = safeJsonParse(raw) as TapCharge;

    if (!(await state.tap.verifyWebhookHash(charge, request.headers.get("hashstring")))) {
      return { status: 401, body: { error: "bad hashstring" } };
    }

    // Tap sends no event id; a charge id + status pair identifies one state change.
    const key = `${charge.id}:${charge.status}`;
    await app.jobs!.enqueue({
      name: "tap.charge",
      payload: { chargeId: charge.id, status: charge.status },
      idempotencyKey: jobIdempotencyKey({ name: "tap.charge", key }),
    });
    return { status: 200, body: { ok: true as const } };
  },
);
src/jobs/tap.tsts
import type { JobHandler } from "@daloyjs/core";
import { tapClient } from "../plugins/tap.ts";
import { orders } from "../orders.ts";
import { toMinor } from "../money.ts";

export const handleTapCharge: JobHandler<{ chargeId: string }> = async ({ job }) => {
  const charge = await tapClient.getCharge(job.payload.chargeId); // authoritative state
  const orderId = charge.metadata?.orderId ?? charge.reference?.order;
  if (charge.status !== "CAPTURED" || !orderId) return;
  await orders.markPaid(orderId, {
    amountMinor: toMinor(charge.amount, charge.currency),
    currency: charge.currency,
    providerRef: charge.id,
  });
};
// Register it in your single app.useJobs() call (see the payments overview).

6. Refunds

Expose refunds only through a protected refund route. The plugin call, with an idempotent reference per logical refund:

ts
await state.tap.refund({
  chargeId: order.providerRef!,
  amount: Number(formatMinor(amountMinor, order.currency)),
  currency: order.currency,
  reason: "requested_by_customer",
  idempotent: `refund-${order.id}-${order.refundedMinor}-${amountMinor}`,
});

Authorize + capture

For an auth-then-capture flow (hotels, marketplaces, anything where the final amount is decided later), Tap has a separate Authorize API with void and capture operations. Not every payment method supports it; confirm with Tap per scheme before relying on it.

Runtimes

Everything here is fetch (through resilientFetch) plus the core WebCrypto helpers, so the plugin runs unchanged on Node hosts, Deno, Bun, Cloudflare Workers, and Vercel Edge. See the runtime table.

Errors

Tap returns JSON like { "errors": [{ "code": "1101", "description": "..." }] } with an HTTP error status. The plugin keeps the code for your logs; map the failure to a generic problem+json (for example a 502 "Payment provider error") instead of forwarding Tap's description. Common causes are 400 (bad body), 401 (wrong key or test/live mismatch), and 404 (a charge from a different account).

Modernisation notes

  • Use src_all for the hosted page. It saves you from maintaining a method picker and lets Tap roll out new options without a redeploy. If you do offer a method picker, map the user's choice to a server-side allowlist of source ids.
  • Always refetch in the worker. The hash proves the fields came from Tap, but deliveries are retried and can arrive out of order.
  • Never fulfil from the redirect. The ?tap_id= on the return URL is for showing the customer "thanks", never for marking the order paid.
  • Keep buildHashString in one place. If Tap changes the hash inputs you want to update one function, not eight call sites.

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

Edit this page on GitHub

Last updated