View as Markdown

Authorize · Guide

Authorize agent payments

Use @provenanceauth/rails to carry a person's authorization into the agent-payment protocols. A grant becomes AP2 open Payment Mandate content or an ACP payment allowance. An intent token travels on AP2 Checkout and Payment Mandates, in an x402 payment's extensions or on the ACP checkout completion, where the merchant verifies it. Provenance verifies the authorization; your payment provider moves the money.

Before you begin: export the sandbox account key and install the rails package.

export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_acct_P9xN2vQ7bT4mW8sYd3cFjLh6gAe1kR5

This package isn't on npm yet. Until then, every request in these docs runs over HTTP against the sandbox.

With access to the private Provenance repository, which your Provenance contact grants, install from it:

git clone https://github.com/michaelnbane-jpg/provenance.git provenance
cd provenance && pnpm install && pnpm build
node scripts/check-publishable.mjs --out ../provenance-packs
cd ../your-project
npm install ../provenance-packs/provenanceauth-sdk-1.0.0.tgz ../provenance-packs/provenanceauth-rails-1.0.0.tgz

Limitations: the AP2 mapping maps to AP2 0.2, exported as AP2_SPEC_VERSION. AP2 mandates are SD-JWTs signed by a Trusted Surface the verifier trusts. Provenance can be that surface after a passkey approval (see Issue AP2 mandates); otherwise your own Trusted Surface signs, with Provenance's content and intent token inside. The x402 mapping maps to x402 v2, exported as X402_VERSION. The ACP mapping maps to ACP 2026-04-17, exported as ACP_SPEC_VERSION.

1. Give the agent a grant

A grant is a person's standing, bounded authority for an agent: a per-payment limit, a monthly budget and allowed merchants. Grant it with POST /v1/mandate/grants:

curl -s $PROVENANCE_API/v1/mandate/grants \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "device_id": "dev_00000000000000000000000000000001",
    "agent_session_id": "sess_buyer_1",
    "constraints": {
      "max_amount": 200,
      "budget_amount": 500,
      "budget_window": "month",
      "allowed_action_types": ["payment"],
      "allowed_counterparties": ["merchant_acme"],
      "expires_at": "2027-12-31T23:59:59Z"
    }
  }' | tee mandate.json

The response, trimmed:

{
  "id": "grt_01M5Q2QMTMZK4271Z95VG4RCDN",
  "object": "grant",
  "status": "active",
  "agent_session_id": "sess_buyer_1",
  "remaining_budget": 500,
  "expires_at": "2027-12-31T23:59:59Z",
  "mandate_token": "eyJhbGciOiJFUzI1NiIsInR5cCI6Im1hbmRhdGUrand0Iiwia2lkIjoiNzUyNjk2ZmYwZjVlNGY1MyJ9.eyJpc3MiOiJwcm92ZW5hbmNlLWF1dGhvcml6ZSJ9.HBZ1gq7tZyq7p7KhKbGDj3Rrcn9DRckwHHvkF7B-L7plT84vCNY1BVBAKlAv5Y8LywQwU0I3rxTBG3qQCk0bCQ"
}

2. Map the grant to an AP2 open Payment Mandate

AP2 0.2 authorizes a purchase with two mandates: a Checkout Mandate for what is bought and a Payment Mandate for how it is paid. When the agent shops on its own, the person approves open mandates that set limits, and the agent closes them for each purchase.

provenanceMandateToAp2OpenPayment turns the grant into open Payment Mandate content (mandate.payment.open.1). AP2 binds an open mandate to the agent's public key, so pass it as agentKey. Allowed merchants need a name in AP2, so pass them as payees. ap2OpenPaymentToProvenance maps the content back.

import { provenanceMandateToAp2OpenPayment } from "@provenanceauth/rails/ap2";

const { mandate: openPayment, not_mapped } = provenanceMandateToAp2OpenPayment(
  { mandate_id: mandate.id, agent_session_id: "sess_buyer_1", constraints: { max_amount: 200, budget_amount: 500, budget_window: "month", allowed_counterparties: ["merchant_acme"], expires_at: "2027-12-31T23:59:59Z" }, mandate_token: mandate.mandateToken },
  {
    currency: "usd",
    agentKey, // the agent's P-256 public JWK
    payees: [{ id: "merchant_acme", name: "Acme", website: "https://acme.example" }],
    checkoutReference, // the open Checkout Mandate's digest, once the agent has it
  },
);
// Your Trusted Surface shows openPayment to the person and signs it as an SD-JWT.

