Skip to content

Connect Razorpay to AI Agents: Orchestrate Orders, QR Codes & Links

A definitive engineering guide to connecting Razorpay to AI agents. Fetch AI-ready tools via Truto's API to orchestrate orders, payment links, and settlements autonomously.

Uday Gajavalli Uday Gajavalli · · 10 min read
Connect Razorpay to AI Agents: Orchestrate Orders, QR Codes & Links

You want to connect Razorpay to an AI agent so your system can autonomously generate payment links, orchestrate order lifecycles, issue refunds, and reconcile settlements based on natural language inputs or triggered workflows. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom Razorpay integration from scratch.

If your team uses standard chat interfaces, check out our guide on connecting Razorpay to ChatGPT, or if you are automating via Anthropic's ecosystem, read our guide on connecting Razorpay to Claude. For engineers building autonomous agents from the ground up using frameworks like LangChain, LangGraph, or Vercel AI SDK, this guide details the exact architecture required.

The shift toward agentic AI in FinOps is accelerating. Finance teams no longer want static dashboards; they want autonomous systems capable of investigating disputes, matching inbound transactions to open invoices, and dynamically generating QR codes for field sales teams. But giving a Large Language Model (LLM) reliable read and write access to a mission-critical payment gateway like Razorpay is a massive engineering hurdle. You either spend sprints building, hosting, and maintaining a custom integration layer, or you utilize managed infrastructure that handles the API boilerplate for you.

This guide breaks down exactly how to fetch AI-ready tools for Razorpay, bind them natively to your LLM, handle complex financial payloads, and execute multi-step workflows autonomously.

The Engineering Reality of Razorpay's API

Building an AI agent is fundamentally straightforward until it needs to interact with the outside world. Giving an LLM access to external financial data sounds simple in a Jupyter Notebook: you write a Node.js function that makes a fetch request, wrap it in an @tool decorator, and pass it to the model. In production, this approach collapses under its own weight. If you build a custom Razorpay connector, you own the entire API lifecycle, schema maintenance, and error handling.

Razorpay's API introduces specific integration challenges that standard LLMs struggle to navigate natively. Understanding these constraints is critical for architecting a reliable agent.

The Strict Order-Payment-Refund Hierarchy

Razorpay operates on a strict entity hierarchy. You do not simply "charge a card." You create an Order. A customer attempts a Payment against that Order. If successful, the Payment is captured. If the customer requests their money back, you issue a Refund against that specific Payment ID.

Standard LLMs often hallucinate direct paths—trying to refund an Order ID instead of the associated Payment ID, or attempting to capture a Payment that is already in a captured state. To prevent these fatal errors, your tools must have extremely precise descriptions and strict parameter schemas that force the LLM to traverse the state machine correctly.

Polymorphic Payment Payloads

When querying payment details via the Razorpay API, the response payload is highly polymorphic. The acquirer_data and method-specific nested objects (card, upi, bank, wallet) change drastically depending on how the customer paid. An LLM trying to extract the last 4 digits of a card will fail if the payment was made via UPI. Maintaining manual JSON schemas that accurately represent these massive, variable payloads for an LLM to digest is a tedious, error-prone task that requires constant updates as Razorpay adds new payment methods.

Rate Limits and the Importance of Explicit Backoff

Razorpay enforces strict rate limiting, particularly on concurrent API requests. When an AI agent attempts to iterate over hundreds of payments to perform reconciliation, it will inevitably hit a rate limit.

A critical architectural note: Truto does not magically retry, throttle, or apply backoff on rate limit errors behind the scenes. Silent retries at the proxy layer are an anti-pattern for AI agents because they cause the LLM connection to time out, leaving the agent in an unknown state.

Instead, when the upstream Razorpay API returns an HTTP 429 Too Many Requests error, Truto passes that error directly back to the caller. What Truto does do is normalize Razorpay's specific rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification.

The caller (your agent framework) is entirely responsible for reading these normalized headers and executing the appropriate exponential backoff and retry loop. This ensures your agent execution environment remains in control of the timeline.

Fetching and Binding Razorpay Tools via Truto

To solve the schema maintenance and API boilerplate problem, Truto maps Razorpay's endpoints into a REST-based CRUD API known as Proxy APIs. We handle the authentication, pagination, and query parameter processing.

More importantly, Truto takes the schemas and descriptions of these Proxy APIs and exposes them formatted specifically for LLM function calling via the /integrated-account/<id>/tools endpoint.

Instead of hardcoding tools, you fetch them dynamically. When you modify a tool's description in the Truto UI to give the LLM better context, that update is immediately reflected in the API response.

Here is how you fetch and bind these tools using the truto-langchainjs-toolset in a Node.js environment:

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
 
