Once a Payment Plan is purchased, User(s) can query all the AI Agents linked to that plan. To ensure AI agents only authorize valid requests (users with credits), we provide a simple API (via the Payments Libraries) that makes validation simple and secure.

Users: Sending Requests to AI Agents

When a user wants to query an AI Agent, they need to send a request with the access token received when purchasing the Payment Plan. This token is used to validate that the user has access to the AI Agent and that they have enough credits.

// 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 payment plans linked to the AI agent.
  2. The requested endpoint and that the HTTP method is permitted (as included as part of the AI agent registration).
  3. The user has sufficient credits to pay for the request (in the case of a credits-based Payment Plan) or the payment plan hasn’t expired (in the case of 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.