hatang 0.1.1

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

crates.io

docs.rs MSRV 1.89 License: MIT

The official Rust client for the Ha Tang (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.
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

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

# 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):

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…) and message; error.retryable() is true when unreachable, 429 or 5xx.

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

Helpers

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:

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)
let hatang = hatang::Hatang::builder()
    .api_key("ht_…")
    .timeout(std::time::Duration::from_secs(10))
    .build()?;
# Ok::<(), hatang::Error>(())

License: MIT

About Ha Tang

Ha Tang (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.