Skip to content

Connect Midtrans to AI Agents: Automate GoPay & Billing Flows

Learn how to safely connect Midtrans to AI Agents using Truto's /tools endpoint. Automate GoPay linking, QRIS generation, and fraud challenge resolutions.

Yuvraj Muley Yuvraj Muley · · 10 min read
Connect Midtrans to AI Agents: Automate GoPay & Billing Flows

You want to connect Midtrans to an AI agent so your system can independently orchestrate GoPay account linking, issue refunds, generate QRIS codes, and resolve fraud challenges based on real-time transaction data. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom Midtrans integration from scratch.

Giving a Large Language Model (LLM) read and write access to your payment gateway is an exercise in strict state management and security. If your team uses ChatGPT, check out our guide on connecting Midtrans to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Midtrans to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for Midtrans, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex revenue operations workflows. For a broader look at this design pattern across multiple SaaS platforms, refer to our research on architecting AI agents and the SaaS integration bottleneck.

Why a Unified Tool Layer Matters for Agent Safety

Before writing a line of integration code for your Midtrans AI Agents integration, decide what layer your agent will interact with. Direct API tools - where you map one agent tool to one raw Midtrans endpoint - look fast in a prototype. In production, this approach pushes provider-specific quirks directly into the LLM's context window.

The model has to remember that GoPay tokenization requires distinct API endpoints compared to credit card tokenization, that virtual account numbers have strict character limits, and that resolving a fraud challenge requires specific status payloads. Every one of those quirks is a hallucination waiting to happen.

A unified tool layer collapses these complexities behind a consistent schema. Your agent sees midtrans_transactions_refund and midtrans_direct_debit_direct_debit_payment rather than having to dynamically construct BI-SNAP headers and calculate HMAC signatures. This yields three concrete safety wins:

  1. Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments (like sending a string for a gross amount instead of an integer) are rejected by Truto before they hit Midtrans, allowing the agent to self-correct.
  2. Smaller attack surface. The LLM only ever chooses from stable function names with predictable required parameters. It never invents undocumented API routes.
  3. Abstracted authentication. The agent does not need to handle API keys, OAuth flows, or central bank compliance signatures. The underlying proxy layer manages the auth state.

The Engineering Reality of the Midtrans API

Building an AI agent is a straightforward exercise in prompting and state management. Giving that agent reliable access to external payment infrastructure is where projects stall. The Midtrans API introduces several specific integration challenges that break standard REST assumptions.

The BI-SNAP Protocol Constraint

To operate in Indonesia, Midtrans utilizes the BI-SNAP (Standar Nasional Open API Pembayaran) specification mandated by the central bank. This is not standard REST. BI-SNAP requires a heavily choreographed handshake involving asymmetric signatures for authentication and symmetric signatures for individual API payloads.

If you expose this directly to an LLM, the agent will attempt to send standard JSON payloads and instantly fail because it cannot compute X-SIGNATURE headers dynamically using SHA-256 with RSA encryption. The proxy layer must handle all BI-SNAP signature generation silently, exposing only the raw business logic parameters (like totalAmount and partnerReferenceNo) to the agent.

Asynchronous Payment State Machines

Standard LLMs are trained to expect synchronous success. A record is either created or it isn't. Midtrans transactions operate on complex asynchronous state machines. A payment can be in authorize, capture, settlement, deny, cancel, or expire states.

Furthermore, Midtrans utilizes a Fraud Detection System (FDS). If a transaction looks suspicious, its fraud_status is flagged as challenge. The transaction is suspended until the merchant explicitly approves or denies it via the API. An AI agent managing payments must be explicitly programmed to understand that a 200 OK on a transaction creation does not mean the money is in the bank - it must poll or react to webhooks, check the fraud_status, and optionally call the approval tools before settlement occurs.

GoPay Tokenization Deep Linking

GoPay is a dominant wallet, but linking an account is a multi-step process. You cannot just pass a phone number and charge it. The API requires getting an auth code, generating a redirect URL for the user to enter their PIN, handling the callback, binding the account to get a token, and then executing a pre-auth or direct debit. If you expose this as granular raw endpoints, the agent will frequently hallucinate steps out of order.

Midtrans AI Agent Hero Tools

Truto exposes the Midtrans API as structured, LLM-ready tools. When you hit the Truto /tools endpoint, you receive complete JSON schemas for these operations. Here are the most critical tools for autonomous payment workflows.

1. Create QRIS Transaction

Tool Name: midtrans_qris_create_qr

QRIS (Quick Response Code Indonesian Standard) is ubiquitous. This tool generates a QRIS MPM (Merchant Presented Mode) QR code for a specific transaction amount. The agent receives the transaction ID and the URL to the generated QR code image.

"Generate a QRIS payment code for a 50,000 IDR charge for order ID ORD-88912."

2. Refund Settled Transaction

Tool Name: midtrans_transactions_refund

Refunds a successfully settled transaction to reverse money back to the customer. This tool abstracts away the differences between refunding a GoPay transaction, a ShopeePay wallet, or a credit card, requiring only the order ID and the refund amount.

