DEV Community

Cover image for Charge a Saved Card by API With Manual Capture (Before the Hold Quietly Expires)
Jafar on Payments
Jafar on Payments

Posted on Edited on

Charge a Saved Card by API With Manual Capture (Before the Hold Quietly Expires)

An order arrives from a returning customer whose card is already saved. The stock check won't finish until tomorrow, so you need to reserve the money without collecting it yet.

Auto capture collects the payment immediately, manual capture lets you collect it later, and capture before expiry collects it automatically unless you act first. Choosing between them means deciding what should happen if nobody follows up.

This guide is for developers building checkouts and billing for UK businesses.

Auto capture, manual capture and capture before expiry

The card on file API reference distinguishes three capture types. Choose one according to when the order is ready and what should happen if your team takes no further action.

Capture type What happens Confirmed status Use it when
Auto capture Authorises and captures COMPLETED The amount is final and delivery can proceed
Manual capture Authorises; you capture or cancel later AUTHORIZED until resolved Stock or service checks must happen first
Capture before expiry Authorises; captures before expiry unless you act first AUTHORIZED until resolved Collection should happen unless someone cancels

Manual capture suits an order that needs an explicit decision before collection. Capture before expiry suits an order where collection should go ahead unless someone stops it. Make that choice part of the order workflow so staff know which decision they still need to make.

The initial reply may be PENDING. However, an outright processor refusal returns FAILED immediately, and no failure webhook follows. Handle that reply straight away; otherwise, use a verified webhook, a payment update sent to your server, or a status poll to establish the outcome.

For this API, manual capture and capture-before-expiry authorisations last 7 days. Store each payment's expiresAt rather than calculating the deadline yourself.

A provider job runs every five minutes and captures capture-before-expiry payments in their last five minutes. For manual capture, cancel before expiresAt if the order won't proceed; don't rely on the platform to release it.

When implementing card on file payments, record the customer's agreement alongside the saved card references. A stored card alone doesn't establish permission for every future charge.

Why off-session card charges need care

An off-session charge starts while the customer isn't on your site or app. Remote purchase card fraud losses rose 3% to £423.5 million in 2025, while cases rose 13% to 3.2 million (UK Finance Annual Fraud Report 2026, 15 June 2026). Keep a clear agreement and payment reference so your team can explain each charge.

The FCA says payee-initiated transactions are outside Strong Customer Authentication's scope. A price rise outside the original agreement needs a new mandate, with authentication if arranged remotely (FCA PS21/19, 29 November 2021). Check the agreed amount and purpose before sending a charge.

Words you'll need

  • Saved card: a card stored by the provider; you retain references rather than its number.
  • Authorise: obtain approval and reserve the amount without collecting it.
  • Hold: the reservation that reduces the customer's available balance.
  • Capture: collect the authorised payment.
  • Cancel: request release of the hold. The issuer controls when the available balance recovers, which can take a few days.
  • SCA: Strong Customer Authentication, where the customer proves their identity using two factors, such as possession of their phone and a fingerprint.
  • MIT: merchant-initiated transaction, charged under an earlier agreement.
  • Idempotent: safe to repeat without creating another financial result.

Status names such as AUTHORIZED use the API's spelling.

When SCA applies and when it doesn't

When customers first save their card at checkout, record the amount, timing and purpose they agree to, and complete authentication where required. Later merchant-initiated charges must stay within that agreement.

MIT treatment involves card scheme requirements too. Each charge must be flagged as unscheduled or recurring and use a card saved for that purpose; the provider and processor handle that flagging.

This ad-hoc charge endpoint accepts cards saved through a normal checkout as unscheduled. A card saved as recurring for a subscription is rejected with a 400 response.

A decline isn't permission to keep trying. Card schemes limit retries, and some decline codes prohibit them entirely; check the decline guidance before retrying or asking the customer to authenticate again.

Step by step: charge, wait, then capture or cancel

These Node.js examples use built-in fetch and the linked API's endpoint paths. Database, queue, alerting and signature-verification functions are application adapters you must implement.

1. Save the card with the customer present

Store the provider's customer UUID, its unique customer identifier, and saved payment method ID. On the charge endpoint, customerId means that provider UUID, returned by create-customer, so the example calls it providerCustomerId.

The checkout call uses customerId differently: it holds your merchant reference, with the provider UUID in a separate field. Don't copy that checkout reference into a charge request.

Keep these references connected to the agreement in your own records. Before charging, your application should be able to establish which saved card belongs to the customer and whether the proposed charge falls within the amount, timing and purpose they accepted.

Validate the charge before sending it: orderId is required and must contain 1 to 50 characters, amount is in pounds with a £1 minimum, and optional notes can contain up to 30 characters.

