# SDK Rust (`hatang`)

`hatang` là client phía server cho API Hạ Tầng bằng Rust. Nó lo những việc backend hay làm nhất: đưa gói và giao dịch mua lên hồ sơ khách, đồng bộ kiến thức cho trợ lý AI, trả lời hội thoại, gửi email, tạo thanh toán VietQR, và xác minh webhook, IPN. Client mặc định là async (`Hatang`, chạy trên reqwest với rustls); feature `blocking` thêm `hatang::blocking::Hatang` với cùng các hàm. Các namespace giống hệt [SDK Python](./python.md).

> **Info: Phiên bản**
>
> `hatang` **0.3.0** · Rust 1.89+ · [crates.io](https://crates.io/crates/hatang) · [docs.rs](https://docs.rs/hatang) · changelog: `CHANGELOG.md` trong crate

## Trước khi bắt đầu

- Một API key (`ht_...`), tạo trong dashboard (xem [Xác thực](https://hatang.dev/vi/docs/guides/getting-started/authentication.md)), có scope cho những gì bạn gọi: `crm:write` cho gói và giao dịch mua, `chat:write` cho hội thoại và kiến thức, `email:send` cho email.
- Với identity hash cho chat: identity secret của site (**Hỗ trợ → Kênh → site → Widget**).

## Cài đặt

```bash
cargo add hatang
# thêm client đồng bộ (script, CLI, framework đồng bộ):
cargo add hatang --features blocking
```

hoặc trong `Cargo.toml`:

```toml
[dependencies]
hatang = "0.3.0"
```

## Tạo client {#client}

```rust
let hatang = hatang::Hatang::from_env()?; // đọc HATANG_API_KEY (và HATANG_BASE_URL, HATANG_ENVIRONMENT)
let hatang = hatang::Hatang::new("ht_...")?;
let hatang = hatang::Hatang::builder()
    .api_key("ht_...")
    .base_url("http://localhost:3001")
    .timeout(std::time::Duration::from_secs(10))
    .build()?;
```

Giữ một client suốt vòng đời process và clone ở nơi cần dùng: các bản clone dùng chung một connection pool. Truyền `reqwest::Client` của riêng bạn qua `.http_client(...)` khi cần proxy hoặc viết test.

Blocking, với feature `blocking`. Client này tự chạy một runtime Tokio nhỏ, nên chỉ gọi từ thread thường, không gọi bên trong một async runtime:

```rust
let hatang = hatang::blocking::Hatang::from_env()?;
let hits = hatang.knowledge.search("hoàn tiền", Some("vi"), Some(3))?;
```

## Kết quả và lỗi {#errors}

Body nhận mọi giá trị `serde::Serialize`: các struct có kiểu của crate, hoặc `serde_json::json!({...})` cho những trường struct chưa có. Mọi hàm trả về JSON của API dưới dạng `serde_json::Value`; các lệnh tạo như `emails.send` trả về `Created { id, .. }`. Gọi không thành công thì trả về `hatang::Error`:

```rust
match hatang.chat.orders.get(&order_id).await {
    Ok(order) => println!("{}", order["status"]),
    // Không tới được (status 0), 429 rate_limit_exceeded, 409 concurrent_idempotent_requests hoặc 5xx:
    // thử lại với cùng idempotency key, sau e.retry_after() nếu có.
    Err(e) if e.retryable() => { /* thử lại sau */ }
    // 429 daily_quota_exceeded: không thử lại được, gửi lại được sau nửa đêm UTC.
    Err(e) if e.is_quota_exceeded() => { /* chờ tới ngày mai */ }
    Err(hatang::Error::Api { status, name, message, .. }) => eprintln!("{status} {name}: {message}"),
    Err(e) => eprintln!("{e}"),
}
```

`name` là mã lỗi của API (`validation_error`, `not_found`, `rate_limit_exceeded`…). Tên trường giữ nguyên snake_case của API.

## Gói và giao dịch mua {#purchases}

Đưa những gì khách đang trả tiền lên hồ sơ khách, để nhân viên và trợ lý AI trả lời "gói của tôi khi nào gia hạn?" bằng dữ liệu thật. Dùng đúng user id bạn truyền vào `identify` trong chat.

```rust
use hatang::{Platform, PurchaseUpsert, SubscriptionUpsert};

// Gói bán trên website (hoặc gói bạn đã tự xác minh với App Store / Google Play).
hatang.chat.subscriptions.upsert(Platform::Web, &subscription.id, &SubscriptionUpsert {
    status: "active".into(),
    sku: Some("PRO-1M".into()),                // SKU của sản phẩm trong danh mục
    external_user_id: Some(user.id.to_string()),
    started_at: Some("2026-10-01T00:00:00Z".into()),
    current_period_end: Some("2026-11-01T00:00:00Z".into()),
    auto_renew: Some(false),
    amount: Some(99000.0),
    currency: Some("VND".into()),
    ..Default::default()
}).await?;

// Mua một lần: gói xu, mở khoá, khoá học. Khi hoàn tiền, gửi status "refunded" cho cùng id.
hatang.chat.purchases.upsert(Platform::Web, &order.id, &PurchaseUpsert {
    store_product_id: "credits:300".into(),   // mã của bạn trên web; product id của store trong app
    sku: Some("XU-300".into()),
    kind: Some("consumable".into()),
    external_user_id: Some(user.id.to_string()),
    amount: Some(29000.0),
    currency: Some("VND".into()),
    ..Default::default()
}).await?;
```

Giao dịch trên store dùng `Platform::Ios` (originalTransactionId của Apple cho gói, transactionId cho mua một lần) hoặc `Platform::Android` (purchase token của Play, hoặc order id). Gửi lại cùng bản ghi chỉ cập nhật nó. Xem [Mua trong ứng dụng và gói thuê bao](https://hatang.dev/vi/docs/guides/support/in-app-purchases.md#backend-only).

## Kiến thức {#knowledge}

```rust
use hatang::KnowledgeDocument;

let docs: Vec<KnowledgeDocument> = articles.iter().map(|a| KnowledgeDocument {
    external_id: Some(format!("help:{}", a.slug)),
    url: Some(a.url.clone()),
    locale: Some("vi".into()),
    ..KnowledgeDocument::new(&a.title, &a.body)
}).collect();
hatang.knowledge.sync("help", &docs).await?; // bộ sưu tập khi đó chỉ còn đúng các tài liệu này
hatang.knowledge.search("đổi trả trong bao lâu", Some("vi"), None).await?;
```

Xem [Knowledge API](https://hatang.dev/vi/docs/guides/support/knowledge-api.md).

## Hội thoại và khách hàng {#chat}

```rust
use hatang::resources::ConversationListParams;
use hatang::ChatMessage;
use serde_json::json;

let open = hatang.chat.conversations.list(&ConversationListParams {
    status: Some(vec!["open".into()]),
    unanswered: Some(true),
    ..Default::default()
}).await?;
hatang.chat.conversations.send(&conv_id, &ChatMessage::new("Đơn của bạn đã được gửi."), Some(&format!("shipped:{}", order.id))).await?;
hatang.chat.conversations.send(&conv_id, &ChatMessage::new("Khách VIP").private(), None).await?; // ghi chú nội bộ
hatang.chat.customers.update(&customer_id, &json!({ "stage": "won", "fields": { "plan": "pro" } })).await?;
```

`list_with` nhận mọi bộ lọc khác mà API hỗ trợ: `hatang.chat.conversations.list_with(&json!({ "channel": "zalo" }))`. Sản phẩm và đơn hàng: `hatang.chat.products` (`list`, `search`, `get`, `create`, `update`, `remove`) và `hatang.chat.orders` (`list`, `get`, `create`, `update`, `payment_link`).

## Email {#emails}

```rust
use hatang::{Attachment, SendEmail};

let email = SendEmail::new("Shop <orders@shop.vn>", ["an@example.com"], "Đơn hàng DH12")
    .html("<p>Cảm ơn bạn!</p>")
    .attach(Attachment::new("invoice.pdf", pdf_bytes).content_type("application/pdf")); // tự mã hoá base64
let sent = hatang.emails.send(&email, Some(&format!("order-mail:{}", order.id))).await?;
hatang.batch.send(&emails).await?; // tối đa 100
```

## Thanh toán và IPN {#payments}

```rust
let payment = hatang.payments.create(&hatang::CreatePayment {
    description: Some("DH12".into()),
    ipn_url: Some("https://shop.vn/hatang/ipn".into()),
    ..hatang::CreatePayment::new(199_000)
}, None).await?;
```

Kiểm tra từng lần gọi IPN bằng body gốc, trước khi parse (ví dụ với axum):

```rust
async fn ipn(headers: axum::http::HeaderMap, body: axum::body::Bytes) -> axum::http::StatusCode {
    match hatang::construct_ipn_event(&body, &headers, &secret_key()) {
        Ok(event) if event["data"]["status"] == "paid" => { mark_paid(&event["data"]["metadata"]["order_id"]); axum::http::StatusCode::OK }
        Ok(_) => axum::http::StatusCode::OK,
        Err(_) => axum::http::StatusCode::BAD_REQUEST,
    }
}
```

## Webhook {#webhooks}

```rust
async fn webhook(headers: axum::http::HeaderMap, body: axum::body::Bytes) -> axum::http::StatusCode {
    let Ok(event) = hatang::construct_webhook_event(&body, &headers, &webhook_secret()) else { // whsec_...
        return axum::http::StatusCode::BAD_REQUEST;
    };
    if event["type"] == "chat.message.created" {
        // ...
    }
    axum::http::StatusCode::OK
}
```

Lần gửi cũ hơn 5 phút bị từ chối; `hatang::webhooks::verify_webhook_at` cho bạn tự đặt ngưỡng và đồng hồ. `verify_webhook` và `verify_ipn` trả về `bool` thay vì lỗi. Header có thể là `http::HeaderMap` (axum, reqwest, hyper), `HashMap` hoặc slice các cặp `(tên, giá trị)`.

## Doanh thu (site xác minh doanh thu) {#revenue}

Cho các site kiểu TrustMRR và báo cáo của chính bạn: số tiền đã về tài khoản ngân hàng của doanh nghiệp, kể cả trong quá khứ. Key chỉ có `payments:read` là đủ; gói thuê bao App Store và web không được tính. Xem [hướng dẫn Revenue API](https://hatang.dev/vi/docs/guides/payments/revenue-api.md).

```rust
use hatang::resources::{RevenueInterval, RevenueSummaryParams};
use hatang::RevenueBasis;

let account = hatang.revenue.account().await?;          // doanh nghiệp, tài khoản ngân hàng (che số), scope, read_only
if !account.read_only {
    // từ chối key có quyền ghi, như secret key của Stripe
}
let events = hatang.revenue.events_since(RevenueBasis::Bank, Some("2025-01-01")).await?; // tự đi theo cursor
let summary = hatang.revenue.summary(&RevenueSummaryParams {
    interval: Some(RevenueInterval::Month),
    ..Default::default()
}).await?;
println!("30 ngày gần nhất: {} đ", summary.totals.last_30_days);
```

`events_since` có cả trên client blocking. Kết quả có kiểu đầy đủ (`RevenueAccount`, `RevenueEvent`, `RevenueSummary`), khác với phần còn lại của crate.

## Identity hash and purchase token {#identity-hash}

```rust
use hatang::{identity_hash, purchase_token};

identity_hash(&user.id.to_string(), &identity_secret); // trả {userId, hash} cho widget hoặc app
purchase_token("site_...", &user.id.to_string());       // StoreKit appAccountToken / Play obfuscatedAccountId
```

Cả hai cho kết quả giống hệt server Hạ Tầng và các SDK app. Xem [Xác minh danh tính](https://hatang.dev/vi/docs/guides/support/web-widget/identity-verification.md).

## Tiếp theo

- [Tài liệu API trên docs.rs](https://docs.rs/hatang)
- [Mua trong ứng dụng và gói thuê bao](https://hatang.dev/vi/docs/guides/support/in-app-purchases.md)
- [Knowledge API](https://hatang.dev/vi/docs/guides/support/knowledge-api.md)
- [REST API](https://hatang.dev/vi/docs/reference/api.md) cho những gì SDK chưa bọc

Source: https://hatang.dev/vi/docs/guides/sdks/rust