"The customer for order ID ORD-5512 canceled their subscription early. Issue a partial refund of 150,000 IDR against transaction ID 54321-abcde."

3. Approve Fraud Challenge

Tool Name: midtrans_transactions_approve

Accepts a transaction flagged by the Midtrans Fraud Detection System (FDS) with a challenge status. Once approved, the transaction proceeds to settlement instead of being automatically canceled.

"Review the flagged transaction for order ORD-992. The customer's IP address and shipping address have been manually verified. Approve the challenge so the payment can settle."

4. Create Virtual Account (BI-SNAP)

Tool Name: midtrans_virtual_account_create_va

Generates a Virtual Account number using the SNAP-based BI-SNAP Core API. This is critical for bank transfers in Indonesia. The agent handles the business logic, while the infrastructure handles the BI-SNAP signature generation.

"Create a Permata Virtual Account for customer ID CUST-102. The total amount is 250,000 IDR and the virtual account name should be 'John Doe Purchases'."

5. Bind GoPay Account

Tool Name: midtrans_account_linking_bind_account

Binds a GoPay account to a merchant after the user has completed the PIN/OTP challenge. This exchanges the authorization code for a customer access token, enabling future direct debits.

"The customer just completed the GoPay OTP flow. Use auth code 'AUTH-9912' to bind their GoPay account to our merchant ID and store the resulting token."

6. Execute GoPay Direct Debit

Tool Name: midtrans_direct_debit_direct_debit_payment

Initiates a GoPay Tokenization direct debit payment. This is used for frictionless, one-click checkouts or recurring subscription billing against a previously bound GoPay wallet.

"Process the monthly subscription renewal. Execute a direct debit payment of 99,000 IDR against GoPay charge token 'TOK-884' for partner reference 'SUB-RENEW-12'."

7. Capture Pre-Auth Transaction

Tool Name: midtrans_transactions_capture

Captures a previously authorized card or GoPay transaction to settle the balance. This is essential for workflows where inventory must be verified or shipping calculated before the final charge is executed.

"Inventory has been confirmed for order ORD-112. Capture the authorized 400,000 IDR transaction to finalize the sale."

To view the complete inventory of Midtrans tools, schemas, and required parameters, visit the Midtrans integration page.

Workflows in Action

Providing an AI agent with tool access unlocks complex, multi-step financial operations. Here are real-world examples of Midtrans automation AI Agents orchestrating workflows.

Automating GoPay Subscription Billing

Managing recurring billing via e-wallets requires checking account status, initiating a charge, and handling failures.

"Run the monthly billing cycle for customer CUST-881. Check their GoPay account status. If valid, execute a direct debit for 150,000 IDR. If the payment fails due to insufficient balance, cancel their active subscription."

  1. The agent calls midtrans_account_linking_inquiry_binding to verify the GoPay token is still active and has sufficient limits.
  2. The agent calls midtrans_direct_debit_direct_debit_payment to execute the charge.
  3. If the API returns a failure code for insufficient funds, the agent calls midtrans_subscriptions_cancel to immediately revoke service access.

Outcome: The system autonomously processes wallet-based recurring revenue and enforces churn policies without human accounting intervention.

Autonomous Fraud Challenge Resolution

Customer support teams waste hours manually reviewing false positives in the Fraud Detection System.

"Check the transaction status for order ORD-445. If the fraud status is 'challenge', analyze the risk profile. Since this is a returning customer with 5 previous successful orders, approve the transaction."

  1. The agent calls list_all_midtrans_transactions passing the order ID.
  2. It inspects the transaction_status and fraud_status fields in the normalized JSON response.
  3. Seeing a challenge status, the agent applies its prompt logic (checking historical CRM data via another tool) and determines it is safe.
  4. The agent calls midtrans_transactions_approve to clear the FDS flag and allow settlement.

Outcome: Legitimate transactions are unblocked instantly, improving conversion rates while maintaining risk controls.

Dynamic QRIS Generation & Expiry

Physical retail or dynamic checkout flows require generating payment methods on the fly and voiding them if the customer walks away.

"The customer at Kiosk 3 wants to pay 85,000 IDR via QRIS. Generate the QR code. If the payment status remains pending after 5 minutes, expire the transaction."

  1. The agent calls midtrans_qris_create_qr with the transaction details and displays the resulting image URL.
  2. The agent enters a wait state or scheduled loop, periodically calling midtrans_qris_get_qr_status.
  3. Upon hitting the timeout threshold without a settlement status, the agent calls midtrans_transactions_expire to void the order ID, freeing it up for future use.

Outcome: The system seamlessly bridges offline physical intent with digital central bank payment rails.

Building Multi-Step Workflows

To execute these workflows, you need to load Midtrans tools into your agent framework. Truto provides a unified /tools endpoint that serves OpenAI-compatible schemas, which can be injected directly into frameworks like LangChain via @truto/langchainjs-toolset.

Handling Midtrans Rate Limits in the Agent Loop

It is critical to understand how API limits work in an autonomous context. Truto does not retry, throttle, or apply backoff on rate limit errors. If your agent goes rogue and loops rapidly against the Midtrans API, Midtrans will reject the requests.

