Skip to content

Search docs

Jump between documentation pages.

Browse docs

Accept cards with Authorize.Net in DaloyJS

Authorize.Net (a Visa / Cybersource brand) is one of the original US card gateways. This guide uses the official authorizenet Node SDK to charge cards via the Authorize.Net API, and the separate JSON Webhooks REST API to receive event notifications.

What you should know up front

  • It's a thin wrapper with callbacks. Requests are built with APIContracts.* classes and sent with APIControllers.* controllers that expose .execute(callback). We wrap that once in a Promise.
  • Don't POST raw card numbers from a browser. Use Accept.js or Accept Hosted to tokenise the card into an opaqueData nonce. Sending raw PANs through your server puts you in full PCI DSS SAQ D scope.
  • The amount comes from your order. The browser sends the nonce and an order id. See never trust client amounts.
  • Use duplicateWindow. The duplicateWindow transaction setting (in seconds, up to 28800) makes the gateway reject a repeat of the same transaction inside the window, a useful backstop for retries.
  • Webhooks are a separate API, signed with HMAC-SHA512 using a dedicated Signature Key (not the Transaction Key) in the X-ANET-Signature header.

1. Provision

  1. Create a sandbox account and copy your API Login ID and Transaction Key from Account -> Settings -> Security Settings -> API Credentials and Keys.
  2. On the same screen, generate a Signature Key. You'll need it to verify webhook signatures.
  3. When you're ready for production, repeat with a live account and swap endpoint.sandbox for endpoint.production.

2. Install

bash
pnpm add authorizenet
bash
pnpm add -D @types/authorizenet

The authorizenet package ships no TypeScript declarations; the community @types/authorizenet package on DefinitelyTyped provides them and is not exhaustive, so expect a few local casts for newer fields.

3. Environment variables

.envbash
AUTHNET_ENVIRONMENT=sandbox          # or "production"
AUTHNET_API_LOGIN_ID=use_your_api_login_id
AUTHNET_TRANSACTION_KEY=use_your_transaction_key
AUTHNET_SIGNATURE_KEY=use_your_signature_key   # from the merchant interface

4. Plugin

src/plugins/authorizenet.tsts
import { APIContracts as ApiContracts, APIControllers as ApiControllers, Constants as SDKConstants } from "authorizenet";
import { verifyWebhookSignature } from "@daloyjs/core";
import type { App } from "@daloyjs/core";

const endpoint =
  process.env.AUTHNET_ENVIRONMENT === "production"
    ? SDKConstants.endpoint.production
    : SDKConstants.endpoint.sandbox;

function merchantAuth() {
  const auth = new ApiContracts.MerchantAuthenticationType();
  auth.setName(process.env.AUTHNET_API_LOGIN_ID!);
  auth.setTransactionKey(process.env.AUTHNET_TRANSACTION_KEY!);
  return auth;
}

// Centralise the callback-to-promise wrapping in one place.
function runController(controller: {
  setEnvironment(url: string): void;
  execute(cb: () => void): void;
  getResponse(): unknown;
}): Promise<unknown> {
  controller.setEnvironment(endpoint);
  return new Promise((resolve) => {
    controller.execute(() => resolve(controller.getResponse()));
  });
}

export interface AuthorizeNetClient {
  chargeOpaqueData(input: {
    amount: string;          // "10.00", from your order
    dataDescriptor: string;  // e.g. "COMMON.ACCEPT.INAPP.PAYMENT"
    dataValue: string;       // Accept.js nonce
    invoiceNumber: string;   // your order id (the field allows up to 20 characters)
    customerIp?: string;
  }): Promise<{ transId: string; authCode: string; accountNumber: string }>;
  verifyWebhook(rawBody: Uint8Array, signatureHeader: string | null): Promise<boolean>;
}

