---
title: "Connect Midtrans to ChatGPT: Manage Payments, Refunds & Subscriptions"
slug: connect-midtrans-to-chatgpt-manage-payments-refunds-subscriptions
date: 2026-09-07
author: Nidhi KN
categories: ["AI & Agents"]
excerpt: "Learn how to connect Midtrans to ChatGPT using an auto-generated MCP server. Generate secure endpoints to automate payments, QRIS generation, and refunds."
tldr: "Connect Midtrans to ChatGPT via a Model Context Protocol (MCP) server to execute API tasks using natural language. This guide covers setup, secure token generation, tool filtering, and multi-step payment workflows."
canonical: https://truto.one/blog/connect-midtrans-to-chatgpt-manage-payments-refunds-subscriptions/
---

# Connect Midtrans to ChatGPT: Manage Payments, Refunds & Subscriptions


If you need to connect Midtrans to ChatGPT to automate payment reconciliations, manage subscriptions, or orchestrate direct refunds, you need a [Model Context Protocol (MCP) server](https://truto.one/what-is-mcp-and-mcp-servers-and-how-do-they-work/). This server acts as the translation layer between ChatGPT's tool calls and Midtrans's complex financial APIs. You can either build and maintain this infrastructure yourself, or use a managed integration platform like Truto to dynamically generate a secure, authenticated MCP server URL based on the integration's documentation schemas.

If your team uses Claude, check out our guide on [connecting Midtrans to Claude](https://truto.one/connect-midtrans-to-claude-orchestrate-qris-va-transaction-status/) or explore our broader architectural overview on [connecting Midtrans to AI Agents](https://truto.one/connect-midtrans-to-ai-agents-automate-gopay-linking-billing-flows/).

Giving a Large Language Model (LLM) read and write access to a payment gateway like Midtrans is an engineering minefield. You have to handle deeply nested transaction payloads, navigate the split between standard REST and BI-SNAP protocols, and ensure the LLM cannot hallucinate arbitrary refund amounts. Every time Midtrans updates a payment method schema, your custom server code must be updated, redeployed, and tested.

This guide breaks down exactly how to use Truto to generate a secure, managed MCP server for Midtrans, connect it natively to ChatGPT, and execute complex financial workflows using natural language.

::cta{buttonText="Talk to us" buttonUrl="/book-a-demo/"}
Stop writing boilerplate API integration code. Let Truto generate secure, managed MCP servers for your AI agents in seconds.
:::

## The Engineering Reality of the Midtrans API

A custom MCP server is a self-hosted integration layer. While the [open MCP standard](https://truto.one/what-is-mcp-model-context-protocol-the-2026-guide-for-saas-pms/) provides a predictable way for models to discover tools, implementing it against Midtrans's API introduces highly specific challenges.

If you decide to build a custom MCP server for Midtrans, you own the entire API lifecycle. Here are the specific integration challenges that break standard CRUD assumptions when working with Midtrans:

### Heavily Nested Transaction Payloads
Midtrans requires extremely specific, nested JSON objects to create a transaction. A basic charge request requires `transaction_details` (containing `order_id` and `gross_amount`), `customer_details`, and optionally `item_details` arrays. When an LLM generates a function call, it tends to prefer flat structures. If your MCP server does not accurately map a flat query namespace back into Midtrans's deeply nested body requirements, the API will reject the payload with a 400 Bad Request. 

### The BI-SNAP vs REST Protocol Split
Midtrans operates multiple API paradigms depending on the payment rail. Core credit card charges and standard Virtual Accounts (VA) use traditional REST patterns. However, newer direct debit and QRIS MPM (Merchant Presented Mode) flows adhere to the Bank Indonesia National Standard Open API Payment (BI-SNAP) specifications. This standard enforces completely different header requirements, digital signature generation (using asymmetric and symmetric cryptography), and distinct error code formats. A custom MCP server must implement routing logic to handle signature generation natively, or the LLM's API calls will fail authorization.

### Rate Limits and Passthrough Errors
A critical architectural note: Truto does not retry, throttle, or apply backoff on rate limit errors. When an upstream API like Midtrans returns an HTTP 429, Truto passes that error directly to the caller. Truto normalizes the upstream rate limit information into standardized headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) per the IETF spec. The caller - meaning your agent framework or ChatGPT client - is entirely responsible for observing these headers and [implementing retry or backoff logic](https://truto.one/best-practices-for-handling-api-rate-limits-and-retries-across-multiple-third-party-apis/). Do not assume the infrastructure will magically absorb rate limit violations.

## Generating the Midtrans MCP Server

Truto [dynamically generates MCP tools from the underlying API documentation](https://truto.one/auto-generated-mcp-tools-for-ai-agents-a-2026-architecture-guide/). When you create an MCP server, Truto provisions an endpoint (`/mcp/:token`) scoped to a single integrated Midtrans account.

You can generate this server via the Truto UI or programmatically via the API.

### Method 1: Via the Truto UI

1. Navigate to the **Integrated Accounts** page in your Truto dashboard.
2. Select your connected Midtrans account.
3. Click the **MCP Servers** tab.
4. Click **Create MCP Server**.
5. Select your desired configuration (e.g., naming the server, applying tags like `"transactions"` or `"refunds"`, and filtering methods to `"read"` and `"write"`).
6. Click Save and copy the generated MCP server URL (it will look like `https://api.truto.one/mcp/a1b2c3d4e5f6...`).

### Method 2: Via the API

If you are dynamically provisioning AI workspaces for your own users, you can generate the MCP server programmatically. Make a `POST` request to the `/mcp` endpoint of your integrated account. Truto validates the configuration, generates a cryptographically hashed token, stores it in distributed KV storage, and returns the URL.

```bash
curl -X POST https://api.truto.one/integrated-account/$INTEGRATED_ACCOUNT_ID/mcp \
  -H "Authorization: Bearer $TRUTO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Midtrans Payment Ops Bot",
    "config": {
      "methods": ["read", "write"],
      "tags": ["transactions", "subscriptions", "qris"]
    }
  }'
```

The response contains the `url` required to connect ChatGPT.

## Connecting the MCP Server to ChatGPT

Once you have the `https://api.truto.one/mcp/<token>` URL, you need to register it with your client. ChatGPT supports remote MCP servers natively.

### Method A: Via the ChatGPT UI

1. In ChatGPT, navigate to **Settings** -> **Apps** -> **Advanced settings**.
2. Toggle **Developer mode** to ON.
3. Under the MCP servers / Custom connectors section, click to add a new server.
4. **Name:** "Midtrans (Truto)".
5. **Server URL:** Paste the Truto MCP URL.
6. Click **Add**. 

ChatGPT will immediately handshake with the Truto MCP router (sending an `initialize` JSON-RPC request) and download the available tool schemas.

### Method B: Via Manual Config File (Local Agents)

If you are testing the MCP server locally with an agent framework or Claude Desktop before deploying to ChatGPT, you can connect using the official Server-Sent Events (SSE) transport wrapper.

Add the following to your `mcp_config.json`:

```json
{
  "mcpServers": {
    "midtrans": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sse",
        "--url",
        "https://api.truto.one/mcp/YOUR_TRUTO_TOKEN_HERE"
      ]
    }
  }
}
```

## Security and Access Control

Exposing a payment gateway to an LLM requires strict boundary control. Truto provides four distinct mechanisms to constrain what the MCP server can execute:

*   **Method Filtering (`config.methods`):** Restrict the server to specific HTTP verbs. Passing `["read"]` ensures the agent can only execute `get` or `list` operations (like checking a transaction status), physically blocking it from executing `create`, `update`, or `delete` (like initiating a refund).
*   **Tag Filtering (`config.tags`):** Limit the tool surface area by integration resource tags. If you only want the agent to handle Virtual Accounts, pass `["virtual_accounts"]`. Tools for subscriptions or GoPay direct debits will be excluded entirely from the LLM's context.
*   **Expiration (`expires_at`):** Set an ISO datetime for temporary access. Truto relies on cloud infrastructure primitives and durable alarms to completely destroy the KV token and database record at the exact timestamp, preventing lingering access.
*   **Extra Authentication (`require_api_token_auth`):** By default, the cryptographically secure token in the URL serves as authentication. For defense-in-depth, setting this to `true` forces the MCP client to also pass a valid Truto API token in the `Authorization` header, ensuring only authorized internal systems can query the endpoint.

## Midtrans Hero Tools for ChatGPT

Truto maps Midtrans endpoints into heavily curated, documentation-backed tools. Here are the highest-leverage tools to expose to your AI agents.

### Create a Midtrans Transaction

**Tool Name:** `create_a_midtrans_transaction`

This is the core tool for initiating a new charge. It requires the agent to pass a `payment_type` (e.g., `credit_card`, `gopay`, `bank_transfer`) and the nested `transaction_details` containing the `order_id` and `gross_amount`.

> "Generate a new Midtrans transaction for order_id 'ORD-9938' for 150000 IDR using GoPay. Return the redirect URL for the customer."

### Refund a Settled Transaction

**Tool Name:** `midtrans_transactions_refund`

Reverses money back to the customer for settled transactions. It requires the `order_id_or_transaction_id`. The tool schema requires the agent to supply a `reason`, creating an audit trail in the Midtrans dashboard.

> "The customer for order 'ORD-4421' requested a cancellation. Issue a full refund via Midtrans and log the reason as 'Customer requested prior to shipping'."

### Generate a QRIS MPM Code

**Tool Name:** `midtrans_qris_create_qr`

Generates a Merchant Presented Mode QR code using the BI-SNAP protocol. The agent submits the transaction details, and the API returns the actions array containing the QR code generation URLs that you can forward to a frontend.

> "Create a QRIS payment code for a new walk-in order. The order ID is 'POS-773' and the amount is 50000 IDR."

### Initiate a GoPay Direct Debit

**Tool Name:** `midtrans_direct_debit_direct_debit_payment`

Executes a direct debit via GoPay Tokenization. This assumes the customer has already linked their account. The agent must provide the `partnerReferenceNo` and the `chargeToken` obtained from the prior account linking inquiry.

> "Charge the customer's linked GoPay account for their monthly usage invoice 'INV-102'. The partner reference number is 'REF-884' and the charge token is 'tok_abc123'."

### Create a Midtrans Subscription

**Tool Name:** `create_a_midtrans_subscription`

Establishes a recurring transaction schedule. The LLM handles the logic of defining the `schedule` object (interval and max intervals) and parsing the returned subscription status.

> "Set up a recurring monthly subscription for user 'usr_991'. Name it 'Pro Tier Monthly', amount 100000 IDR, using their saved token 'token_554'."

### Create a Virtual Account

**Tool Name:** `midtrans_virtual_account_create_va`

Generates a Virtual Account number via the BI-SNAP Core API. This is critical for B2B invoicing workflows where the agent needs to generate a dedicated bank transfer target for a specific client.

> "Generate a Virtual Account number for client 'Acme Corp' for invoice 'INV-993'. Total amount is 5000000 IDR. Give me the VA number and the expiry time."

### List All Midtrans Transactions

**Tool Name:** `list_all_midtrans_transactions`

Retrieves the status and details of a specific Midtrans transaction. This is the primary tool for agentic polling and status verification, returning `transaction_status`, `fraud_status`, and `gross_amount`.

> "Check the status of transaction 'ORD-1122'. Has it settled yet, or is it still pending?"

To view the complete schema definitions, required parameters, and the full inventory of tools available, check the [Midtrans integration page](https://truto.one/integrations/detail/midtrans).

## Workflows in Action

When you connect Midtrans to ChatGPT via Truto, the LLM stops being a text generator and becomes an autonomous payment operations agent. Here is how complex workflows play out in practice.

### Scenario 1: Dispute Resolution and Direct Refund

Customer support asks the agent to investigate an angry customer's duplicate charge and refund it if necessary.

> "Look up order 'ORD-9883'. If it is fully settled and the fraud status is safe, issue a direct refund to their GoPay account for the full amount and provide the refund reference number."

**Agent Execution Steps:**
1. The agent calls `list_all_midtrans_transactions` passing `order_id: "ORD-9883"`.
2. The Truto proxy executes the API request and returns the JSON payload indicating `transaction_status: "settlement"` and `payment_type: "gopay"`.
3. Satisfying its logical constraints, the agent decides to proceed with the refund.
4. The agent calls `midtrans_transactions_direct_refund`, mapping the `transaction_id` and the `gross_amount` from the previous step into the refund payload.
5. The agent parses the response and returns the `refund_chargeback_id` to the support rep.

```mermaid
sequenceDiagram
    participant User as Support Agent
    participant LLM as ChatGPT
    participant TrutoMCP as Truto MCP
    participant Midtrans as Midtrans API
    
    User->>LLM: "Look up ORD-9883 and refund if settled"
    LLM->>TrutoMCP: call list_all_midtrans_transactions(ORD-9883)
    TrutoMCP->>Midtrans: GET /v2/ORD-9883/status
    Midtrans-->>TrutoMCP: 200 OK (status: settlement)
    TrutoMCP-->>LLM: JSON Result
    
    LLM->>TrutoMCP: call midtrans_transactions_direct_refund(transaction_id)
    TrutoMCP->>Midtrans: POST /v2/ORD-9883/refund/direct
    Midtrans-->>TrutoMCP: 200 OK (refund_chargeback_id)
    TrutoMCP-->>LLM: JSON Result
    LLM-->>User: "Refund processed successfully. Ref: 12345"
```

### Scenario 2: QRIS Payment Link Generation

A sales representative needs to generate a quick payment link for a custom enterprise invoice while on a call.

> "Generate a QRIS payment for a new custom quote. Order ID 'QTE-441', amount 2500000 IDR. Give me the image URL so I can email it to the client."

**Agent Execution Steps:**
1. The agent calls `midtrans_qris_create_qr` with `payment_type: "qris"` and the required `transaction_details`.
2. The MCP server translates this into the BI-SNAP compliant payload and handles the signature generation required by Midtrans.
3. The API responds with the `actions` array.
4. The agent searches the array for the object where `name` equals `"generate-qr-code"`.
5. The agent returns the formatted `url` to the user.

### Scenario 3: Subscription Modification

A user wants to pause a recurring billing cycle due to a support escalation.

> "Check the subscription for 'sub_123'. If it is active, disable it so they aren't charged next week."

**Agent Execution Steps:**
1. The agent calls `get_single_midtrans_subscription_by_id` passing `id: "sub_123"`.
2. Upon seeing `status: "active"` in the return payload, the agent proceeds.
3. The agent calls `midtrans_subscriptions_disable` with `subscription_id: "sub_123"`.
4. The agent confirms to the user that future charges have been halted, while noting that pending retries may still execute based on the documentation schema provided by Truto.

## Abstracting the Payment Lifecycle

Building an AI agent that interfaces with Midtrans requires more than just formatting API calls. You must manage complex cryptography requirements for BI-SNAP, deeply nested JSON validation, and strict rate limit adherence. 

By leveraging Truto to auto-generate your MCP server, you offload the entire infrastructure burden. Your application treats Midtrans as a set of predictable, well-documented JSON-RPC tools, while Truto handles the protocol translation and token lifecycle behind the scenes. This allows your engineering team to focus on the agent's logic and workflow orchestration, rather than writing custom integration boilerplate.