When Midtrans returns an HTTP 429 Too Many Requests, Truto passes that exact 429 error straight back to the caller. However, Truto normalizes the upstream rate limit information into standardized IETF headers: ratelimit-limit, ratelimit-remaining, and ratelimit-reset.

Your agent executor must be engineered to catch tool execution errors, read the ratelimit-reset header, and halt execution until the window clears. Do not rely on the proxy layer to silently absorb the errors.

sequenceDiagram
    participant App as Agent Executor
    participant LLM as LLM (Claude/GPT)
    participant Truto as Truto Tool Layer
    participant Midtrans as Midtrans API

    App->>LLM: "Refund order ORD-111"
    LLM-->>App: tool_call(midtrans_transactions_refund)
    App->>Truto: POST /integrated-account/<id>/tools/execute
    Truto->>Midtrans: POST /v2/ORD-111/refund
    Midtrans-->>Truto: 429 Too Many Requests
    Truto-->>App: 429 Error (headers: ratelimit-reset: 15)
    App->>App: Sleep for 15 seconds
    App->>Truto: Retry execution
    Truto->>Midtrans: POST /v2/ORD-111/refund
    Midtrans-->>Truto: 200 OK
    Truto-->>App: Normalized refund JSON
    App->>LLM: Tool Result (Success)
    LLM-->>App: "Refund processed successfully."

Implementation with LangChain

Here is how you bind these tools to an LLM and execute a real-world flow. Notice how we use bindTools() to pass the schemas to the model.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "@truto/langchainjs-toolset";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";
 
// 1. Initialize the Truto Tool Manager with your API token
const trutoManager = new TrutoToolManager({
  apiKey: process.env.TRUTO_API_KEY,
});
 
async function runMidtransAgent() {
  // 2. Fetch the tools for the specific connected Midtrans account
  // This account ID is generated when a user OAuths/keys into Midtrans via Truto
  const midtransAccountId = "integrated-account-midtrans-id";
  const tools = await trutoManager.getTools(midtransAccountId);
 
  // 3. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // 4. Bind the Midtrans tools to the model
  const llmWithTools = llm.bindTools(tools);
 
  // 5. Define a strict prompt to guide the financial agent
  const prompt = ChatPromptTemplate.fromMessages([
    [
      "system",
      "You are a financial operations agent managing a Midtrans account. " +
      "Always verify transaction status before issuing refunds. " +
      "If you encounter rate limits, note the failure and stop.",
    ],
    ["human", "{input}"],
    new MessagesPlaceholder("agent_scratchpad"),
  ]);
 
  // 6. Create the agent and executor
  const agent = await createOpenAIToolsAgent({
    llm: llmWithTools,
    tools,
    prompt,
  });
 
  const executor = new AgentExecutor({
    agent,
    tools,
    // We handle errors locally or pass them to the model to reason about
    handleParsingErrors: true,
  });
 
  console.log("Executing Midtrans Refund Flow...");
  
  const result = await executor.invoke({
    input: "Check the status of transaction TX-99012. If it is settled, issue a full refund.",
  });
 
  console.log("Agent Response:", result.output);
}
 
runMidtransAgent().catch(console.error);

When this script runs, the LLM will first call list_all_midtrans_transactions with TX-99012. If the JSON response indicates transaction_status: "settlement", the LLM will autonomously invoke midtrans_transactions_refund to complete the workflow.

If the initial API call returns a 429 error, the executor (depending on your implementation) will catch it, read the standardized ratelimit-reset headers supplied by Truto, and either backoff or return the error to the LLM for graceful degradation.

Architecting for Scale

Connecting Midtrans to AI agents transforms static payment gateways into dynamic, autonomous revenue operations systems. By standardizing the interaction layer, you remove the burden of BI-SNAP compliance, complex signature hashing, and endpoint discovery from your LLM.

Your engineers shouldn't be writing boilerplate payment API wrappers just to get an agent to refund a transaction. Expose the unified tools, configure your rate limit retry logic on the executor side, and focus your engineering cycles on improving the agent's reasoning capabilities.

FAQ

Can AI agents safely execute Midtrans payments?
Yes, by routing agent actions through a unified tool layer. This ensures strict schema validation and isolates the agent from managing complex BI-SNAP authentication, preventing hallucinations from breaking payment flows.
How do AI agents handle Midtrans rate limits?
Truto passes HTTP 429 Too Many Requests directly to the caller, while normalizing the headers to standard IETF formats (ratelimit-reset). The agent executor or framework is responsible for reading this header and applying backoff logic.
Does this support Midtrans GoPay tokenization?
Yes. The tool layer exposes specific methods for GoPay account binding, pre-authorization, and direct debit execution, allowing the agent to orchestrate the entire wallet billing cycle.
Can I use these Midtrans tools with LangChain or CrewAI?
Yes. Truto's /tools endpoint outputs standard JSON schemas that can be ingested by any agentic framework using native methods like .bindTools(), making it entirely framework-agnostic.

More from our Blog