function buildSaleRequest(input: Parameters<AuthorizeNetClient["chargeOpaqueData"]>[0]) {
  const opaque = new ApiContracts.OpaqueDataType();
  opaque.setDataDescriptor(input.dataDescriptor);
  opaque.setDataValue(input.dataValue);

  const payment = new ApiContracts.PaymentType();
  payment.setOpaqueData(opaque);

  const order = new ApiContracts.OrderType();
  order.setInvoiceNumber(input.invoiceNumber);

  // Reject a repeat of the same transaction for 10 minutes (max 28800 seconds).
  const duplicateWindow = new ApiContracts.SettingType();
  duplicateWindow.setSettingName("duplicateWindow");
  duplicateWindow.setSettingValue("600");
  const settings = new ApiContracts.ArrayOfSetting();
  settings.setSetting([duplicateWindow]);

  const tx = new ApiContracts.TransactionRequestType();
  tx.setTransactionType(ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
  tx.setPayment(payment);
  tx.setAmount(input.amount);
  tx.setOrder(order);
  tx.setTransactionSettings(settings);
  if (input.customerIp) tx.setCustomerIP(input.customerIp);

  const req = new ApiContracts.CreateTransactionRequest();
  req.setMerchantAuthentication(merchantAuth());
  req.setTransactionRequest(tx);
  return req;
}

// Exported so job handlers (which run outside a request) can use it too.
export const authorizeNetClient: AuthorizeNetClient = {
  async chargeOpaqueData(input) {
    const req = buildSaleRequest(input);
    const controller = new ApiControllers.CreateTransactionController(req.getJSON());
    const raw = (await runController(controller)) as Record<string, unknown>;
    const response = new ApiContracts.CreateTransactionResponse(raw);

    const messages = response.getMessages();
    if (messages?.getResultCode() !== ApiContracts.MessageTypeEnum.OK) {
      const first = messages?.getMessage()?.[0];
      throw Object.assign(new Error("Authorize.Net request failed"), { code: first?.getCode() });
    }

    const txResp = response.getTransactionResponse();
    // responseCode "1" = approved. 2 declined, 3 error, 4 held for review.
    if (!txResp || txResp.getResponseCode() !== "1") {
      const err = txResp?.getErrors()?.getError()?.[0];
      throw Object.assign(new Error("Transaction not approved"), {
        code: err?.getErrorCode() ?? "DECLINED",
        transId: txResp?.getTransId(),
      });
    }

    return {
      transId: txResp.getTransId(),
      authCode: txResp.getAuthCode(),
      accountNumber: txResp.getAccountNumber(),
    };
  },

  async verifyWebhook(rawBody, signatureHeader) {
    if (!signatureHeader) return false;
    // Header looks like "sha512=ABCDEF...": the core helper strips the matching
    // prefix, accepts upper- or lowercase hex, and compares in constant time.
    return verifyWebhookSignature({
      payload: rawBody,
      signature: signatureHeader,
      secret: process.env.AUTHNET_SIGNATURE_KEY!,
      algorithm: "sha512",
    });
  },
};

// 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 authorizeNetPlugin(app: App) {
  app.decorate("authnet", authorizeNetClient);
}

declare module "@daloyjs/core" {
  interface AppState {
    authnet: AuthorizeNetClient;
  }
}

Why req.getJSON()? The controllers want a serialised JSON snapshot of the request graph. It's an awkward shape; that's the SDK, not a typo.

5. Charge an Accept.js nonce

Your frontend obtains an opaqueData nonce with Accept.js (dataDescriptor: "COMMON.ACCEPT.INAPP.PAYMENT" for browser-side Accept, or the Apple Pay / Google Pay descriptors for wallets). Your server only ever sees the nonce. The route relies on the shared app wiring, including behindProxy, and the overview's orders and money modules.

src/routes/checkout-authorizenet.tsts
import { z } from "zod";
import { resolveClientIp } from "@daloyjs/core";
import { authorizeNetPlugin } from "../plugins/authorizenet.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 })

authorizeNetPlugin(app);

app.post(
  "/checkout/authorizenet",
  {
    operationId: "checkoutAuthorizeNet",
    request: {
      body: z.object({
        orderId: z.string().min(1).max(20),
        dataDescriptor: z.enum(["COMMON.ACCEPT.INAPP.PAYMENT", "COMMON.APPLE.INAPP.PAYMENT", "COMMON.GOOGLE.INAPP.PAYMENT"]),
        dataValue: z.string().min(1).max(8_192),
      }).strict(),
    },
    responses: {
      201: {
        description: "approved",
        body: z.object({ transId: z.string(), last4: z.string() }),
      },
    },
  },
  async ({ body, request, state }) => {
    const order = await orders.forCheckout(body.orderId, state.session.get<string>("userId"));
    const result = await state.authnet.chargeOpaqueData({
      amount: formatMinor(order.amountMinor, order.currency), // server-side total
      dataDescriptor: body.dataDescriptor,
      dataValue: body.dataValue,
      invoiceNumber: order.id,
      // Only trusts X-Forwarded-For hops that behindProxy declares; undefined when unknown.
      customerIp: resolveClientIp(request, BEHIND_PROXY),
    });
    return {
      status: 201,
      body: { transId: result.transId, last4: result.accountNumber.replace(/^X+/, "") },
    };
  },
);

Refunds, voids, and prior-auth captures go through the same CreateTransactionController with a different transactionType (refundTransaction, voidTransaction, priorAuthCaptureTransaction) plus a refTransId. Expose refunds only through a protected refund route.

6. Subscribe to webhooks

