# Gọi thử trong 15 phút

> Lấy key sandbox, ký request và chạy một hồ sơ tới khi thẻ được phát hành.

Nguồn: https://www.finex.vn/developers/quickstart

Làm xong trang này, bạn sẽ có một hồ sơ chạy từ đầu tới lúc thẻ được phát hành trên sandbox. Sandbox không gọi VPBank thật và không cần dữ liệu khách thật.

| Môi trường | Base URL | API key |
|---|---|---|
| Development (sandbox) | `https://api.finex.studio/v1/partner` | `fx_test_…` |
| Production | `https://prod.finex.vn/v1/partner` | `fx_live_…`, cấp sau khi qua [danh sách go-live](https://www.finex.vn/developers/guides/go-live) |

> **Có AI agent?**
>
> Cài [Skill `finex-vpbank-card`](https://www.finex.vn/developers/tools/ai-skill) rồi nhờ Claude Code, Codex hoặc Antigravity: *"Tích hợp Finex mở thẻ VPBank vào backend của tôi"*. Agent sẽ viết sẵn phần ký request, callback và chạy thử trên sandbox.

> **Muốn bấm thử trước khi viết code?**
>
> Import [Postman collection](https://www.finex.vn/developers/tools/postman), điền key sandbox rồi bấm **Run collection**: cả luồng eKYC, Video KYC và các tình huống lỗi chạy xong trong vài giây.

### 1. Lấy key sandbox

Gửi email tới [hi@finex.vn](mailto:hi@finex.vn) kèm tên ứng dụng và người phụ trách kỹ thuật. Finex gửi lại ba giá trị, mỗi giá trị chỉ hiện **một lần**:

- `api_key` (`fx_test_…`): gửi trong header `x-api-key`.
- `api_secret` (`fx_test_sk_…`): dùng để ký request.
- `callback_secret` (`fx_test_cb_…`): dùng để kiểm tra callback Finex gửi tới.

Bạn gửi lại cho Finex `callback_url` (HTTPS public) và, nếu dùng Video KYC, các `redirect_url`. Lúc thử nghiệm có thể dùng ngrok hoặc Cloudflare Tunnel làm `callback_url`.

```bash
export FINEX_API_KEY="fx_test_..."
export FINEX_API_SECRET="fx_test_sk_..."
export FINEX_CALLBACK_SECRET="fx_test_cb_..."
```

Secret chỉ nằm trên server của bạn. Không đưa vào app, không commit lên git.

### 2. Thêm hàm ký request

Request nào cũng cần chữ ký HMAC. Chép hàm `finex()` dưới đây vào server; các ví dụ khác trong tài liệu đều dùng hàm này. Muốn hiểu chi tiết thì xem [Xác thực và ký request](https://www.finex.vn/developers/reference/authentication).

**Node.js**

```js
// finex.mjs — Node.js ≥ 18
import crypto from "node:crypto";

const BASE = "https://api.finex.studio"; // chỉ host, không kèm path
const API_KEY = process.env.FINEX_API_KEY;
const API_SECRET = process.env.FINEX_API_SECRET;

export async function finex(method, pathWithQuery, body, idempotencyKey = crypto.randomUUID()) {
  const ts = Math.floor(Date.now() / 1000).toString();
  const raw = body === undefined ? "" : JSON.stringify(body); // chỉ chuyển sang JSON một lần
  const signature = crypto
    .createHmac("sha256", API_SECRET)
    .update(`${ts}.${method}.${pathWithQuery}.${raw}`, "utf8")
    .digest("hex");
  const headers = { "x-api-key": API_KEY, "x-timestamp": ts, "x-signature": signature };
  if (raw) headers["Content-Type"] = "application/json";
  if (method === "POST" || method === "PUT") headers["Idempotency-Key"] = idempotencyKey;

  const res = await fetch(BASE + pathWithQuery, {
    method,
    headers,
    body: raw || undefined,
    signal: AbortSignal.timeout(90_000),
  });
  const json = await res.json();
  return { status: res.status, requestId: res.headers.get("x-request-id"), ...json };
}
```

**Python**

```python
# finex.py — Python 3, cần: pip install requests
import hashlib, hmac, json, os, time, uuid, requests

BASE = "https://api.finex.studio"
API_KEY, API_SECRET = os.environ["FINEX_API_KEY"], os.environ["FINEX_API_SECRET"]

def finex(method, path_with_query, body=None, idempotency_key=None):
    ts = str(int(time.time()))
    raw = "" if body is None else json.dumps(body, ensure_ascii=False, separators=(",", ":"))
    sig = hmac.new(API_SECRET.encode(), f"{ts}.{method}.{path_with_query}.{raw}".encode("utf-8"),
                   hashlib.sha256).hexdigest()
    headers = {"x-api-key": API_KEY, "x-timestamp": ts, "x-signature": sig}
    if raw:
        headers["Content-Type"] = "application/json"
    if method in ("POST", "PUT"):
        headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
    r = requests.request(method, BASE + path_with_query, headers=headers,
                         data=raw.encode("utf-8") if raw else None, timeout=90)
    return r.status_code, r.headers.get("x-request-id"), r.json()
```

**PHP**

```php
<?php
// finex.php — PHP 7.4+ với ext-curl
function uuidv4(): string {
    $d = random_bytes(16);
    $d[6] = chr(ord($d[6]) & 0x0f | 0x40);
    $d[8] = chr(ord($d[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($d), 4));
}

function finex(string $method, string $pathWithQuery, ?array $body = null, ?string $idemKey = null): array {
    $ts  = (string) time();
    $raw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $sig = hash_hmac('sha256', "$ts.$method.$pathWithQuery.$raw", getenv('FINEX_API_SECRET'));
    $headers = ['x-api-key: ' . getenv('FINEX_API_KEY'), "x-timestamp: $ts", "x-signature: $sig"];
    if ($raw !== '') $headers[] = 'Content-Type: application/json';
    if (in_array($method, ['POST', 'PUT'])) $headers[] = 'Idempotency-Key: ' . ($idemKey ?? uuidv4());
    $ch = curl_init('https://api.finex.studio' . $pathWithQuery);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $raw !== '' ? $raw : null, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 90,
    ]);
    $res = curl_exec($ch);
    return [curl_getinfo($ch, CURLINFO_HTTP_CODE), json_decode($res, true)];
}
```

**Java**

```java
// Finex.java — Java 17+ (java.net.http). rawBody là chuỗi JSON đã serialize MỘT lần.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HexFormat;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class Finex {
  static final String BASE = "https://api.finex.studio";
  static final String API_KEY = System.getenv("FINEX_API_KEY");
  static final String API_SECRET = System.getenv("FINEX_API_SECRET");
  static final HttpClient HTTP = HttpClient.newHttpClient();

  public static HttpResponse<String> call(String method, String pathWithQuery, String rawBody, String idempotencyKey)
      throws Exception {
    String ts = String.valueOf(System.currentTimeMillis() / 1000);
    String raw = rawBody == null ? "" : rawBody;
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String sig = HexFormat.of().formatHex(
        mac.doFinal((ts + "." + method + "." + pathWithQuery + "." + raw).getBytes(StandardCharsets.UTF_8)));

    HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE + pathWithQuery))
        .timeout(Duration.ofSeconds(90))
        .header("x-api-key", API_KEY)
        .header("x-timestamp", ts)
        .header("x-signature", sig);
    if (!raw.isEmpty()) b.header("Content-Type", "application/json");
    if (method.equals("POST") || method.equals("PUT"))
      b.header("Idempotency-Key", idempotencyKey != null ? idempotencyKey : UUID.randomUUID().toString());
    b.method(method, raw.isEmpty()
        ? HttpRequest.BodyPublishers.noBody()
        : HttpRequest.BodyPublishers.ofString(raw, StandardCharsets.UTF_8));
    return HTTP.send(b.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
  }
}
```

**.NET**

```csharp
// Finex.cs — .NET 6+. rawBody là chuỗi JSON đã serialize MỘT lần.
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;

public static class Finex
{
    const string Base = "https://api.finex.studio";
    static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(90) };
    static readonly string ApiKey = Environment.GetEnvironmentVariable("FINEX_API_KEY")!;
    static readonly string ApiSecret = Environment.GetEnvironmentVariable("FINEX_API_SECRET")!;

    public static async Task<HttpResponseMessage> CallAsync(
        string method, string pathWithQuery, string? rawBody = null, string? idempotencyKey = null)
    {
        var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        var raw = rawBody ?? "";
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(ApiSecret));
        var sig = Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes($"{ts}.{method}.{pathWithQuery}.{raw}")))
            .ToLowerInvariant();

        var req = new HttpRequestMessage(new HttpMethod(method), Base + pathWithQuery);
        req.Headers.Add("x-api-key", ApiKey);
        req.Headers.Add("x-timestamp", ts);
        req.Headers.Add("x-signature", sig);
        if (method is "POST" or "PUT")
            req.Headers.Add("Idempotency-Key", idempotencyKey ?? Guid.NewGuid().ToString());
        if (raw.Length > 0)
        {
            req.Content = new StringContent(raw, Encoding.UTF8);
            req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
        return await Http.SendAsync(req);
    }
}
```

**cURL**

```bash
# Bash + openssl: hữu ích để thử nhanh
TS=$(date +%s)
BODY='{"phone_number":"0900000001","email":"an@example.com"}'
SIG=$(printf '%s' "$TS.POST./v1/partner/leads/check.$BODY" \
  | openssl dgst -sha256 -hmac "$FINEX_API_SECRET" -hex | sed 's/^.* //')

curl -X POST "https://api.finex.studio/v1/partner/leads/check" \
  -H "x-api-key: $FINEX_API_KEY" \
  -H "x-timestamp: $TS" \
  -H "x-signature: $SIG" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
  -H "Content-Type: application/json" \
  --data-raw "$BODY"
```

> **Lỗi hay gặp nhất**
>
> Chuyển body sang JSON **một lần**, ký đúng chuỗi đó và gửi đúng chuỗi đó. Nếu ký một chuỗi rồi lại `JSON.stringify` lần nữa để gửi, hai chuỗi có thể lệch nhau và bạn sẽ nhận `401 INVALID_SIGNATURE`.

### 3. Gọi API đầu tiên

Số `0900000001` là số thử trên sandbox, sẽ đi hết luồng EKYC tới khi thẻ được phát hành.

**Node.js**

```js
import { finex } from "./finex.mjs";

const res = await finex("POST", "/v1/partner/leads/check", { phone_number: "0900000001", email: "an@example.com" });
console.log(res.status, res.data); // 200 { eligible: true, reason: null }
```

**Python**

```python
from finex import finex

status, request_id, res = finex("POST", "/v1/partner/leads/check", {"phone_number": "0900000001", "email": "an@example.com"})
print(status, res["data"])  # 200 {'eligible': True, 'reason': None}
```

**PHP**

```php
[$status, $res] = finex('POST', '/v1/partner/leads/check', ['phone_number' => '0900000001', 'email' => 'an@example.com']);
var_dump($status, $res['data']); // 200 ['eligible' => true, 'reason' => null]
```

```json
{ "success": true, "request_id": "req_0MH8Q2K1X4F2A9C0D1E2F3A4B5C6D7", "data": { "eligible": true, "reason": null }, "message": null }
```

Gặp `401`? Xem [mã lỗi](https://www.finex.vn/developers/reference/errors#INVALID_SIGNATURE). Nhớ ghi log `request_id`: khi cần hỗ trợ, Finex tra theo mã này.

### 4. Tạo hồ sơ và nhận callback

**Node.js**

```js
const res = await finex("POST", "/v1/partner/leads", {
  ip_address: "113.161.10.20", // IP thiết bị của khách, không phải IP server
  device: { user_agent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)" },
  full_name: "Nguyễn Văn An",
  phone_number: "0900000001",
  email: "an@example.com",
  dob: "15/08/1996",
  gender: "M",
  marital_status: "SINGLE",
  document_number: "079096001234",
  date_of_issue: "10/05/2021",
  date_of_expiry: "15/08/2036",
  place_of_issue: "Cuc canh sat QLHC ve TTXH",
  // Mã tỉnh/quận là mã VPBank lấy từ GET /v1/partner/reference-data/provinces và /districts, không tự đặt
  permanent_province: "b37b139eba3549c3a7550d4a1a1a414f", permanent_district: "34B108C4F54300D6E0530A2510AB2319", permanent_address: "12 Nguyễn Huệ",
  current_province: "b37b139eba3549c3a7550d4a1a1a414f", current_district: "D2255A062C2F0140E0530A2518AB85EC", current_address: "45 Lê Lợi",
  employer_status: "EMPL1",
  job_position: "POSH29",
  income_amount: 25000000,
  employer_name: "ADIDAS VIETNAM",
  employer_province: "b37b139eba3549c3a7550d4a1a1a414f", employer_district: "34B108C4F54300D6E0530A2510AB2319", employer_address: "1 Lê Duẩn",
  consent0: "DONG_Y", consent1: "DONG_Y", consent2: "DONG_Y", consent3: "KHONG_DONG_Y",
  consent_timestamp: new Date().toISOString(),
});
const leadId = res.data.lead.lead_id; // lưu ngay cùng mã khách hàng nội bộ của bạn
console.log(res.status, res.data.lead); // 201 { status: "SUBMITTED", next_step: null, ... }
```

Nhận `201` là VPBank đã nhận hồ sơ. Lưu `lead_id` lại. Khoảng 10 giây sau, `callback_url` của bạn nhận sự kiện `lead.ekyc_required`. Đoạn code nhận callback:

**Node.js (Express)**

```js
import express from "express";
import crypto from "node:crypto";

const app = express();
const CALLBACK_SECRETS = [process.env.FINEX_CALLBACK_SECRET, process.env.FINEX_CALLBACK_SECRET_OLD].filter(Boolean);

app.post("/finex/callback", express.raw({ type: "application/json" }), async (req, res) => {
  const ts = req.header("x-timestamp") ?? "";
  const sig = req.header("x-signature") ?? "";
  const raw = req.body.toString("utf8");
  const ok = CALLBACK_SECRETS.some((s) => {
    const expected = crypto.createHmac("sha256", s).update(`${ts}.${raw}`).digest("hex");
    return expected.length === sig.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
  });
  if (!ok) return res.sendStatus(401);

  const evt = JSON.parse(raw);
  if (await alreadyProcessed(evt.event_id)) return res.sendStatus(200); // chống trùng
  await enqueue(evt); // xử lý bất đồng bộ; không làm việc nặng ở đây
  res.sendStatus(200);
});
```

**Python (Flask)**

```python
import hashlib, hmac, json, os
from flask import Flask, request

app = Flask(__name__)
CALLBACK_SECRETS = [s for s in (os.environ.get("FINEX_CALLBACK_SECRET"), os.environ.get("FINEX_CALLBACK_SECRET_OLD")) if s]

@app.post("/finex/callback")
def finex_callback():
    ts, sig = request.headers.get("x-timestamp", ""), request.headers.get("x-signature", "")
    raw = request.get_data()  # bytes nguyên bản
    ok = any(hmac.compare_digest(hmac.new(s.encode(), ts.encode() + b"." + raw, hashlib.sha256).hexdigest(), sig)
             for s in CALLBACK_SECRETS)
    if not ok:
        return "", 401
    evt = json.loads(raw)
    if not already_processed(evt["event_id"]):
        enqueue(evt)
    return "", 200
```

### 5. Đi hết luồng

Trên sandbox, mỗi bước chờ (kết quả sơ bộ, hợp đồng, duyệt, phát hành) tự xong sau khoảng 10 giây. Ảnh chỉ cần là JPEG/PNG hợp lệ, OTP `000000` luôn đúng. Để code gọn, ví dụ này hỏi trạng thái liên tục; khi chạy thật hãy dựa vào callback. Không muốn chờ thì gọi [`POST /v1/partner/sandbox/leads/{id}/vpbank-event`](https://www.finex.vn/developers/sandbox#tự-đẩy-hồ-sơ-sang-bước-tiếp) để đẩy hồ sơ sang bước tiếp ngay.

**Node.js**

```js
import { finex } from "./finex.mjs";

const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(leadId, step) {
  for (let i = 0; i < 30; i++) {
    const { data } = await finex("GET", `/v1/partner/leads/${leadId}`);
    if (data.lead.next_step === step) return data.lead;
    await sleep(5000);
  }
  throw new Error(`Hết thời gian chờ next_step=${step}`);
}

// leadId lấy ở bước 4
await waitFor(leadId, "ocr");                                   // callback lead.ekyc_required
await finex("POST", `/v1/partner/leads/${leadId}/ocr`, { image_front: PNG, image_back: PNG });
await finex("POST", `/v1/partner/leads/${leadId}/liveness`, { images_liveness: [PNG], frames: [PNG] });
await finex("PUT", `/v1/partner/leads/${leadId}/additional-info`, {
  card_type: "MTSC",
  card_delivery_address: "CUADDR",
  reference1_fullname: "Tran Thi Binh",
  reference1_relationship: "SB", // anh/chị/em ruột, mã từ GET /v1/partner/reference-data/relationships
  reference1_mobile_phone_number: "0912345678",
  security_question: "Tên thú cưng đầu tiên của bạn là gì?",
  security_answer: "Milu",
});
await waitFor(leadId, "econtract");                             // callback lead.contract_ready
await finex("POST", `/v1/partner/leads/${leadId}/econtract/otp`);
await finex("POST", `/v1/partner/leads/${leadId}/econtract/confirm`, { otp: "000000" });
const lead = await waitFor(leadId, "none");                     // lead.approved → lead.issued
console.log(lead.status); // ISSUED
```

Xong. Tiếp theo, xem [Luồng tích hợp](https://www.finex.vn/developers/flow) để biết app cần những màn hình nào.
