TCONNECT
Blog

Payment Gateway integration: an end-to-end guide for developers

A practical guide to integrating a Payment Gateway with the TConnect API: from authentication, AES encryption and creating a transaction to receiving IPN callbacks and handling edge cases.

T
TCONNECT Team February 18, 2026· 5 min read

Overview

A Payment Gateway is the bridge between your application and the banking / e-wallet systems. When a customer pays, the data passes through the gateway to authenticate, route and confirm the transaction.

The TConnect Payment Gateway supports:

  • Domestic / international cards (Napas, Visa, Mastercard, JCB)
  • E-wallets (MoMo, ZaloPay, VNPay)
  • VietQR (bank transfer)
  • Installments through partner banks

One API solution, every method, with no need to integrate each gateway separately.


The overall architecture

[Frontend]  →  POST /create-order  →  [Backend của bạn]
                                             │
                                   POST /openapi/v1/payment/create
                                             │
                                       [TConnect API]
                                             │
                               ┌─────────────┴──────────────┐
                          [Ngân hàng]                  [Ví điện tử]
                               │
                    redirect_url / deeplink trả về
                               │
                       [Khách thanh toán]
                               │
                    IPN Callback → [Backend của bạn]
                               │
                    Cập nhật trạng thái đơn hàng

Step 1: Authenticate and get an Access Token

TConnect uses OAuth2 with a client_id / client_secret pair. The token is valid for 36,000 seconds (10 hours).

function login(base_url, username, password, client_id, client_secret):
    payload = {
        username:      username,
        password:      password,
        client_id:     client_id,
        client_secret: client_secret,
        grant_type:    "password"
    }
    POST {base_url}/openapi/v1/auth/login
        body: payload
 
    return response.access_token, response.refresh_token

Note: Cache the access_token and do not call login before every request. Use the refresh_token to renew it when it expires.


Step 2: Encrypt the payload with AES-256-CBC

Every request body sent to TConnect must be encrypted with AES-256-CBC. The IV (16 bytes) is prepended to the ciphertext, and the whole thing is hex-encoded.

function encrypt_payload(data, aes_key):
    iv         = generate random 16 bytes
    plaintext  = json_encode(data) as UTF-8 bytes
    ciphertext = AES_256_CBC_encrypt(plaintext, key=aes_key, iv=iv)
    return hex_encode(iv + ciphertext)
 
function decrypt_response(hex_data, aes_key):
    raw        = hex_decode(hex_data)
    iv         = first 16 bytes of raw
    ciphertext = remaining bytes of raw
    plaintext  = AES_256_CBC_decrypt(ciphertext, key=aes_key, iv=iv)
    return json_decode(plaintext)

Step 3: Create a payment transaction

function create_payment(base_url, partner_code, access_token, aes_key, order_data):
    payload = {
        order_id:       order_data.id,
        amount:         order_data.amount,   // VND, không có số thập phân
        currency:       "VND",
        description:    order_data.description,
        return_url:     "https://yoursite.com/payment/return",
        cancel_url:     "https://yoursite.com/payment/cancel",
        ipn_url:        "https://yoursite.com/webhook/ipn",
        payment_method: "all",               // hoặc "card", "wallet", "qr"
        buyer_info: {
            name:  order_data.customer_name,
            email: order_data.customer_email,
            phone: order_data.customer_phone
        }
    }
 
    encrypted = encrypt_payload(payload, aes_key)
 
    POST {base_url}/openapi/v1/payment/create
        body: { data: encrypted }
        headers:
            Authorization:  "Bearer {access_token}"
            Partner-Code:   partner_code
            Content-Type:   "application/json"
 
    result = decrypt_response(response.data, aes_key)
    return result.payment_url   // redirect khách đến đây

Once you have the payment_url, redirect your frontend to this URL. The customer then picks a payment method and completes the payment.


Step 4: Receive the IPN Callback

When a transaction finishes (success or failure), TConnect POSTs to the ipn_url you provided.

// IPN endpoint: POST /webhook/ipn
function ipn_handler(request):
    body = parse_json(request)
 
    // 1. Decrypt
    txn = decrypt_response(body.data, AES_KEY)
 
    // 2. Idempotency — tránh xử lý 2 lần
    if cache.get("ipn:{txn.request_id}") exists:
        return { status: "ok" }
    cache.set("ipn:{txn.request_id}", ttl=86400)
 
    // 3. Xử lý theo trạng thái
    if txn.status == "SUCCESS":
        mark_order_paid(txn.order_id, txn.amount)
    else if txn.status == "FAILED":
        mark_order_failed(txn.order_id)
 
    // 4. Bắt buộc trả 200 — TConnect retry nếu không nhận được
    return { status: "ok" }

Important: Always return HTTP 200, even when you have already processed the event. If you return an error, TConnect will retry, which leads to duplicate processing.


Step 5: Check transaction status (polling)

Besides IPN, you can actively query the status:

function check_payment_status(base_url, partner_code, access_token, aes_key, order_id):
    payload   = { order_id: order_id }
    encrypted = encrypt_payload(payload, aes_key)
 
    POST {base_url}/openapi/v1/payment/query
        body: { data: encrypted }
        headers:
            Authorization: "Bearer {access_token}"
            Partner-Code:  partner_code
 
    return decrypt_response(response.data, aes_key)

Use polling as a fallback when IPN is delayed, for example: poll after 5 minutes if no IPN has arrived.


Handling common edge cases

SituationHow to handle it
Customer closes the browser after payingThe IPN still fires, so process it normally
Network error, the IPN never arrivesTConnect retries automatically · Add a cronjob to poll the status after 15 minutes
Customer pays twice for the same orderIdempotency check via request_id
return_url redirects but there is no IPN yetDo not mark paid at return_url, wait for the IPN
Token expires mid-flowCatch 401 → refresh the token → retry the request

Checklist before going live

  • Test the full payment flow on Sandbox
  • Implement idempotency for the IPN handler
  • Log the entire IPN payload (for debugging later)
  • Configure retry/fallback for when IPN is delayed
  • Do not use return_url to mark paid, always use IPN
  • Rate limit the IPN endpoint (to avoid DDoS)
  • Rotate the aes_key and client_secret on a schedule

Conclusion

Integrating a Payment Gateway is not complicated once you understand the flow correctly: create the transaction → redirect → IPN callback. The most important part is handling IPN safely with idempotency and never trusting return_url to confirm a successful payment.

The TConnect Sandbox is free and requires no KYB, so you can start today.

Topics
payment-gatewaypayment-apiintegrationdeveloper

Start integrating today

Free sandbox · Full API docs · Technical support