Skip to main content

Rust SDK (hatang)

hatang is the server-side client for the Ha Tang API in Rust. It covers what a backend does most: put plans and purchases on the customer's profile, sync the AI assistant's knowledge, answer conversations, send email, create VietQR payments, and verify webhooks and IPN calls. The client is async (Hatang, on reqwest with rustls); the blocking feature adds hatang::blocking::Hatang with the same methods. It mirrors the Python SDK namespace for namespace.

Version

hatang 0.3.0 · Rust 1.89+ · crates.io · docs.rs · changelog: CHANGELOG.md in the crate

Before you start​

  • An API key (ht_...), created in the dashboard (see Authentication), with the scopes you call: crm:write for plans and purchases, chat:write for conversations and knowledge, email:send for email.
  • For the chat identity hash, the site's identity secret (Support → Channels → the site → Widget).

Install​

cargo add hatang
# a synchronous client too (scripts, CLIs, sync frameworks):
cargo add hatang --features blocking

or in Cargo.toml:

[dependencies]
hatang = "0.3.0"

Create a client​

let hatang = hatang::Hatang::from_env()?; // reads HATANG_API_KEY (and 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()?;

Keep one client for the life of the process and clone it where you need it: clones share one connection pool. Pass your own reqwest::Client with .http_client(...) for proxies or tests.

Blocking, with the blocking feature. It runs its own small Tokio runtime, so call it from plain threads, never from inside an async runtime:

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

Results and errors​

Bodies take any serde::Serialize value: the crate's 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 return Created { id, .. }. A call that does not succeed returns hatang::Error:

match hatang.chat.orders.get(&order_id).await {
Ok(order) => println!("{}", order["status"]),
// Unreachable (status 0), 429 rate_limit_exceeded, 409 concurrent_idempotent_requests or 5xx:
// retry with the same idempotency key, after e.retry_after() when it is set.
Err(e) if e.retryable() => { /* try again later */ }
// 429 daily_quota_exceeded: not retryable, sends work again after midnight UTC.
Err(e) if e.is_quota_exceeded() => { /* hold until tomorrow */ }
Err(hatang::Error::Api { status, name, message, .. }) => eprintln!("{status} {name}: {message}"),
Err(e) => eprintln!("{e}"),
}

name is the API's error code (validation_error, not_found, rate_limit_exceeded…). Field names are the API's snake_case.

Plans and purchases​

Put what a customer pays for on their profile, so agents and the AI assistant can answer "when does my plan renew?" from facts. Use the same user id you pass to identify in the chat.

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

// A plan sold on your website (or one you verified with the App Store / Google Play yourself).
hatang.chat.subscriptions.upsert(Platform::Web, &subscription.id, &SubscriptionUpsert {
status: "active".into(),
sku: Some("PRO-1M".into()), // the catalog product's SKU
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?;

// One-time purchases: credit packs, unlocks, courses. Send status "refunded" for the same id on a refund.
hatang.chat.purchases.upsert(Platform::Web, &order.id, &PurchaseUpsert {
store_product_id: "credits:300".into(), // your own code on the web; the store's product id in an 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?;

Store purchases use Platform::Ios (Apple originalTransactionId for plans, transactionId for one-time purchases) or Platform::Android (Play purchase token, or order id). Sending the same record again only updates it. See In-app purchases and subscriptions.

Knowledge​

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?; // the collection then holds exactly these
hatang.knowledge.search("đổi trả trong bao lâu", Some("vi"), None).await?;

See Knowledge API.

Conversations and customers​

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?; // internal note
hatang.chat.customers.update(&customer_id, &json!({ "stage": "won", "fields": { "plan": "pro" } })).await?;

list_with takes any other filter the API knows: hatang.chat.conversations.list_with(&json!({ "channel": "zalo" })). Products and orders: hatang.chat.products (list, search, get, create, update, remove) and hatang.chat.orders (list, get, create, update, payment_link).

Email​

use hatang::{Attachment, SendEmail};

let email = SendEmail::new("Shop <[email protected]>", ["[email protected]"], "Đơn hàng DH12")
.html("<p>Cảm ơn bạn!</p>")
.attach(Attachment::new("invoice.pdf", pdf_bytes).content_type("application/pdf")); // base64-encoded for you
let sent = hatang.emails.send(&email, Some(&format!("order-mail:{}", order.id))).await?;
hatang.batch.send(&emails).await?; // up to 100

Payments and IPN​

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?;

Check each IPN call with the raw body, before parsing it (axum shown):

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,
}
}

Webhooks​

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
}

Deliveries older than 5 minutes are refused; hatang::webhooks::verify_webhook_at takes your own tolerance and clock. verify_webhook and verify_ipn return a bool instead of an error. Headers can be an http::HeaderMap (axum, reqwest, hyper), a HashMap or a slice of (name, value) pairs.

Revenue (verified-revenue sites)​

For TrustMRR-style sites and your own reporting: the money that reached the business's bank accounts, past included. A key with only payments:read is enough; App Store and web subscriptions are not counted. See the Revenue API guide.

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

let account = hatang.revenue.account().await?; // business, masked bank accounts, scopes, read_only
if !account.read_only {
// refuse keys that can write, like Stripe secret keys
}
let events = hatang.revenue.events_since(RevenueBasis::Bank, Some("2025-01-01")).await?; // follows the cursor
let summary = hatang.revenue.summary(&RevenueSummaryParams {
interval: Some(RevenueInterval::Month),
..Default::default()
}).await?;
println!("last 30 days: {} đ", summary.totals.last_30_days);

events_since exists on the blocking client too. Responses are typed (RevenueAccount, RevenueEvent, RevenueSummary), unlike the rest of the crate.

Identity hash and purchase token​

use hatang::{identity_hash, purchase_token};

identity_hash(&user.id.to_string(), &identity_secret); // return {userId, hash} to the widget or the app
purchase_token("site_...", &user.id.to_string()); // StoreKit appAccountToken / Play obfuscatedAccountId

Both match Ha Tang's servers and the app SDKs value for value. See Identity verification.

Next steps​

View this page as Markdown