async function initializeRazorpayAgent(integratedAccountId: string) {
  // 1. Initialize the Truto Tool Manager with your Razorpay account ID
  const toolManager = new TrutoToolManager({
    trutoApiKey: process.env.TRUTO_API_KEY,
    integratedAccountId: integratedAccountId,
  });
 
  // 2. Fetch all available Razorpay tools dynamically
  // You can pass { methods: ['read', 'custom'] } to filter if needed
  const tools = await toolManager.getTools();
 
  // 3. Initialize your LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // 4. Define the agent's system prompt
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are an elite FinOps agent interacting with Razorpay. Always traverse the Order -> Payment -> Refund hierarchy correctly. Handle financial data with precision."],
    ["placeholder", "{chat_history}"],
    ["human", "{input}"],
    ["placeholder", "{agent_scratchpad}"],
  ]);
 
  // 5. Bind the tools and create the executor
  const agent = await createOpenAIToolsAgent({
    llm,
    tools,
    prompt,
  });
 
  return new AgentExecutor({
    agent,
    tools,
    maxIterations: 10,
  });
}

Because the tools are generated directly from Truto's proxy resources, the LLM receives perfectly formatted JSON schemas for Razorpay's complex nested objects, eliminating hallucinated fields.

Razorpay Hero Tools for AI Agents

While Truto exposes dozens of endpoints for Razorpay, specific operations unlock massive leverage for autonomous agents. Here are the hero tools your agent will use to orchestrate financial workflows.

list_all_razorpay_settlement_recon

Reconciliation is historically a manual, spreadsheet-heavy process. This tool allows the agent to pull a highly detailed list of all transactions settled to your account for a specific year, month, and day. It returns entity details, debit/credit values, fees, taxes, UTR numbers, and associated order receipts, allowing the agent to automatically match Razorpay settlements against internal accounting ledgers.

"Fetch the settlement reconciliation report for October 12th, 2026. Cross-reference the UTR numbers with the daily bank feed and highlight any discrepancies in collected fees versus expected gateway charges."

This tool enables the agent to dynamically generate Standard Payment Links or UPI Payment Links. It requires the amount, currency, and customer details. This is incredibly powerful for automated collections workflows, allowing the agent to detect an overdue invoice in your CRM and immediately generate a tailored payment link to email the client.

"Invoice INV-9981 for Acme Corp is 14 days overdue. Generate a standard payment link for 50,000 INR, set the expiry for 48 hours from now, and enable automatic reminders. Return the short_url so I can draft the follow-up email."

create_a_razorpay_order

The foundational step for any Razorpay checkout flow. The agent can construct a server-side order defining the exact amount, currency, and custom receipt identifier. Because the schema enforces integer values for currency (e.g., passing 50000 for 500.00 INR), the LLM learns to format the financial payload correctly based on the tool definition.

"We just confirmed a custom enterprise upgrade for user ID 8819. Create a Razorpay order for 1200 USD. Tag the notes field with 'Enterprise Upgrade Q4' and return the Order ID so the frontend can initialize the checkout modal."

create_a_razorpay_qr_code

For businesses bridging the digital and physical worlds (like field sales, delivery services, or event management), this tool allows the agent to programmatically generate dynamic UPI QR codes. The agent passes the fixed amount, customer ID, and close parameters, receiving an image_url back that can be immediately embedded in digital documents or tickets.

"The delivery agent has arrived at the location for Order #442. Generate a single-use Razorpay QR code for the exact pending amount of 850 INR. Set the usage type to 'single_use' and return the image URL to be displayed on the driver's app."

get_single_razorpay_payment_by_id

When a customer reports an issue or a webhook fails, the agent uses this tool to surgically retrieve the full state of a specific payment. The payload includes critical debugging context like error_code, error_reason, acquirer_data, and refund_status, allowing the agent to diagnose exactly why a transaction failed without human intervention.

"Customer support ticket #1102 states their card was charged but the order didn't complete. Pull the details for payment ID 'pay_Mlk98Pq1' and tell me if the status is captured, failed, or authorized, and list any error reasons provided by the acquirer."

list_all_razorpay_disputes

Managing chargebacks and disputes is a time-sensitive operational nightmare. This tool allows the AI agent to regularly scan for new disputes across the Razorpay account, retrieving the reason_code, the deducted amount, the phase of the dispute, and the critical respond_by timestamp.

"Scan for all currently open disputes in Razorpay. For any dispute where the 'respond_by' timestamp is within the next 72 hours, extract the payment ID and the reason code so we can immediately compile the defense evidence."

For the complete inventory of available methods, endpoints, and schema details, review the Razorpay integration page.

Workflows in Action

Connecting these tools transforms static scripts into autonomous FinOps workflows. Here are concrete examples of how AI agents utilize Truto's Razorpay tools in production environments.

Workflow 1: Automated Payment Dispute Investigation

Chargebacks require immediate investigation. When a dispute webhook fires, a human usually has to log into the dashboard, find the payment, find the user, and determine if the transaction was legitimate. An AI agent handles this instantly.