The content, trimmed:

{
  "vct": "mandate.payment.open.1",
  "constraints": [
    { "type": "payment.amount_range", "currency": "USD", "max": 20000 },
    { "type": "payment.allowed_payees", "allowed": [{ "id": "merchant_acme", "name": "Acme", "website": "https://acme.example" }] },
    { "type": "payment.reference", "conditional_transaction_id": "FzLoxbbtgQGYZxoSM2NJYJtkFTSsdfUBoVEQ12k7JN8" }
  ],
  "cnf": { "jwk": { "kty": "EC", "crv": "P-256", "x": "QpSyxPQHy38xckyvDr54gZ3T42zj9iLtV4koyb5U27c", "y": "37HLd7JJinxjJIn8J7HijssoecBlfhdW-gUL7feI9lw" } },
  "exp": 1830297599,
  "com.provenanceauth.mandate": { "token": "eyJhbGciOiJFUzI1NiIs..." }
}

The fields map like this:

ProvenanceAP2 0.2
constraints.max_amountpayment.amount_range max, in minor units for the currency
constraints.allowed_counterpartiespayment.allowed_payees allowed, as merchant objects with the same ids
constraints.expires_atexp
mandate_tokenThe com.provenanceauth.mandate claim, which AP2 carries unchanged into the closed mandate

The grant's budget stays with Provenance, which enforces it each time the agent authorizes. AP2's payment.budget caps the total over an open mandate's whole life, while a Provenance budget renews each day, week or month, so not_mapped lists it.

3. Put the intent token on AP2 mandates

The merchant signs a Checkout JWT for the cart. Authorize with ap2BindingPayload as the action payload, so the token binds the Checkout's hash, the payee and the amount. Then attach the token to the closed Checkout Mandate (mandate.checkout.1) and Payment Mandate (mandate.payment.1) content, in a com.provenanceauth.intent claim.

import { ap2BindingPayload, ap2CheckoutMandateContent, ap2PaymentMandateContent } from "@provenanceauth/rails/ap2";

const payee = { id: "merchant_acme", name: "Acme", website: "https://acme.example" };
const payment_amount = { amount: 19900, currency: "USD" };
const auth = await prov.mandate.intents.create({
  actionDescription: "Buy SuperShoe Limited Edition Gold for $199.00 at Acme",
  actionPayload: ap2BindingPayload({ checkout_jwt: checkoutJwt, payee, payment_amount }),
  agentSessionId: "sess_buyer_1",
  deviceId: "dev_00000000000000000000000000000001",
  mandateToken: mandate.mandateToken,
});

const jwksUrl = `${process.env.PROVENANCE_API}/.well-known/jwks.json`;
const checkoutMandate = ap2CheckoutMandateContent(checkoutJwt, auth.intentToken, { jwksUrl });
const paymentMandate = ap2PaymentMandateContent(
  { checkout_jwt: checkoutJwt, payee, payment_amount, payment_instrument: { id: "pi_1", type: "card", description: "Card 4242" } },
  auth.intentToken,
  { mandateToken: mandate.mandateToken },
);
// Sign both with your Trusted Surface (the person is present) or the agent's key (an open mandate).

The closed Checkout Mandate content, trimmed:

