Bài này dựng một endpoint FastAPI POST /verify-account gọi API tra cứu của BankGateway bằng httpx bất đồng bộ, dùng chung một client cho mọi request và trả lỗi rõ ràng cho frontend.

Thông số request

  • Endpoint: POST https://api.bankgateway.vn/api/v1/lookup
  • Header: X-API-Key: bg_live_... (tạo ở Dashboard › Khóa API), Content-Type: application/json, và nên có Idempotency-Key (chuỗi duy nhất cho mỗi lượt, tối đa 200 ký tự).
  • Body: {"bankCode": "MB", "accountNumber": "0783825888"}. bankCode nhận mã ngân hàng (MB, VCB, TCB...) hoặc BIN Napas (970422). accountNumber phải là chuỗi để giữ số 0 ở đầu.

API key chỉ dùng ở máy chủ. Không đặt key trong ứng dụng di động hay JavaScript chạy trên trình duyệt.

Bước 1: Cài đặt

BASHCode Example
pip install fastapi uvicorn httpx
export BANKGATEWAY_API_KEY=bg_live_xxxxxxxxxxxxxxxx

Bước 2: Ứng dụng FastAPI

PYTHONCode Example
# main.py
import os, uuid, asyncio
from contextlib import asynccontextmanager

import httpx
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

API_URL = "https://api.bankgateway.vn/api/v1/lookup"


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Một client dùng chung: giữ kết nối Keep-Alive, giảm độ trễ
    app.state.http = httpx.AsyncClient(timeout=15)
    yield
    await app.state.http.aclose()


app = FastAPI(lifespan=lifespan)


class VerifyIn(BaseModel):
    bank_code: str = Field(examples=["MB"])
    account_number: str = Field(min_length=4, max_length=30)


async def lookup(client: httpx.AsyncClient, bank_code: str, account_number: str) -> httpx.Response:
    headers = {
        "X-API-Key": os.environ["BANKGATEWAY_API_KEY"],
        "Idempotency-Key": str(uuid.uuid4()),  # giữ nguyên khi retry
    }
    payload = {"bankCode": bank_code, "accountNumber": account_number}
    for attempt in range(1, 4):
        res = await client.post(API_URL, json=payload, headers=headers)
        if res.status_code != 429 and res.status_code < 500:
            return res
        await asyncio.sleep(float(res.headers.get("Retry-After", 0.5 * 2 ** attempt)))
    return res


@app.post("/verify-account")
async def verify_account(body: VerifyIn):
    res = await lookup(app.state.http, body.bank_code, body.account_number)
    data = res.json()
    if data.get("success"):
        return {"account_name": data["data"]["accountName"]}
    code = data.get("error", {}).get("code")
    if res.status_code == 404:
        raise HTTPException(422, "Số tài khoản không tồn tại")
    if res.status_code == 422:
        raise HTTPException(422, f"Tài khoản không nhận được tiền ({code})")
    raise HTTPException(503, "Chưa xác minh được, vui lòng thử lại")

Bước 3: Chạy thử

BASHCode Example
uvicorn main:app --reload
curl -X POST localhost:8000/verify-account -H "Content-Type: application/json" \
  -d '{"bank_code": "MB", "account_number": "0783825888"}'

Xử lý kết quả trả về

  • HTTP 200: có data.accountName (viết hoa, không dấu). Hiển thị để người dùng xác nhận đúng người nhận. Có tính phí.
  • HTTP 404, error.code = NOT_FOUND: ngân hàng xác nhận số tài khoản không tồn tại. Báo người dùng kiểm tra lại. Có tính phí vì đã có kết quả từ ngân hàng.
  • HTTP 422: tài khoản đã đóng, không được nhận tiền hoặc ngân hàng không xác minh được. Không chuyển tiền. Không tính phí.
  • HTTP 429 hoặc 5xx: vượt giới hạn tốc độ, ngân hàng chậm hoặc bảo trì, error.retryable = true. Thử lại sau, giữ nguyên Idempotency-Key. Không tính phí.

Dùng SDK Python

SDK chỉ dùng thư viện chuẩn, hợp với script hoặc ứng dụng đồng bộ:

PYTHONCode Example
from bankgateway import BankGateway

bg = BankGateway(os.environ["BANKGATEWAY_API_KEY"])
print(bg.lookup("MB", "0783825888")["accountName"])

Đọc tiếp