<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Jafar on Payments]]></title><description><![CDATA[Jafar on Payments]]></description><link>https://jafaronpayments.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 19:41:07 GMT</lastBuildDate><atom:link href="https://jafaronpayments.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Test Payment Webhooks From the CLI Before a Real Customer Finds the Bug]]></title><description><![CDATA[You've just changed the code that marks orders as paid, and you need to know it still copes when a payment fails, a card is only authorised or a refund…]]></description><link>https://jafaronpayments.hashnode.dev/how-to-test-payment-webhooks-from-the-cli-before-a-real-customer-finds-the-bug</link><guid isPermaLink="true">https://jafaronpayments.hashnode.dev/how-to-test-payment-webhooks-from-the-cli-before-a-real-customer-finds-the-bug</guid><category><![CDATA[cli]]></category><category><![CDATA[Testing]]></category><category><![CDATA[webhooks]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Jafar Sadhik]]></dc:creator><pubDate>Fri, 13 Nov 2026 12:05:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aec4e93449bd9c91a9afe84/02118b90-e457-4e73-bfb4-2b34d1cf380c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've just changed the code that marks orders as paid, and you need to know it still copes when a payment fails, a card is only authorised or a refund bounces. Making a real sandbox payment for each case means opening a checkout, picking a test bank and clicking through, again and again.</p>
<p>If you build payment integrations for UK businesses, a payments CLI turns each of those cases into one command. This post shows how to fire synthetic webhook events from the terminal, check requests with a dry run, read JSON output in scripts and run the same tests in CI.</p>
<h2>Why webhook testing matters</h2>
<p>A webhook is an HTTP request your payment provider sends to your server when something changes, such as a payment completing or a refund failing. Your code reacts by shipping an order, emailing a receipt or updating your books.</p>
<p>The Standard Webhooks specification describes delivery as "at least once": the same event can arrive more than once, so your handler has to cope with repeats (Standard Webhooks specification). If you only ever test the happy path, the first duplicate or failed event you see will be in production.</p>
<p>The volume is growing too. There were 351 million open banking payments in the UK in 2025, up 57% on 2024 (Open Banking Limited). <a href="https://paywithatoa.com/gb/blog/how-pay-by-bank-in-the-travel-industry-is-transforming-customer-payments">Pay by Bank</a> payments bring their own statuses, such as a payment that expires because the customer never approved it in their bank app, and each one needs a tested code path.</p>
<h2>Ways to test a webhook handler</h2>
<table>
<thead>
<tr>
<th align="left">Method</th>
<th align="left">What it tests</th>
<th align="left">Speed</th>
<th align="left">What it catches</th>
</tr>
</thead>
<tbody><tr>
<td align="left">Unit test with a saved JSON payload</td>
<td align="left">Your parsing and business logic</td>
<td align="left">Fastest</td>
<td align="left">Logic bugs</td>
</tr>
<tr>
<td align="left">Synthetic event from a CLI</td>
<td align="left">Your live endpoint: routing, auth, signature check and response</td>
<td align="left">Seconds</td>
<td align="left">Config and wiring bugs</td>
</tr>
<tr>
<td align="left">Real sandbox payment</td>
<td align="left">The full flow, including checkout and redirects</td>
<td align="left">Minutes</td>
<td align="left">Gaps between a synthetic payload and a real one</td>
</tr>
</tbody></table>
<p>You want all three. The CLI fills the gap in the middle: it hits your real endpoint over the internet, signed the way the provider signs real events, without you creating a payment.</p>
<h2>What a payments CLI gives you</h2>
<p>A payments CLI (command-line interface) is a program you run in the terminal to call your provider's API. The useful ones for testing share a few features:</p>
<ul>
<li><strong>Sandbox and production kept apart.</strong> The sandbox is a test copy of the live system where no real money moves. Each environment has its own keys, and a sandbox key won't work in production.</li>
<li><strong>Synthetic webhook events.</strong> A "trigger" command sends a fake but correctly shaped event to the sandbox URL you registered. Good CLIs make this sandbox-only by design, so you can't fire fake events at live customers.</li>
<li><strong>Dry run.</strong> A --dryRun flag builds the request and shows it without sending it.</li>
<li><strong>JSON output.</strong> An --output json flag gives machine-readable results instead of a table, which scripts and jq can read.</li>
<li><strong>Exit codes.</strong> Each type of failure returns a different number, so a pipeline can react differently to a bad token and a network blip.</li>
</ul>
<p>For example, <a href="https://docs.paywithatoa.com/cli">a payments CLI</a> for UK Pay by Bank and card payments documents exit code 2 for auth failures, 3 for bad input, 5 for rate limits and 6 for network errors. Flag names vary between tools, so check --help on yours. The commands below use paycli as a stand-in name.</p>
<h2>Step by step: test your webhooks from the terminal</h2>
<h3>1. Log in and create a sandbox key</h3>
<pre><code class="language-bash">paycli login                      # opens your browser to approve the session
paycli keys create --env sandbox  # an API key for sandbox payment commands
paycli whoami                     # confirm the account and profile
</code></pre>
<p>Logging in through the browser means you never paste a secret into your shell history.</p>
<h3>2. Register a sandbox webhook URL</h3>
<p>Point the provider at an endpoint it can reach. For local work, that's a tunnel to your laptop or a request inspector that shows you the raw request.</p>
<pre><code class="language-bash">paycli webhooks create --url https://your-tunnel.example.com/webhooks/payments --event PAYMENTS_STATUS
paycli webhooks create --url https://your-tunnel.example.com/webhooks/refunds --event REFUND_STATUS
paycli webhooks list --output json
</code></pre>
<h3>3. Fire one event per status</h3>
<p>Run every status your handler claims to support, not just the successful one.</p>
<pre><code class="language-bash"># Pay by Bank payment completed
paycli webhooks trigger PAYMENTS_STATUS --status COMPLETED --orderId test-001 --amount 25.00