{
  "vct": "mandate.checkout.1",
  "checkout_jwt": "eyJhbGciOiAiRVMyNTYiLCAidHlwIjogIkpXVCIs...",
  "checkout_hash": "NivWhuqfzcvZNapvIEJ2-3tsdQLkiuIcye2g46WVgX8",
  "com.provenanceauth.intent": { "token": "eyJhbGciOiJFUzI1NiIs...", "jwks_url": "https://sandbox-api.provenanceauth.com/.well-known/jwks.json" }
}
ProvenanceAP2 0.2
The intent tokenThe com.provenanceauth.intent claim on the closed Checkout and Payment Mandates
The issuer's published keys URLcom.provenanceauth.intent.jwks_url, a hint
The token's payload_hashThe Checkout's checkout_hash (the Payment Mandate's transaction_id), the payee id, the amount in minor units and the currency

4. Verify an AP2 mandate at the merchant

Your AP2 stack verifies the mandate's SD-JWT signature and key binding. Pass the content it returns to verifyAp2Mandate, with expected built from the Checkout you signed. It recomputes checkout_hash, checks your facts, evaluates any open mandates the agent presented, and checks the token against the issuer's published keys and its binding. Pass onlineStatus to also check revocation. The same call verifies a Payment Mandate at the credential provider.

import { ap2ReceiptClaims, verifyAp2Mandate } from "@provenanceauth/rails/ap2";
import { publicVerify } from "@provenanceauth/rails/checkout";
import { fetchJwks } from "@provenanceauth/sdk";

const issuer = process.env.PROVENANCE_API!;
const jwks = await fetchJwks(issuer);

const result = await verifyAp2Mandate(checkoutMandateContent, {
  jwks,
  expected: { checkout_jwt: myCheckoutJwt, payee_id: "merchant_acme", amount: 19900, currency: "usd" },
  open: openCheckoutMandates, // when the agent shops on its own
  onlineStatus: publicVerify(issuer),
});
if (result.hand_back) {
  // AP2 unresolved_constraint: ask the agent for a mandate the person approved directly.
}
const receipt = ap2ReceiptClaims(result, { iss: "https://acme.example", reference: mandateHash, order_id });
// Sign the receipt with your key and return it to the agent.

result.ap2_error is the AP2 error code for your receipt:

result.reasonap2_errorMeans
checkout_hash_mismatchinvalid_mandatecheckout_hash isn't the hash of checkout_jwt
checkout_mismatch, payment_mismatchinvalid_mandateThe Checkout, payee, amount or currency differs from your own
constraint_failedinvalid_mandateThe closed mandate breaks an open mandate's limit, such as the amount range or allowed payees
claim_changedinvalid_mandateA claim of the open mandate changed in the closed one
unresolved_constraintunresolved_constraintAn open mandate has a constraint this check can't evaluate, such as payment.budget, which needs the mandate's spending history
no_intentunresolved_constraintThe mandate carries no intent token
token_expired, token_invalid, token_revokedinvalid_credentialThe intent token is past its expiry, didn't verify against the published keys, or was revoked
payload_unbound, payload_hash_mismatchinvalid_mandateThe token binds no payload, or a different Checkout or payment
unsupported_mandatemandates_not_supportedThe vct isn't a mandate type of AP2 0.2

Mandates Provenance signed. An agent can present closed Checkout and Payment Mandates Provenance signed after a passkey approval. Verify the whole SD-JWT with verifyAp2UserMandate, listing Provenance's AP2 keys (/.well-known/ap2/jwks.json) as an issuer, or add that URL to external_confirmations.ap2_issuers on your agent policy. See Issue AP2 mandates.

hand_back: true comes with unresolved_constraint. AP2 uses it to bring the person back: the agent asks them to approve this exact Checkout, authorizes a new intent token bound to it, and presents mandates they approved directly.

5. Ask for an intent in the 402

The x402 mapping maps to x402 v2. The payment scheme (exact, upto and others) stays the payment, and your facilitator verifies and settles it. The intent token travels beside it, in an x402 extension named com.provenanceauth.intent.

On the merchant's side, add the extension to the PaymentRequired you already send. x402Challenge builds the 402 from your own payment requirements and sets the base64 PAYMENT-REQUIRED header. withIntentExtension adds the extension to a PaymentRequired your x402 server builds.

import { x402Challenge } from "@provenanceauth/rails/x402";

const accepts = [{
  scheme: "exact",
  network: "eip155:84532",
  amount: "25000000",
  asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
  payTo: "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
  maxTimeoutSeconds: 60,
}];
const resource = { url: "https://merchant.example/reports/q3", description: "Q3 report" };
const challenge = x402Challenge({ resource, accepts });
// new Response("{}", { status: challenge.status, headers: challenge.headers })

The decoded header carries the extension next to your payment requirements, trimmed:

{
  "x402Version": 2,
  "resource": { "url": "https://merchant.example/reports/q3", "description": "Q3 report" },
  "accepts": [{ "scheme": "exact", "network": "eip155:84532", "amount": "25000000" }],
  "extensions": {
    "com.provenanceauth.intent": {
      "info": { "required": true },
      "schema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object" }
    }
  }
}

