Bài này viết một typed HttpClient trong .NET 8 để gọi API tra cứu tên chủ tài khoản của BankGateway, đăng ký qua IHttpClientFactory và dùng System.Text.Json cho dữ liệu trả về.

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: Client

CSHARPCode Example
using System.Net.Http.Json;

public record LookupData(string AccountName, string BankCode, string AccountNumber, int FeeChargedVnd);
public record LookupError(string Code, bool Retryable);
public record LookupResponse(bool Success, LookupData? Data, LookupError? Error);

public class BankGatewayClient(HttpClient http)
{
    public async Task<(LookupResponse Body, int Status)> LookupAsync(
        string bankCode, string accountNumber, CancellationToken ct = default)
    {
        var idempotencyKey = Guid.NewGuid().ToString(); // giữ nguyên khi retry

        for (var attempt = 1; ; attempt++)
        {
            using var req = new HttpRequestMessage(HttpMethod.Post, "/api/v1/lookup")
            {
                Content = JsonContent.Create(new { bankCode, accountNumber }),
            };
            req.Headers.Add("Idempotency-Key", idempotencyKey);

            using var res = await http.SendAsync(req, ct);
            var body = await res.Content.ReadFromJsonAsync<LookupResponse>(cancellationToken: ct);
            var status = (int)res.StatusCode;

            if (body!.Success || body.Error?.Retryable != true || attempt == 3)
                return (body, status);

            await Task.Delay(TimeSpan.FromMilliseconds(500 * Math.Pow(2, attempt)), ct);
        }
    }
}

Bước 2: Đăng ký trong Program.cs

CSHARPCode Example
builder.Services.AddHttpClient<BankGatewayClient>(c =>
{
    c.BaseAddress = new Uri("https://api.bankgateway.vn");
    c.Timeout = TimeSpan.FromSeconds(15);
    c.DefaultRequestHeaders.Add("X-API-Key", builder.Configuration["BankGateway:ApiKey"]);
});

Lưu key bằng User Secrets khi phát triển (dotnet user-secrets set "BankGateway:ApiKey" "bg_live_...") và biến môi trường BankGateway__ApiKey trên máy chủ.

Bước 3: Dùng trong API

CSHARPCode Example
app.MapPost("/verify-account", async (VerifyIn input, BankGatewayClient bg) =>
{
    var (body, status) = await bg.LookupAsync(input.BankCode, input.AccountNumber);
    return status switch
    {
        200 => Results.Ok(new { accountName = body.Data!.AccountName }),
        404 => Results.UnprocessableEntity("Số tài khoản không tồn tại"),
        422 => Results.UnprocessableEntity("Tài khoản không nhận được tiền"),
        _ => Results.Problem("Chưa xác minh được, vui lòng thử lại", statusCode: 503),
    };
});

record VerifyIn(string BankCode, string AccountNumber);

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í.

Đọc tiếp