# Pay by Bank payment failed
paycli webhooks trigger PAYMENTS_STATUS --status FAILED --orderId test-002

# Card payment authorised but not captured yet
paycli webhooks trigger PAYMENTS_STATUS --paymentMethod CARD --status AUTHORIZED --orderId test-003

# Customer never approved the payment in time
paycli webhooks trigger EXPIRED_STATUS --orderId test-004

# Refund failed at the customer's bank
paycli webhooks trigger REFUND_STATUS --status FAILED --orderId test-005
</code></pre>
<p>After each one, check three things in your logs: the signature check passed, the right code path ran, and your endpoint answered with a 2xx status quickly.</p>
<h3>4. Fire the same event twice</h3>
<p>Run the COMPLETED trigger for test-001 again. Your handler should spot that the order is already paid and do nothing. If you see two confirmation emails or two stock deductions, your handler isn't idempotent (safe to run twice with only one result).</p>
<p>Retries use exponential back-off, so a FAILED or EXPIRED event can arrive after COMPLETED. Check each event against the stored order status and accept only a forward move, with COMPLETED, FAILED and EXPIRED all treated as terminal statuses.</p>
<p>A simple guard in Node.js looks like this:</p>
<pre><code class="language-javascript">const STATUS_RANK = {
  PENDING: 0,
  AUTHORIZED: 1,
  COMPLETED: 2,
  FAILED: 2,
  EXPIRED: 2
};

async function handlePaymentEvent(event) {
  return db.transaction(async (tx) =&gt; {
    const order = await tx.orders.findForUpdate(event.orderId);
    if (!order) {
      return 503; // ask the provider to retry later
    }

    const currentRank = STATUS_RANK[order.status];
    const incomingRank = STATUS_RANK[event.status];

    if (currentRank === undefined || incomingRank === undefined) {
      return 400;
    }
    if (order.status === "COMPLETED" || incomingRank &lt;= currentRank) {
      return 204; // duplicate, older event or another terminal status
    }

    const key = event.orderId + ":" + event.status;
    const isNew = await tx.processedEvents.insertIfAbsent(key);
    if (!isNew) {
      return 204;
    }

    if (event.status === "COMPLETED") {
      await tx.orders.markPaid(event.orderId);
    }
    if (event.status === "FAILED" || event.status === "EXPIRED") {
      await tx.orders.releaseStock(event.orderId);
    }
    await tx.orders.setStatus(event.orderId, event.status);
    return 204;
  });
}
</code></pre>
<p>These database methods are application helpers: implement the row lock, duplicate guard, stock changes and stored status update in one transaction. insertIfAbsent should rely on a unique constraint in your database, so two deliveries landing at the same moment can't both get through.</p>
<p>Have your HTTP handler send the returned status code. For an order it doesn't know yet, return a non-2xx response, because only non-2xx responses are retried, as described in the provider's webhook introduction.</p>
<p>Trigger COMPLETED then FAILED for the same orderId and confirm the order stays COMPLETED and stock is not released.</p>
<h3>5. Check requests with a dry run and JSON output</h3>
<p>Before you script anything that creates payments or refunds, look at exactly what would be sent:</p>
<pre><code class="language-bash">paycli payments create --amount 1.00 --orderId dry-001 --customerId cust-test --dryRun --output json
</code></pre>
<p>Then read real results as JSON, never by scraping the table view:</p>
<pre><code class="language-bash">paycli payments transactions --status COMPLETED --output json | jq '.[0]'
</code></pre>
<h3>6. Run it in CI</h3>
<p>CI runners can't open a browser, so you can't log in there. Log in once on a workstation, copy the CLI's credentials folder into your CI secret store, and point the runner at it with the CLI's home directory variable. Use a dedicated CI profile with a sandbox-only key.</p>
<p>A small Node.js script can then run the triggers and branch on the exit codes:</p>
<pre><code class="language-javascript">const { spawnSync } = require("child_process");