Pass required: false to let clients without Provenance pay as usual.

To tell agents your rules in the same answer, pass profile: discoveryFields(profile).x402.profile. The extension's info.profile then carries the amount above which a person approves, your selling agent and its key ids, and profile_url; an older client ignores it (Be findable by agents).

6. Pay with x402 from the agent

On the agent's side, wrap fetch with intentPaymentFetch. It acts only on a 402 whose PAYMENT-REQUIRED header lists the extension. Any other 402 comes back to you unchanged.

  • getToken authorizes under the grant, with the payment's facts as the action payload, so the token binds this resource, amount, asset, network and recipient.
  • createPayment builds the signed payment with your x402 client.

The wrapper appends the token to the extension's info, keeps the merchant's info as sent, and retries once with the PAYMENT-SIGNATURE header.

import { intentPaymentFetch, x402BindingPayload } from "@provenanceauth/rails/x402";

const payingFetch = intentPaymentFetch(
  fetch,
  async ({ paymentRequired }) => {
    const [requirements] = paymentRequired.accepts;
    const auth = await prov.mandate.intents.create({
      actionDescription: `Pay for ${paymentRequired.resource.url}`,
      actionPayload: x402BindingPayload(paymentRequired.resource, requirements),
      agentSessionId: "sess_buyer_1",
      deviceId: "dev_00000000000000000000000000000001",
      mandateToken: mandate.mandateToken,
    });
    return auth.intentToken;
  },
  {
    createPayment: ({ paymentRequired }) => x402Client.createPaymentPayload(paymentRequired),
    jwksUrl: `${process.env.PROVENANCE_API}/.well-known/jwks.json`,
  },
);
const report = await payingFetch("https://merchant.example/reports/q3");

x402Client stands for your x402 client library. Return null from either callback to stop and get the 402 back.

The fields map like this:

Provenancex402 v2
The merchant asks for an intentPaymentRequired.extensions["com.provenanceauth.intent"].info.required
The intent tokenPaymentPayload.extensions["com.provenanceauth.intent"].info.token
The issuer's published keys URLPaymentPayload.extensions["com.provenanceauth.intent"].info.jwks_url, a hint
The token's payload_hashresource.url plus the chosen requirements' scheme, network, amount, asset and payTo

7. Verify the payment at the merchant

On the merchant's side, verifyX402Payment reads the PAYMENT-SIGNATURE header and checks the token against the issuer's published keys before you settle. Pass expected, built from the requirements you advertised, to check that the token binds this payment and that the payment's accepted requirements match. Pass onlineStatus to also check revocation, which an offline check can't see. Use it for any payment of real value.

import { verifyX402Payment, x402BindingPayload, x402Challenge } from "@provenanceauth/rails/x402";
import { publicVerify } from "@provenanceauth/rails/checkout";
import { fetchJwks } from "@provenanceauth/sdk";

const issuer = process.env.PROVENANCE_API!;
const jwks = await fetchJwks(issuer);

export async function handle(req: Request): Promise<Response> {
  const result = await verifyX402Payment(req.headers.get("payment-signature"), {
    jwks,
    expected: x402BindingPayload(resource, accepts[0]),
    onlineStatus: publicVerify(issuer), // the free, keyless POST /v1/verify
  });
  if (!result.accepted) {
    const challenge = x402Challenge({ resource, accepts });
    return new Response("{}", { status: challenge.status, headers: challenge.headers });
  }
  // Verify and settle the payment with your facilitator, then serve.
  return new Response("the report");
}
result.reasonMeans
no_paymentThe PAYMENT-SIGNATURE header is missing or malformed
invalid_x402_versionThe payment isn't x402Version: 2
no_intentThe payment has no com.provenanceauth.intent token
token_expiredThe intent token is past its expiry
token_invalidThe signature didn't verify against the published keys
payload_unboundThe token was authorized without an action payload
payload_hash_mismatchThe resource, amount, asset, network or recipient differs from what the person authorized
accepted_mismatchThe payment was made under different requirements than the token binds
token_revokedThe online check found the token revoked

