hatang 0.3.0

Official Rust client for the Ha Tang (Hạ Tầng) API: transactional email, live chat and support CRM, VietQR payments, AI chatbot knowledge and webhook verification. Async (Tokio) and blocking.
Documentation
# hatang

<!-- hatang:badge:start -->
[![crates.io](https://img.shields.io/crates/v/hatang)](https://crates.io/crates/hatang)
<!-- hatang:badge:end -->

[![docs.rs](https://img.shields.io/docsrs/hatang)](https://docs.rs/hatang)
[![MSRV 1.89](https://img.shields.io/badge/rustc-1.89+-blue)](https://hatang.dev/docs/guides/sdks/rust)
[![License: MIT](https://img.shields.io/crates/l/hatang)](https://crates.io/crates/hatang)

The official Rust client for the [Ha Tang](https://hatang.dev) (Hạ Tầng) API, the customer support and sales platform
for businesses in Vietnam. Call it from your Rust backend (axum, actix-web, workers, CLIs) to:

- **Send transactional email**: templates, attachments, scheduling, batches of up to 100, idempotency keys.
- **Run live chat and the support CRM**: answer conversations as an agent, add private notes, send product cards,
  update customers and export them as CSV.
- **Put plans and purchases on the customer's profile**: web, App Store and Google Play subscriptions and
  one-time purchases, so agents and the AI chatbot answer from facts.
- **Teach the AI assistant**: upsert, batch and sync knowledge documents, and test what it would find.
- **Take VietQR payments and orders**: create payments and payment links, then verify IPN calls.
- **Verify webhooks**: Standard Webhooks (Svix) signatures with replay protection, plus chat identity hashes and
  app store purchase tokens.

```bash
cargo add hatang
# without an async runtime:
cargo add hatang --features blocking
```

Rust 1.89+. An async client (`Hatang`, reqwest with rustls) and, with the `blocking` feature, a synchronous one
(`hatang::blocking::Hatang`) with the same methods.

## Quick start

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

#[tokio::main]
async fn main() -> hatang::Result<()> {
    let hatang = Hatang::from_env()?; // reads HATANG_API_KEY; or Hatang::new("ht_…")

    // What a customer pays for, from your backend (web sales included).
    hatang.chat.subscriptions.upsert(Platform::Web, "sub_123", &SubscriptionUpsert {
        status: "active".into(),
        sku: Some("PRO-1M".into()),               // finds the product in your catalog
        external_user_id: Some("user-42".into()), // the id you pass to identify() in the chat
        current_period_end: Some("2026-12-01T00:00:00Z".into()),
        amount: Some(99000.0),
        currency: Some("VND".into()),
        ..Default::default()
    }).await?;
    hatang.chat.purchases.upsert(Platform::Web, "order_981", &PurchaseUpsert {
        store_product_id: "credits.300".into(),
        sku: Some("XU-300".into()),
        kind: Some("consumable".into()),
        external_user_id: Some("user-42".into()),
        amount: Some(29000.0),
        currency: Some("VND".into()),
        ..Default::default()
    }).await?;
    Ok(())
}
```

Email, with an attachment and an idempotency key (a retry with the same key sends once):

```rust,no_run
# async fn run(hatang: hatang::Hatang, pdf: Vec<u8>) -> hatang::Result<()> {
use hatang::{Attachment, SendEmail};

let email = SendEmail::new("Mộc Hương <hello@mochuong.vn>", ["chi.ha@example.com"], "Hoá đơn DH000010")
    .html("<p>Cảm ơn chị đã mua hàng!</p>")
    .attach(Attachment::new("DH000010.pdf", pdf).content_type("application/pdf"));
let sent = hatang.emails.send(&email, Some("invoice-DH000010")).await?;
println!("{}", sent.id);
# Ok(()) }
```

Blocking (scripts, CLIs, sync frameworks; not inside an async runtime):

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

Bodies take any `serde::Serialize` value: the typed structs, or `serde_json::json!({...})` for fields they do not
cover. Every method returns the API's JSON as a `serde_json::Value` (create calls such as `emails.send` give
`Created { id, .. }`). A call that does not succeed returns `hatang::Error::Api` with `status` (0 when Ha Tang was not
reached), `name` (`validation_error`, `not_found`…), `message` and `retry_after` (the `retry-after` header).
`error.retryable()` is true when the same call can succeed later: unreachable, `429 rate_limit_exceeded`,
`409 concurrent_idempotent_requests` or 5xx; wait `error.retry_after()` when set, otherwise back off. The daily email
quota is not retryable that way: `error.is_quota_exceeded()` says when it is reached (it resets at midnight UTC).

```rust,no_run
# async fn run(hatang: hatang::Hatang, email: hatang::SendEmail) {
match hatang.emails.send(&email, Some("order-981")).await {
    Ok(sent) => println!("sent {}", sent.id),
    Err(e) if e.retryable() => { /* retry later with the same key, after e.retry_after() if set */ }
    Err(e) if e.is_quota_exceeded() => { /* hold until midnight UTC */ }
    Err(e) => eprintln!("not sent: {e}"), // fix the request; retrying as is won't help
}
# }
```

## What is in it

| Namespace | Methods |
|---|---|
| `chat.subscriptions` | `upsert`, `list`, `for_customer`, `purchase_token` |
| `chat.purchases` | `upsert`, `list`, `for_customer` |
| `chat.customers` | `list`, `get`, `update`, `conversations`, `export_csv` |
| `chat.conversations` | `list`, `list_with`, `get`, `update`, `messages`, `send`, `send_products` |
| `chat.products` | `list`, `search`, `get`, `create`, `update`, `remove` |
| `chat.orders` | `list`, `get`, `create`, `update`, `payment_link` |
| `knowledge` | `upsert`, `batch`, `sync`, `get`, `list`, `remove`, `search` |
| `emails`, `batch` | `send`, `get`, `list`, `update`, `cancel`; `batch.send` |
| `payments` | `create`, `get`, `list`, `cancel` |
| `events` | `send` |
| `revenue` | `account`, `events`, `events_since`, `summary` (typed) |

## Revenue (verified-revenue sites)

For TrustMRR-style sites: the money that reached a business's bank accounts, past included, read with a key that
has only `payments:read`. App store and web subscriptions are not counted.

```rust,ignore
use hatang::{Hatang, RevenueBasis};

let hatang = Hatang::new(key)?;
let account = hatang.revenue.account().await?;          // business, masked bank accounts, read_only
assert!(account.read_only, "refuse keys that can write");
let events = hatang.revenue.events_since(RevenueBasis::Bank, None).await?; // all history, oldest first
let summary = hatang.revenue.summary(&Default::default()).await?;          // totals.last_30_days, monthly buckets
```

See [Revenue API](https://hatang.dev/docs/guides/payments/revenue-api) and `examples/revenue.rs`.

## Helpers

```rust,ignore
use hatang::{construct_ipn_event, construct_webhook_event, identity_hash, purchase_token};

// Signed chat identity: send this as `hash` with userId to identify() in the widget or the app SDKs.
identity_hash("user-42", IDENTITY_SECRET);

// StoreKit appAccountToken / Google Play obfuscatedAccountId for one of your users.
purchase_token("site_…", "user-42");

// Webhooks (whsec_… secret) and payment IPN calls: pass the raw body, before JSON parsing.
let event = construct_webhook_event(&body, &headers, WEBHOOK_SECRET)?;
let ipn = construct_ipn_event(&body, &headers, SECRET_KEY)?;
```

Both return `Error::Signature` when the signature does not match; `verify_webhook` / `verify_ipn` return a `bool`.
`headers` can be an `http::HeaderMap` (axum, reqwest, hyper), a `HashMap` or a slice of `(name, value)` pairs.

A webhook endpoint in axum:

```rust,ignore
use axum::{body::Bytes, http::{HeaderMap, StatusCode}};

async fn hatang_webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
    match hatang::construct_webhook_event(&body, &headers, &std::env::var("HATANG_WEBHOOK_SECRET").unwrap()) {
        Ok(event) => {
            println!("{} {}", event["type"], event["data"]);
            StatusCode::OK
        }
        Err(_) => StatusCode::BAD_REQUEST,
    }
}
```

## Configuration

| Builder method | Environment | Default |
|---|---|---|
| `api_key` | `HATANG_API_KEY` | required |
| `base_url` | `HATANG_BASE_URL` | `https://api.hatang.dev` |
| `environment` | `HATANG_ENVIRONMENT` | the key's own |
| `timeout` | | 30 s |
| `http_client` | | a `reqwest::Client` of your own (proxies, pools, tests) |

```rust,no_run
let hatang = hatang::Hatang::builder()
    .api_key("ht_…")
    .timeout(std::time::Duration::from_secs(10))
    .build()?;
# Ok::<(), hatang::Error>(())
```

License: MIT

<!-- hatang:about:start -->
<!-- generated by scripts/sync-versions.ts from sdks/listing.json, do not edit -->
## About Ha Tang

[Ha Tang](https://hatang.dev) (Hạ Tầng) is a customer support platform for businesses in Vietnam: one inbox for your website, mobile app, Zalo, Messenger, Instagram, TikTok Shop, WhatsApp and email, with an AI assistant, plus a transactional email API, VietQR payments and e-invoices.

- Product: [hatang.dev]https://hatang.dev
- Guide: [Ha Tang Rust SDK]https://hatang.dev/docs/guides/sdks/rust ([Tiếng Việt]https://hatang.dev/vi/docs/guides/sdks/rust)
- API reference: [hatang]https://docs.rs/hatang
- REST API: [hatang.dev/docs/reference/api]https://hatang.dev/docs/reference/api
- AI coding agents: [MCP server and rules]https://hatang.dev/docs/guides/getting-started/ai-agents
- Changelog: [hatang.dev/docs/changelog]https://hatang.dev/docs/changelog
- Support: [hatang.dev/contact]https://hatang.dev/contact
<!-- hatang:about:end -->