Once a user (or agent) purchases a Payment Plan, if this plan has some AI agents or services attached to it, the user can start querying these AI agents. To facilitate AI agents to authorize only the requests of users with a valid Payment Plan, the Payments libraries provide a simple API to make this validation simple and secure.

Users: Sending Requests to AI Agents

When a user wants to access an AI agent, they need to send a request with the access token received when they purchased the Payment Plan. This token is used to validate that the user has access to the AI agent and that they have enough credits or an active subscription.

// After purchasing a Payment Plan, let's generate the access token
const credentials = await payments.agents.getAgentAccessToken(planId, agentId)

//// OUTPUT: credentials:
//// {
////   accessToken: 'eJyNj0sKgDAURP9lJQ ....',
////   proxies: [ 'https://proxy.nevermined.app' ]
//// }  
      
// Now we can use this access token to send requests to the AI agent
const agentHTTPOptions = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Bearer ${credentials.accessToken}`,
  }
}

// Example request to the AI agent
const response = await fetch(new URL('https://my.agent.io/prompt'), agentHTTPOptions)

if (response.ok) {
  const data = await response.json()
  console.log('AI agent response:', data)
} else {
  console.error('Error accessing AI agent:', response.status, await response.text())
}

AI Agents: Authorizing Only Valid Requests from Users

All the authorization can be done by calling the requests.startProcessingRequest method. This method will receive the access token sent by the user and will validate:
  1. The user is a subscriber of any of the payment plans giving access to the AI agent.
  2. The endpoint requested and HTTP method is allowed because it was included as part of the AI agent registration.
  3. The user has enough credits to pay for the request (if the AI agent is using a credit-based Payment Plan) or the payment plan hasn’t expired (if it’s a time-based subscription).
In the example below, we will start a simple HTTP server that will first validate the request using the startProcessingRequest method. If the request is valid, it will return a 200 OK response; otherwise, it will return a 402 Payment Required response.
import http from 'http'

const agentHost = 'https://example.com' // The AI agent is running on this host

const server = http.createServer(async (req, res) => {
  const authHeader = req.headers['authorization'] as string
  const requestedUrl = `${agentHost}${req.url}`
  const httpVerb = req.method
  console.log('Received request:', { endpoint: requestedUrl, httpVerb, authHeader })
   
  try {
    const isValidReq = await payments.requests.startProcessingRequest(
      agentId,
      authHeader,
      requestedUrl,
      httpVerb!,
    )
    console.log('isValidReq', isValidReq)
    if (isValidReq.balance.isSubscriber) {
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ message: 'Hello from the agent!' }))
      return
    }
  } catch (error) {
    console.log('Unauthorized access attempt:', authHeader)
    console.log('Error details:', error)
  }

  res.writeHead(402, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: 'Payment Required' }))
})

server.listen(8889, () => {
  console.log('AI agent server running on port 8889')
})
As you can see, the Payments libraries are framework-agnostic, so you can integrate them with any web framework in TypeScript/JavaScript (Express, Next.js, etc.) or Python (FastAPI, Flask, etc.).

Best Practices for Request Processing

Validation First

Always validate payments before processing expensive AI operations to avoid wasting resources.

Error Handling

Provide clear error messages and appropriate HTTP status codes for different failure scenarios.

Resource Management

Implement timeouts and resource limits to prevent abuse and ensure fair usage.

Monitoring

Log all requests, validation results, and processing times for analytics and debugging.