const REASONS = {
  2: "auth failed: the CI key was revoked or has expired",
  5: "rate limited: wait before re-running",
  6: "network error: safe to re-run"
};

function trigger(status, orderId) {
  const result = spawnSync("paycli", [
    "--profile", "ci", "webhooks", "trigger", "PAYMENTS_STATUS",
    "--status", status, "--orderId", orderId, "--output", "json"
  ], { encoding: "utf8" });

  if (result.status !== 0) {
    const reason = REASONS[result.status] || "exit code " + result.status;
    throw new Error("Trigger " + status + " failed, " + reason);
  }
  return JSON.parse(result.stdout);
}

const runId = process.env.RUN_ID;
trigger("COMPLETED", "ci-" + runId + "-completed");
trigger("FAILED", "ci-" + runId + "-failed");
</code></pre>
<p>After the triggers, have the same script ask your app what it recorded for each order, and exit with a non-zero code if a status isn't what you expected, so the pipeline fails.</p>
<p>If the pipeline creates anything, such as a sandbox payment or refund, pass a stable idempotency key built from the run ID, for example --idempotencyKey "ci-refund-$RUN_ID". Keep that key stable for the CLI, but don't rely on server-side deduplication: the REST API reference documents no idempotency header. After a restarted job, check the sandbox order or refund list for that orderId before creating it again.</p>
<p>The same tests apply to a custom checkout and to off-the-shelf <a href="https://paywithatoa.com/gb/integrations">payment integrations</a> for Shopify, WooCommerce or Xero, because each one reacts to the same status events.</p>
<h2>Mistakes to avoid</h2>
<ul>
<li><strong>Testing only COMPLETED.</strong> Failed, expired and authorised events are where the bugs live.</li>
<li><strong>Never testing duplicates.</strong> Delivery is at least once, so fire every event twice.</li>
<li><strong>Treating a synthetic event as the whole truth.</strong> It matches the real shape, but run at least one real sandbox payment end to end before you ship.</li>
<li><strong>Parsing table output.</strong> Use --output json, because table layouts can change between versions.</li>
<li><strong>Random idempotency keys in CI.</strong> Build a stable CLI key from the run ID, but don't assume it prevents duplicates on the server. After a restarted job, check the sandbox order or refund list for that orderId before creating it again.</li>
<li><strong>Committing CLI credentials.</strong> Keep them in your CI secret store, use a sandbox-only key and revoke it when you rotate.</li>
<li><strong>Pointing tests at production.</strong> Keep a separate CI profile that only holds a sandbox key.</li>
<li><strong>Ignoring exit codes.</strong> Retrying straight away on a rate limit can extend the block, so branch on the code.</li>
</ul>
<h2>Conclusion</h2>
<p>Webhooks are delivered at least once (Standard Webhooks specification) and open banking payments grew 57% in 2025 (Open Banking Limited), so more of your traffic will be events you haven't tested yet. A payments CLI lets you fire every status, twice, at your real endpoint in seconds. Your next step: write a script that triggers each status your handler supports and run it on every pull request.</p>
]]></content:encoded></item><item><title><![CDATA[How to Set Spending Limits for AI Agent Payments (Before Your Agent Overspends)]]></title><description><![CDATA[Giving an AI agent your payment API key is a bit like giving a new intern the company card with no limit and hoping for the best. Most days it's fine. The…]]></description><link>https://jafaronpayments.hashnode.dev/how-to-set-spending-limits-for-ai-agent-payments-before-your-agent-overspends</link><guid isPermaLink="true">https://jafaronpayments.hashnode.dev/how-to-set-spending-limits-for-ai-agent-payments-before-your-agent-overspends</guid><category><![CDATA[ai agents]]></category><category><![CDATA[payments]]></category><category><![CDATA[Security]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Jafar Sadhik]]></dc:creator><pubDate>Thu, 05 Nov 2026 15:03:51 GMT</pubDate><content:encoded><![CDATA[<p>Giving an AI agent your payment API key is a bit like giving a new intern the company card with no limit and hoping for the best. Most days it's fine. The one day it isn't, it's expensive.</p>
<p>If you're building an AI agent that books, buys or pays suppliers, this guide explains how to give it real spending limits, with code you can adapt.</p>
<h2>Why this matters now</h2>
<p>AI agents that pay are no longer just demos:</p>
<ul>
<li>In April 2025, Visa launched Visa Intelligent Commerce and Mastercard launched Agent Pay, both built so AI agents can pay on a person's behalf.</li>
<li>In September 2025, Google published its Agent Payments Protocol (AP2), which uses signed "mandates" to record exactly what a person has allowed an agent to buy.</li>
<li>McKinsey estimates agentic commerce could reach $3 trillion to $5 trillion globally by 2030 (McKinsey, October 2025).</li>
</ul>
<p>More agents moving money means more need for limits that actually hold.</p>
<h2>What an agent payment is</h2>
<p>An agent payment is when software, not a person, starts a payment. The person sets the goal, like "book the cheapest train" or "pay this month's supplier invoices", and the agent does the steps.</p>
<p>That can mean collecting money from customers or sending money to suppliers. Either way, someone has to decide in advance how far the agent is allowed to go.</p>
<h2>Why a limit in the prompt isn't a real limit</h2>
<p>Telling the model "never spend more than £500" is an instruction, not a rule. Models can misread instructions, make mistakes, or be tricked by text hidden in a web page or email. That last one is called prompt injection, and it's one of the biggest risks for agents that act on their own.</p>
<p>A real limit has to live somewhere the model can't change.</p>
<h2>Put the limit where the money moves</h2>
<p>The safest place for a limit is the system that actually moves the money. It checks every payment against what a person approved, after the agent asks and before any money leaves.</p>
<p>A good spending limit has four parts:</p>
<ul>
<li>a maximum amount per payment</li>
<li>a maximum amount per day, week or month</li>
<li>an end date, after which the permission stops</li>
<li>a direction: money in (collecting) or money out (sending)</li>
</ul>
<p>Here's what that check looks like if you build it yourself, in TypeScript:</p>
<pre><code class="language-ts">type Direction = "COLLECT" | "SEND";

type SpendLimit = {
  maxPerPayment: number; // in pounds
  maxPerMonth: number;
  validTo: Date;
  direction: Direction;
};

function checkPayment(
  limit: SpendLimit,
  amount: number,
  spentThisMonth: number,
  direction: Direction
): void {
  if (new Date() &gt; limit.validTo) throw new Error("Permission has expired");
  if (direction !== limit.direction) throw new Error("Payment is going the wrong way");
  if (amount &gt; limit.maxPerPayment) throw new Error("Over the per-payment limit");
  if (spentThisMonth + amount &gt; limit.maxPerMonth) throw new Error("Over the monthly limit");
}
</code></pre>
<p>The important part is where this runs: on your server, between the agent's request and the payment. The agent can ask, but it can't skip the check. Some providers now offer <a href="https://paywithatoa.com/gb/products/agentic-payments">agentic payments</a> with these limits enforced on their own servers, so a payment over the cap is refused before any money moves.</p>
<h2>Keep a person in charge of the big decisions</h2>
<p>Two moments should always need a human:</p>
<ul>
<li><strong>Setting up the limit</strong> in the first place.</li>
<li><strong>Confirming payments that need Strong Customer Authentication (SCA)</strong>, such as sending money out or charging a customer who isn't there. SCA is the UK rule that the person proves it's really them, with something like a one-time code, a fingerprint or a passkey.</li>
</ul>
<p>Don't give the agent an "approve" tool. If the model can call approve, sooner or later it will. Let the agent ask, and let a person approve on a separate screen, which is how <a href="https://docs.paywithatoa.com/agent-pay/overview">spending-limit contracts for AI agents</a> keep approval outside the model's reach.</p>
<h2>Checklist before your agent touches real money</h2>
<ul>
<li>Limits are checked on the server, not in the prompt</li>
<li>Every limit has a per-payment cap, a period cap, an end date and a direction</li>
<li>The agent has no "approve" tool</li>
<li>Payouts and off-session charges need a person to confirm</li>
<li>You've tested what happens when the agent asks for more than it's allowed</li>
<li>Every payment the agent makes is logged, with who approved what</li>
</ul>
<h2>Conclusion</h2>
<p>AI agents that can pay are already here, with Visa, Mastercard and Google all launching agent payment standards in 2025. A limit written in the prompt can be talked around, so put caps, end dates and approvals on the server where the money moves, and keep a person in charge of the big decisions. Work through the checklist above before your agent spends its first pound.</p>
]]></content:encoded></item></channel></rss>