For browser clients, the merchant's CORS headers expose PAYMENT-REQUIRED and PAYMENT-RESPONSE and allow PAYMENT-SIGNATURE.

The grant's budget and merchant limits are enforced when the agent authorizes and when your executor calls POST /v1/mandate/assessments; an offline check proves only that the token is genuine and current.

8. Map the grant to an ACP allowance

The Agentic Commerce Protocol (ACP) has the agent ask the merchant's payment provider for a delegated payment token, bounded by an allowance. provenanceToAcpAllowance builds that allowance from the grant, so the token can't exceed what the person agreed to. It refuses a merchant that isn't in the mandate's allowed_counterparties.

import { provenanceToAcpAllowance } from "@provenanceauth/rails/acp";

const allowance = provenanceToAcpAllowance(mandate, {
  checkoutSessionId: session.id,
  merchantId: "merchant_acme",
  currency: session.currency,
});

The allowance, for a grant with a max_amount of 200:

{
  "reason": "one_time",
  "max_amount": 20000,
  "currency": "usd",
  "checkout_session_id": "checkout_session_123",
  "merchant_id": "merchant_acme",
  "expires_at": "2027-12-31T23:59:59Z"
}

The fields map like this:

ProvenanceACP 2026-04-17
constraints.max_amount, or the authorized amount of an intent tokenallowance.max_amount, in minor units for the currency
constraints.expires_at, or the intent token's expallowance.expires_at
constraints.allowed_counterpartiesallowance.merchant_id must be in the list when the list is set
The intent tokenprovenance_intent.token on the complete-checkout request
The token's payload_hashThe checkout session id, total, currency, merchant id and store origin

9. Attach the intent to the checkout completion

Authorize the purchase with the checkout's facts as the action payload, so the token's payload hash binds this session, its total, its currency, its merchant and the store's origin. acpBindingFromSession reads the first four from the checkout session (the total is the session's total line in minor units) and takes the origin as its third argument: the scheme and host of the store's checkout endpoint, such as https://acme.example. Then add the token to the complete-checkout request with withProvenanceIntent.

import { acpBindingFromSession, acpExtension, withProvenanceIntent } from "@provenanceauth/rails/acp";

const binding = acpBindingFromSession(session, "merchant_acme", "https://acme.example");
const auth = await prov.mandate.intents.create({
  actionDescription: `Complete checkout ${session.id} at merchant_acme`,
  actionPayload: binding,
  agentSessionId: "sess_buyer_1",
  deviceId: "dev_00000000000000000000000000000001",
  mandateToken: mandate.mandateToken,
});

const jwksUrl = `${process.env.PROVENANCE_API}/.well-known/jwks.json`;
const body = withProvenanceIntent({ payment_data: paymentData }, auth.intentToken, { jwksUrl });
const { declaration } = acpExtension(auth.intentToken, { jwksUrl });

The request carries the token in an ACP extension field, com.provenanceauth.intent. The merchant lists the extension in its capabilities.extensions:

{
  "name": "com.provenanceauth.intent@2026-10-24",
  "extends": ["$.CheckoutSessionCompleteRequest.provenance_intent"],
  "schema": "https://provenanceauth.com/schemas/acp/provenance-intent/2026-10-24.json"
}

Pass schemaUrl to point the declaration at your own copy of the schema. Card details and the payment token stay with the payment provider.

10. Verify the completion at the merchant

On the merchant's side, verifyAcpCompletion checks the token against the issuer's published keys and checks that its payload hash matches your own record of the session. Pass the facts from your checkout session, never from the request.

import { acpBindingFromSession, verifyAcpCompletion } from "@provenanceauth/rails/acp";
import { publicVerify } from "@provenanceauth/rails/checkout";
import { fetchJwks } from "@provenanceauth/sdk";

const issuer = process.env.PROVENANCE_API!;
const jwks = await fetchJwks(issuer);