2. Save the order before charging

Idempotency support varies by provider. This charge endpoint ignores an Idempotency-Key header, and repeating an orderId creates another payment request and charge.

Use a unique local orderId and commit its record before calling the provider. A repeated worker must find that record and reconcile it instead of sending another charge.

const API_BASE = process.env.PAYMENTS_API_BASE;
const API_KEY = process.env.PAYMENTS_API_KEY;
const headers = {
  Authorization: "Bearer " + API_KEY,
  "Content-Type": "application/json"
};

async function chargeSavedCard(order) {
  // Atomic insert with a unique orderId; existing orders need reconciliation.
  const created = await db.payments.insertIfAbsent({
    orderId: order.id,
    status: "PENDING",
    paymentRequestId: null
  });
  if (!created) return reconcileOrder(order.id);

  try {
    const res = await fetch(
      API_BASE + "/api/payments/card/process-payment",
      {
        method: "POST",
        headers,
        body: JSON.stringify({
          customerId: order.providerCustomerId,
          paymentMethodId: order.savedCardId,
          captureType: "MANUAL_CAPTURE",
          amount: order.amount,
          orderId: order.id
        })
      }
    );

    if (!res.ok) {
      throw new Error("Charge HTTP " + res.status);
    }

    const reply = await res.json();
    // Patch identifiers only; don't overwrite an earlier webhook's status.
    await db.payments.attachReply(order.id, {
      paymentRequestId: reply.paymentRequestId,
      expiresAt: reply.expiresAt
    });
    await applyStatus({
      orderId: order.id,
      status: reply.status
    });
    return reply;
  } catch (error) {
    await alertOps("Reconcile charge for " + order.id);
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode

After a timeout, check your own payment record or the provider's transactions API for the orderId. Retry only after establishing that no payment exists; an inconclusive lookup needs further reconciliation, not another charge.

A timeout tells you that your application didn't receive a usable answer. It doesn't establish whether the provider received the request or charged the card. Keep the existing order record available for investigation, rather than deleting it to let the next worker start again.

reconcileOrder represents that workflow, not an automatic retry. Keep it mutually exclusive with other workers handling the same order.

Check currency units too. Sending pence to an endpoint expecting pounds can charge 100 times the intended amount.

3. Verify webhooks and move status forwards

A webhook tells your server that a payment changed status. It can arrive before the charge reply, so find the record by the orderId saved before the request.

This provider has two signing schemes: an older signatureHash field inside the JSON body, and a newer HMAC-SHA256 signature over the raw body, sent in a documented signature header as v1=<hex>. The newer scheme uses a shared secret to check that the message is authentic and unchanged. Implement the scheme configured for your account.

const rank = {
  PENDING: 0,
  AUTHORIZED: 1,
  CAPTURE_REQUESTED: 1,
  CANCEL_REQUESTED: 1,
  COMPLETED: 2,
  CANCELLED: 2,
  FAILED: 2
};

async function applyStatus(event) {
  return db.transaction(async function (tx) {
    const payment = await tx.payments.lockByOrderId(event.orderId);
    if (!payment) throw new Error("Unknown payment");

    const nextRank = rank[event.status];
    if (nextRank === undefined) throw new Error("Unknown status");
    if (nextRank <= rank[payment.status]) return;

    await tx.payments.update(event.orderId, {
      status: event.status
    });
    // Durable work recorded in the same transaction.
    if (event.status === "AUTHORIZED") {
      await tx.outbox.add("start-fulfilment", event.orderId);
    }
    if (event.status === "FAILED") {
      await tx.outbox.add("review-decline", event.orderId);
    }
  });
}

// Register before any JSON body parser.
app.post("/webhooks/payments",
  express.raw({ type: "application/json" }),
  async function (req, res) {
    try {
      // Adapter checks the configured signing scheme.
      // Read the signature header your provider documents.
      const event = await verifyAndDecodeWebhook(req.body, req.headers);
      await applyStatus(event);
      res.status(200).end();
    } catch (error) {
      res.status(503).end();
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

The transaction locks the record and stores follow-up work atomically, meaning both changes succeed together. A worker processes that durable work afterwards, preventing a database update from losing its associated task.

The outbox is a stored list of tasks waiting to run. Here, authorisation schedules the order's next step, while failure schedules a decline review. That review still needs to respect the restrictions on retrying declined cards; receiving a failure event doesn't authorise another charge.

Duplicate and older events cannot move status backwards. An unknown payment receives a non-2xx response so delivery can be retried; immediate FAILED replies use the same failure handling.

CAPTURE_REQUESTED and CANCEL_REQUESTED are local bookkeeping states, not provider statuses. A later verified webhook or status poll replaces them with a terminal outcome, meaning the payment has completed, failed or been cancelled.

4. Capture or cancel

Both actions work only while the provider payment is AUTHORIZED. Repeating the same action cannot move money twice: an "already captured" or "already cancelled" error confirms the action already happened.

async function postAction(paymentRequestId, action, body) {
  const path = "/api/payments/card/payment-request/" +
    encodeURIComponent(paymentRequestId) + "/" + action;

  const res = await fetch(API_BASE + path, {
    method: "POST",
    headers,
    body: JSON.stringify(body || {})
  });
  const text = await res.text();
  const alreadyDone = action === "capture"
    ? /\balready captured\b/i.test(text)
    : /\balready cancelled\b/i.test(text);

  if (!res.ok && !alreadyDone) {
    throw new Error(action + " HTTP " + res.status);
  }
}

function capturePayment(id) {
  return postAction(id, "capture");
}

function cancelPayment(id, reason, description) {
  const body = { cancelledReasonCode: reason };
  if (reason === "Other") {
    if (!description) throw new Error("Cancellation description required");
    body.cancelledReasonDescription = description;
  }
  return postAction(id, "cancel", body);
}
Enter fullscreen mode Exit fullscreen mode

Match only the corresponding already-completed action, and confirm its status through reconciliation. An already-cancelled payment isn't a successful capture.

Cancellation reasons are Duplicate, Abandoned, Requested by customer and Other. The last also requires cancelledReasonDescription.

Partial capture isn't supported: the capture endpoint takes no amount. If the final amount changes, cancel the hold and charge the new amount within the customer's agreement. After capture, returning money requires a refund.

When explaining cancellation to a customer, distinguish your request from their issuer's release of the hold. Your application can record that cancellation was requested without promising that the available balance has already recovered.

5. Sweep holds before they expire

Use a scheduled job to review approaching deadlines. This example uses a 24-hour window, stores successful action requests and isolates each hold's failure.

async function sweepExpiringHolds() {
  const windowEnd = new Date(
    Date.now() + 24 * 60 * 60 * 1000
  ).toISOString();

  const holds = await db.payments.find({
    status: "AUTHORIZED",
    expiresBefore: windowEnd
  });

  for (const hold of holds) {
    try {
      const order = await db.orders.get(hold.orderId);
      let requestedStatus;

      if (order.status === "ready") {
        await capturePayment(hold.paymentRequestId);
        requestedStatus = "CAPTURE_REQUESTED";
      } else if (order.status === "cancelled") {
        await cancelPayment(hold.paymentRequestId, "Abandoned");
        requestedStatus = "CANCEL_REQUESTED";
      } else {
        await alertOps("Review expiry for " + hold.orderId);
        continue;
      }

      // Conditional update preserves any terminal webhook already received.
      await db.payments.updateIfStatus(
        hold.orderId, "AUTHORIZED", { status: requestedStatus }
      );
    } catch (error) {
      await alertOps("Hold action failed for " + hold.orderId);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Make the alert adapter durable and ensure it doesn't throw through the loop. Reconcile requested states afterwards so a missing webhook doesn't leave them unresolved.

Give the person receiving an expiry alert enough information to act: the order reference, current order decision and stored deadline. An alert needs an owner who can decide to capture or cancel before expiry; leaving it unread doesn't resolve the hold.

Mistakes to avoid

  • Treating PENDING as paid. AUTHORIZED reserves funds; COMPLETED confirms collection.
  • Blindly retrying charges. Check for an existing payment first. Repeating orderId doesn't prevent duplicates.
  • Waiting for a FAILED webhook after outright refusal. Handle the reply immediately.
  • Assuming a hold cancels itself safely. Cancel unwanted manual holds before expiry.
  • Forgetting automatic capture. Capture before expiry collects unless you intervene.
  • Retrying declines in a loop. Respect scheme limits and decline-specific restrictions.
  • Charging outside the agreement. Obtain fresh consent and authentication where required.
  • Storing card numbers. Retain provider references instead.

Checklist

  • Confirm consent and an eligible unscheduled saved card.
  • Validate provider UUID, pounds and field limits.
  • Save a unique order record before charging.
  • Handle immediate failure and uncertain charge outcomes.
  • Verify raw webhook bodies and apply forward-only updates.
  • Store expiry, sweep holds and reconcile requested actions.
  • Test duplicate, early and out-of-order webhooks.

Conclusion

Manual capture gives you time to confirm an order, but you must manage the hold and resolve uncertain outcomes. Before enabling it, test a charge timeout, an immediate refusal and an approaching expiry so each leads to a recorded decision.

Top comments (0)