Prompt: "A new chargeback was logged for payment ID 'pay_Kq9L2zX'. Investigate the payment details, find the associated customer and order, and compile a summary of the transaction history to determine if this is friendly fraud."

  1. get_single_razorpay_dispute_by_id: The agent fetches the dispute parameters to understand the reason_code (e.g., unrecognized charge) and the exact amount_deducted.
  2. get_single_razorpay_payment_by_id: The agent pulls the root payment data, extracting the order_id, email, contact, and the card network details.
  3. get_single_razorpay_order_by_id: The agent checks the order status and attempts history, verifying if the service was marked as delivered in the metadata.
  4. Result: The agent drafts a comprehensive Slack alert to the risk team: "Dispute received for $45.00 (Reason: Unrecognized). Payment pay_Kq9L2zX was fully 3D-Secure authenticated. The associated Order #882 shows digital goods were delivered. Recommendation: Submit evidence to challenge the dispute."

B2B SaaS companies often struggle with failed subscription renewals. Instead of sending generic dunning emails, an agent orchestrates targeted recovery.

Prompt: "The scheduled subscription charge for Customer ID 'cust_Lx891P' failed due to insufficient funds. Generate a customized payment link for the outstanding balance of 15,000 INR and configure it to expire in 3 days."

  1. get_single_razorpay_customer_by_id: The agent retrieves the customer's exact profile, ensuring the name and contact details are accurate.
  2. list_all_razorpay_invoices: The agent searches for the specific unpaid invoice associated with the failed subscription cycle to verify the exact amount_due.
  3. create_a_razorpay_payment_link: Using the verified amount and customer contact data, the agent generates a secure link, explicitly setting the expire_by parameter to 72 hours from the current UNIX timestamp, and enabling send_email.
  4. Result: Razorpay dispatches a secure, trackable payment link directly to the customer, and the agent logs the short_url back into the CRM's recovery notes.

Building Multi-Step Workflows

When architecting multi-step loops in frameworks like LangGraph or the Vercel AI SDK, network volatility is your primary enemy. AI agents are incredibly fast; an LLM iterating over an array of 50 failed payments to update their notes via update_a_razorpay_payment_by_id will trigger Razorpay's rate limits almost instantly.

As established, Truto passes the HTTP 429 error upstream to you, alongside the ratelimit-reset header. Your execution loop must intercept this specific error state, halt the tool execution, wait the required duration, and then permit the agent to retry the action. If you fail to handle the 429 gracefully, the agent will interpret the API failure as a complete workflow failure and hallucinate a premature conclusion.

Here is a conceptual architecture for handling Truto's rate limit headers within a custom tool execution wrapper:

async function executeToolWithBackoff(toolCall: any, maxRetries = 3) {
  let attempt = 0;
  
  while (attempt < maxRetries) {
    try {
      // Execute the Truto proxied API call
      const response = await performTrutoApiCall(toolCall);
      return response;
    }
    catch (error: any) {
      if (error.status === 429) {
        attempt++;
        // Extract Truto's normalized IETF headers
        const resetTime = parseInt(error.headers.get('ratelimit-reset') || '10', 10);
        const remaining = error.headers.get('ratelimit-remaining');
        
        console.warn(`[Agent] Rate limit hit. Remaining: ${remaining}. Pausing execution for ${resetTime} seconds...`);
        
        // Halt execution until the reset window passes
        await new Promise(resolve => setTimeout(resolve, resetTime * 1000));
        continue;
      }
      // If it's a 400/500 error, pass it back to the LLM to process and correct
      throw error;
    }
  }
  throw new Error("Max retries exceeded for tool execution");
}

By injecting this logic at the tool-execution layer of your framework, the LLM remains blissfully unaware of the network throttling. It simply waits slightly longer for the tool to return a successful result, allowing it to seamlessly continue its multi-step Razorpay orchestration.

Moving Forward

Connecting an AI agent to Razorpay shouldn't require weeks of maintaining API schemas, wrestling with undocumented edge cases, or manually mapping the Order-Payment-Refund object hierarchy into Prompt syntax. By utilizing Truto's /tools endpoint, you offload the infrastructure burden. You provide your LLM with dynamically updated, perfectly formatted functional descriptions, allowing your engineering team to focus on the intelligence of the agent rather than the boilerplate of the integration.

FAQ

How does Truto handle Razorpay rate limits for AI agents?
Truto does not silently retry or absorb rate limits. It passes the HTTP 429 error directly to your agent along with standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your agent framework is responsible for reading these headers and executing exponential backoff.
Do I need to write JSON schemas for Razorpay endpoints?
No. Truto automatically generates and maintains the JSON schemas for every Razorpay method and exposes them via the /tools endpoint, formatted specifically for LLM function calling.
Which agent frameworks are supported?
Truto's tools are framework-agnostic. You can bind them to LangChain, LangGraph, CrewAI, the Vercel AI SDK, or pass them directly to the OpenAI/Anthropic APIs.
Can I filter which Razorpay tools the AI agent has access to?
Yes. You can filter the /tools endpoint response by passing query parameters like `methods[0]=read` to restrict the agent to read-only operations.

More from our Blog