export async function complete(sessionId: string, body: Record<string, unknown>) {
  const session = await loadCheckoutSession(sessionId);
  const result = await verifyAcpCompletion(body, {
    jwks,
    expected: acpBindingFromSession(session, "merchant_acme", "https://acme.example"),
    onlineStatus: publicVerify(issuer), // the free, keyless POST /v1/verify
  });
  if (!result.accepted) throw new Error(result.reason);
  return placeOrder(session, body);
}
result.reasonMeans
no_intentThe request has no provenance_intent.token
token_expiredThe intent token is past its expiry
token_invalidThe signature didn't verify against the published keys
payload_unboundThe token was authorized without an action payload
payload_hash_mismatchThe session, total, currency, merchant or origin differs from what the person authorized
merchant_id_mismatch, total_mismatchThe same, naming the field, when the request includes provenance_intent.binding
binding_tamperedThe request's provenance_intent.binding doesn't match the token
token_revokedThe online check found the token revoked

The third argument to acpBindingFromSession is your store's origin, and both sides pass it. An approval for another store that uses the same merchant id fails with payload_hash_mismatch.

11. Buy from another agent under a signed offer

When the seller is another company's agent, it sells under a signed offer and the acceptance is a deal (Deals between agents). Each rail carries the acceptance token:

RailHow the deal rides
x402 v2The seller's x402OfferRequired puts the offer in the 402's com.provenanceauth.intent extension. intentPaymentFetch with dealTokenGetter(acceptOffer) accepts it through POST /v1/authorize/deals and pays with the acceptance token. The seller checks it with verifyX402DealPayment.
ACPThe checkout completion's Provenance extension carries the acceptance token, as it carries any intent token.
AP2 (maps to AP2 0.2)Put the deal id in the Cart Mandate's metadata. Provenance never signs AP2 mandates.

Before an agent accepts an offer, it can check that the seller agent and its key are the ones the business's signed profile lists (Find a business). Sellers publish the profile in each rail's answer with discoveryFields(profile): info.profile in the x402 402, profile in the ACP extension declaration, and com.provenanceauth.profile in the AP2 merchant agent's metadata.

import { intentPaymentFetch } from "@provenanceauth/rails/x402";
import { acceptOffer, dealTokenGetter } from "@provenanceauth/rails/deals";

const pay = intentPaymentFetch(fetch, dealTokenGetter((offer) => acceptOffer(offer, { apiBase, apiKey, agent_session_id: "sess_scout_7", grant_id: mandate_id })), { createPayment });
const res = await pay("https://saltmarsh.example/reports/eu-storage");

Either side can then record the rail's reference with POST /v1/authorize/deals/{id}/payment. Provenance never moves or holds the money.

Errors you might see

SymptomCauseFix
valid: false, grant_constraint_violated at verifyThe payment is over max_amount or to a merchant not in allowed_counterpartiesStay within the grant, or give the agent a new one.
valid: false, grant_budget_exceededThe budget for this window is spentWait for the next window, or grant a larger budget.
provenanceToAcpAllowance throws not in the mandate's allowed_counterpartiesThe checkout's merchant isn't one the person allowedUse an allowed merchant, or give the agent a new grant.
provenanceToAcpAllowance throws the mandate has no max_amountAn ACP allowance needs a per-payment limitGive the grant a max_amount.
payload_hash_mismatch at the merchantThe cart or the payment amount changed after the person authorized itAuthorize again with the new total.
unresolved_constraint from verifyAp2MandateThe AP2 mandate has no intent token, or an open mandate has a constraint the check can't evaluateAsk the person to approve this Checkout, then present the new intent token.
provenanceMandateToAp2OpenPayment throws needs a Merchant objectAP2 lists allowed payees as merchant objects with a namePass payees with an id and name for each allowed counterparty.
intentPaymentFetch returns the 402 without calling getTokenThe merchant's PAYMENT-REQUIRED doesn't list com.provenanceauth.intent, or isn't x402 v2Pay with your x402 client alone, or ask the merchant to add the extension.
token_invalid: unknown kid at the merchantThe merchant's cached keys predate a key rotationFetch the keys again.
402 trial_ended on the grantThe Free trial endedChoose a plan in Settings → Plan & usage; see plans and usage.

See also