Typescript

@ecompaymentskw/typescript-sdk

Server-side TypeScript SDK for Ecom Payments E_API, E_LINKS, refunds, and
webhook verification. Requires Node.js 18 or newer.

Install

npm install @ecompaymentskw/typescript-sdk

Configure

import { Ecom } from "@ecompaymentskw/typescript-sdk";

const ecom = new Ecom({
  apiToken: process.env.ECOM_API_TOKEN!,
  merchantId: process.env.ECOM_MID!,
  environment: "sandbox", // or "production"
});

Keep the API token and webhook secret on your server. Do not expose them in
browser code.

E_API charges

const charge = await ecom.eApi.createCharge({
  amount: { value: 10, currency: "KWD" },
  options: { mode: "INDIRECT", paymentMethod: "KNET" },
  urls: {
    successUrl: "https://example.com/payment/success",
    errorUrl: "https://example.com/payment/error",
  },
  customer: {
    fullName: "Ali",
    phoneCode: "+965",
    phoneNumber: "66778899",
  },
  language: "en",
});

console.log(charge.paymentUrl);

const details = await ecom.eApi.getCharge(charge.paymentToken);

E_LINKS invoices

const invoice = await ecom.eLinks.createInvoice({
  amount: { value: 25, currency: "KWD" },
  customer: {
    fullName: "Ali",
    phoneCode: "+965",
    phoneNumber: "66778899",
    email: "[email protected]",
  },
  notification: { email: true, sms: true },
  language: "en",
});

const page = await ecom.eLinks.listInvoices({
  page: 1,
  take: 10,
  order: "DESC",
});

await ecom.eLinks.sendInvoiceReminder(invoice.id, { email: true });
await ecom.eLinks.markInvoiceAsPaid(invoice.id, {
  paymentMethod: "CASH",
  notes: "Paid at the store",
});

Other invoice methods are getInvoice, getInvoiceByPaymentToken, and
deleteInvoice.

Refunds

const refund = await ecom.refunds.createRefund({
  amount: 5,
  ecomId: details.id,
  merchantReference: "refund-order-123",
});

const refunds = await ecom.refunds.listRefunds({
  page: 1,
  take: 10,
  order: "DESC",
});

const refundDetails = await ecom.refunds.getRefund(refund.id);

Webhooks

Verify the event's data object against the X-Webhook-Signature header:

import type { WebhookEvent } from "@ecompaymentskw/typescript-sdk";

function handleWebhook(
  event: WebhookEvent,
  signature: string,
  webhookSecret: string,
) {
  if (!ecom.webhooks.verifySignature(event.data, signature, webhookSecret)) {
    throw new Error("Invalid Ecom webhook signature");
  }

  switch (event.eventType) {
    case "TRANSACTION_STATUS_CHANGED":
      console.log(event.data.paymentStatus);
      break;
    case "REFUND_STATUS_CHANGED":
      console.log(event.data.status);
      break;
  }
}

generateSignature(data, secret) is also exported for testing.

Errors

Non-successful responses throw EcomApiError:

import { EcomApiError } from "@ecompaymentskw/typescript-sdk";

try {
  await ecom.eApi.getCharge("payment-token");
} catch (error) {
  if (error instanceof EcomApiError) {
    console.error(error.status, error.apiError, error.message, error.body);
  }
}