Webhooks aren't in the transaction SDK. Use the REST API with HTTP Basic auth (API Login ID + Transaction Key), once per environment, usually as a script or admin endpoint, not on every boot:

scripts/authnet-subscribe.tsts
const host =
  process.env.AUTHNET_ENVIRONMENT === "production"
    ? "https://api.authorize.net"
    : "https://apitest.authorize.net";

const basic = btoa(`${process.env.AUTHNET_API_LOGIN_ID}:${process.env.AUTHNET_TRANSACTION_KEY}`);

await fetch(`${host}/rest/v1/webhooks`, {
  method: "POST",
  headers: { "Content-Type": "application/json", Authorization: `Basic ${basic}` },
  body: JSON.stringify({
    name: "Acme webhooks",
    url: "https://api.acme.com/webhooks/authorizenet",
    eventTypes: [
      "net.authorize.payment.authcapture.created",
      "net.authorize.payment.refund.created",
      "net.authorize.payment.void.created",
    ],
    status: "active",
  }),
});

7. Verify webhook deliveries

Webhook verification
Authorize.NetDaloyJS routeJob worker
  1. 01requestAuthorize.NetDaloyJS routePOST /webhooks/authorizenetX-ANET-Signature: sha512=... over raw body
  2. 02noteDaloyJS routeDaloyJS routeverifyWebhookSignature, algorithm sha512Signature Key, constant-time compare
  3. 03responseDaloyJS routeAuthorize.Net401 when the digest does not match{ error: 'invalid signature' }
  4. 04asyncDaloyJS routeJob workerenqueue keyed by notificationId, then 200worker fetches the full transaction
Hash the raw bytes with the Signature Key before parsing, reject mismatches with 401, dedupe atomically on notificationId, then let the worker fetch the full record.

Authorize.Net's docs state that the hash is HMAC-SHA512 over the notification body with your Signature Key, sent in X-ANET-Signature. They do not spell out the header format or key encoding; in practice the header is sha512= followed by uppercase hex, and the key is used as the string from the merchant interface. Confirm with the sandbox Test Webhook button before going live.

src/webhooks/authorizenet.tsts
import { z } from "zod";
import { readBodyLimited, safeJsonParse, jobIdempotencyKey } from "@daloyjs/core";

app.post(
  "/webhooks/authorizenet",
  {
    operationId: "authorizenetWebhook",
    responses: {
      200: { description: "ack", body: z.object({ ok: z.literal(true) }) },
      401: { description: "bad signature", body: z.object({ error: z.string() }) },
    },
  },
  async ({ request, state }) => {
    const raw = await readBodyLimited(request, 1_048_576);
    if (!(await state.authnet.verifyWebhook(raw, request.headers.get("x-anet-signature")))) {
      return { status: 401, body: { error: "invalid signature" } };
    }

    const event = safeJsonParse(new TextDecoder().decode(raw)) as {
      notificationId: string;
      eventType: string;
      payload: { entityName: string; id: string };
    };

    // Payloads are intentionally minimal; the worker calls getTransactionDetailsRequest.
    await app.jobs!.enqueue({
      name: "authnet.notification",
      payload: { notificationId: event.notificationId, eventType: event.eventType, entityId: event.payload.id },
      idempotencyKey: jobIdempotencyKey({ name: "authnet.notification", key: event.notificationId }),
    });
    return { status: 200, body: { ok: true as const } };
  },
);

Ack fast: Authorize.Net retries failed deliveries over a long schedule and eventually marks a failing webhook inactive. The worker fetches the transaction with getTransactionDetailsRequest, compares the settled amount with the stored order, and updates your ledger idempotently (see the webhook pattern).

Errors & result objects

There are two layers of failure. The outer messages block reports request-level errors (auth, schema, throttling). When that's OK, the inner transactionResponse can still have a responseCode of 2 (decline), 3 (error), or 4 (held for review). The plugin collapses both into thrown errors carrying the gateway codes for your logs; route them through problem+json with your own message.

Runtimes

The SDK is built on axios plus file-based logging dependencies and runs on Node hosts: long-lived Node, Vercel Node.js functions, AWS Lambda, and Azure Functions. It is not suited to Cloudflare Workers or Vercel Edge; there, POST the JSON API (https://api.authorize.net/xml/v1/request.api, or the apitest host) directly with fetch. Deno is not verified. See the runtime table.

Modernisation notes

  • Use transHashSha2, not transHash. The MD5-based transHash is being phased out.
  • No built-in retry. If you need it, wrap runController with your own back-off on transient network errors only, never on declines, and keep duplicateWindow set so a retried charge cannot go through twice.
  • Prefer Customer Profiles for repeat business. Vault the card into a customer payment profile on first charge, then bill later transactions by profile id.

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

Edit this page on GitHub

Last updated