Skip to content
Logo

Add payments to your agent

Use a Link SDK to let your agent request payment credentials from a customer’s Link wallet. Your application connects the customer’s Link account, creates a spend request describing the proposed purchase, asks the customer to approve it, and then uses the scoped credential to complete checkout.

This hosted integration is available for US and Canadian customers. Your business, agent, and the sellers your customers buy from can be outside these countries.

Link’s API lives at api.link.com and authorizes against login.link.com, separate from api.stripe.com. You authenticate with an OAuth access token that represents one customer. Stripe secret keys and restricted API keys don’t work, and the Stripe server-side SDKs don’t cover these endpoints.

Before you begin

This guide covers a hosted application. For an agent running locally, use the Link CLI quickstart.

Hosted authorization requirements

Prepare the following before connecting a customer’s Link account:

  • A supported runtime: Node.js 20 or newer for TypeScript, Go 1.23 or newer, or Python 3.11 or newer. TypeScript requires an ESM project.
  • The hosted OAuth prerequisites: a registered confidential client, a Stripe publishable key, a server-side callback and session store, and secure token storage.

For the payment examples in this guide, you also need a customer with a US or Canadian Link account and an eligible payment method.

The code blocks are integration excerpts. Your application supplies the credential storage, customer messaging, saved run state, and checkout execution described in each step.

Install the SDK

Install the SDK for your language.

npm install @stripe/link-sdk

The TypeScript package exports Link as both a default and a named export. Each SDK provides an authenticated client for the steps that follow.

Register a hosted OAuth client

Follow OAuth client registration to get your client_id and client_secret and register exact redirect URIs. Keep the client secret in a server-side secrets manager. Skip registration if you already have a client.

Build the OAuth authorization URL with the payment_methods.agentic scope. Add userinfo:read if you need the customer's name and email. Generate PKCE values and store the verifier and a random state in the customer's server-side session before redirecting them.

Follow OAuth callback handling to verify state and handle the returned code or error. This authorization redirect is separate from a spend request's completion callback.

Exchange the code for tokens

Exchange the authorization code from your server using the original PKCE verifier. Check the granted scopes, then store and manage the tokens securely on your server before creating the SDK client.

Create the SDK client

The SDK accepts an OAuth access token, but it doesn’t perform login, persist credentials, or own refresh tokens. Provide a function that returns a current access token. The SDK calls it before every request and, as a fallback after a 401, calls it once more with a forced-refresh signal.

In these examples, credentialManager (credential_manager in Python) is your application’s token store, not a Link SDK export. It returns the customer’s current token and refreshes it when requested.

import Link from '@stripe/link-sdk'
 
const link = new Link({
  getAccessToken: async ({ forceRefresh } = {}) =>
    credentialManager.getLinkAccessToken({ forceRefresh }),
})

Your credential manager should track token expiry, coalesce concurrent refreshes, persist rotated refresh tokens safely, and keep all tokens out of agent context, logs, and client-side code.

Choose a payment method

List the payment methods in the connected Link wallet and select the default eligible method:

const methods = await link.paymentMethods.list()
const eligibleMethods = methods.filter(
  (method) => method.capabilities?.agentic_payments?.eligible !== false,
)
const paymentMethod =
  eligibleMethods.find((method) => method.is_default) ?? eligibleMethods[0]
 
if (!paymentMethod) {
  throw new Error('The user needs to add an eligible Link payment method.')
}

Ineligible methods include a capabilities.agentic_payments object with eligible: false and ineligibility_reasons.

Link CLI calls this selector payment_method_id, while the SDKs send the selected method ID as payment_details.

Create a spend request

Describe what the agent is buying and why. Amounts use the currency’s minor unit, such as cents for USD, and context must contain at least 100 characters.

const spendRequest = await link.spendRequests.create({
  payment_details: paymentMethod.id,
  credential_type: 'card',
  amount: 2599,
  currency: 'usd',
  merchant_name: 'Acme',
  merchant_url: 'https://acme.example',
  context:
    'The user asked the agent to buy the selected item from Acme for $25.99, including the displayed shipping cost.',
})

Pass an idempotency_key (IdempotencyKey in Go) with a stable, non-sensitive value for the purchase so that a retried create returns the original request. See Error handling.

Ask for approval

Request approval, send the returned URL to the customer, and save the spend request ID so a later agent run can resume the purchase. The sendToUser and saveRunState helpers (and their Python equivalents) represent your application’s messaging and persistent storage.

const approval = await link.spendRequests.requestApproval(spendRequest.id)
const approvalDeadline = Date.now() + 30 * 60 * 1000
 
await sendToUser(`Approve this purchase: ${approval.approval_url}`)
await saveRunState({ spendRequestId: spendRequest.id, approvalDeadline })

The customer has 30 minutes to approve the request.

Return the customer to your app

Optionally, send the customer back to your application after they finish an approval or required action. Supply a completion callback when you create the request. This is separate from the OAuth redirect_uri that you registered for authorization.

Supply completion_callback_url and nonce together, or omit both. Generate an unpredictable opaque nonce, save it with the request, and compare it exactly when the customer returns. See Completion callbacks for URL and nonce validation requirements and supported behavior.

const nonce = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
await saveRunState({ nonce })
 
const spendRequest = await link.spendRequests.create({
  // ...the purchase fields from the previous example
  completion_callback_url: 'https://agent.example.com/link/callback',
  nonce,
})

The CLI equivalent adds --completion-callback-url "https://agent.example.com/link/callback" --nonce "$NONCE" to spend-request create.

Use the returned approval_url and next action's action_url as-is, whether the action appears under status_details.requires_action or status_details.failed. Offer the action URL only when it isn't null.

On return, verify the nonce and retrieve the request before continuing. Callback status describes the customer's action, not proof of payment success. Follow the completion callback and recovery rules.

Wait for the approval result

The SDKs don’t poll automatically. Follow the approval polling rules, including how to show required actions and recover from a timeout.

Use the polling example for your language with the request ID and deadline you saved in the previous step:

Save the returned spend request as result for the next step. Load the request ID and deadline from your application’s saved state when resuming a purchase.

Retrieve and use the credential

After the request is approved, retrieve again with the card expansion. This keeps the full credential out of routine polling responses. The checkoutWorker and notifyUser helpers (and their Python equivalents) represent your application’s checkout executor and customer messaging. Keep the checkout executor outside model context.

if (result.status !== 'approved') {
  await notifyUser(`Purchase not approved: ${result.status}`)
  return
}
 
const approved = await link.spendRequests.retrieve(result.id, {
  include: ['card'],
})
 
if (!approved?.card) {
  throw new Error('Approved spend request did not include a card.')
}
 
await checkoutWorker.complete(approved.card)

The returned card contains id, number, brand, exp_month, exp_year, and optional cvc, billing_address, and valid_until. Keep returned card credentials out of model context, logs, and customer-visible messages.

Refresh and revoke access

Follow the OAuth refresh and revocation reference to refresh before the access token expires, persist rotated refresh tokens, and revoke access when a customer disconnects your agent.

Know the limits

Review the limits table for purchase amounts, request rates, approval windows, and credential validity. Use Error handling to plan recovery when a call fails.

Next steps

Extend your integration with another payment option or financial data: