A crypto payment API in Rust: reqwest and axum
easyway has no Rust crate, and a Rust backend doesn't need one. Creating an invoice is one HTTPS request and checking a webhook is one HMAC. This post builds both with crates most Rust web projects already have: reqwest for the call, axum for the endpoint, and hmac + sha2 for the signature. We compiled it with Rust 1.97, ran it against a local stand-in of the API and against the live API, and sent it real and forged webhook deliveries.
The pieces
| File | Job |
|---|---|
src/easyway.rs | POST /v1/invoices and return the invoice, whose payment_url you redirect the customer to. |
src/webhook.rs | Check the X-Webhook-Signature header of a delivery. |
src/main.rs | The axum route that receives invoice.paid, checks it and marks the order paid. |
Between the two calls the customer pays on the hosted checkout: they pick a coin and network, see the amount and a QR code, and the page follows the payment by itself. Create the API key in Dashboard → Developers. An sk_test_… key only touches sandbox data, so you can run everything below before real money moves.
[package]
name = "shop"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
hex = "0.4"
hmac = "0.12"
reqwest = { version = "0.12", features = ["json"] }
serde_json = "1"
sha2 = "0.10"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }1. Create the invoice with reqwest
// src/easyway.rs: create an invoice. reqwest + serde_json, no SDK.
use std::time::Duration;
use serde_json::{json, Value};
#[derive(Debug)]
pub enum Error {
Api { status: u16, code: String }, // fix the request (or retry 429/5xx)
Network(reqwest::Error), // timeout or connection: retry with the same order id
}
pub struct Client { http: reqwest::Client, base: String, key: String }
impl Client {
pub fn from_env() -> Client {
let http = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15)) // reqwest has no total timeout by default
.build()
.expect("http client");
Client {
http,
base: std::env::var("EASYWAY_API").unwrap_or_else(|_| "https://api.easyway.cash".into()),
key: std::env::var("EASYWAY_API_KEY").expect("EASYWAY_API_KEY"),
}
}
/// amount_cents is an integer: 14900 -> "149.00". Never an f64.
pub async fn create_invoice(&self, order_id: u64, amount_cents: u64) -> Result<Value, Error> {
let body = json!({
"amount": format!("{}.{:02}", amount_cents / 100, amount_cents % 100),
"currency": "USD",
"order_id": order_id.to_string(),
"description": format!("Order #{order_id}"),
"success_url": format!("https://shop.example.com/thanks?order={order_id}"),
"cancel_url": "https://shop.example.com/cart",
});
let res = self.http
.post(format!("{}/v1/invoices", self.base))
.bearer_auth(&self.key)
.header("Idempotency-Key", format!("shop-order-{order_id}")) // 8-128 chars
.json(&body)
.send()
.await
.map_err(Error::Network)?;
let status = res.status();
let json: Value = res.json().await.unwrap_or(Value::Null); // an HTML 502 is not JSON
if status.is_success() {
return Ok(json); // id, status "pending", payment_url, ...
}
// Most errors put a class in "error" and the code in "message".
let field = |k: &str| json.get(k).and_then(Value::as_str).map(str::to_owned);
let class = ["bad_request", "unauthorized", "forbidden", "not_found", "conflict"];
let code = match field("error") {
Some(e) if class.contains(&e.as_str()) => field("message"),
other => other,
};
Err(Error::Api { status: status.as_u16(), code: code.unwrap_or_else(|| "unknown_error".into()) })
}
}| Detail | Why |
|---|---|
| Integer cents, never f64 | The API takes decimal strings such as "149.00". Keep money as integer cents and format it at the edge; 0.1 + 0.2 as f64 is 0.30000000000000004, and serde_json would send that number as is (see amounts as strings). |
| Idempotency-Key | Built from the order id, so a retry after a timeout returns the same invoice instead of a second one. It must be 8–128 characters of letters, digits and _ - : .; the shop-order- prefix keeps short ids valid. |
| Timeouts | A reqwest::Client has no overall timeout unless you set one. Without it, a stalled connection holds the task until the OS gives up. |
| 4xx is not an Err | send() returns Ok for a 401 or a 502. Check status(), then read the code: most errors put a class in error and the code in message (see errors in the docs). |
| Two error kinds | Error::Network (timeout, refused connection) is safe to retry with the same order id. Error::Api needs a fix, except 429 and 5xx (see which errors to retry). |
Against a local stand-in of the API, cargo run -- 2048 printed the payment_url, and the request carried "amount":"149.00" and Idempotency-Key: shop-order-2048. A stand-in answering 502 with an HTML page gave Api { status: 502, code: "unknown_error" }, a closed port gave Network(…), and the live API with a made-up key gave Api { status: 401, code: "invalid_api_key" }. To bill in a coin instead of USD, set currency to an asset id such as "USDT_TRC20" (see pricing in USD or in the coin); to show only some coins, add allowed_assets (see limiting the checkout).
2. Verify the webhook with hmac
Each delivery carries X-Webhook-Signature: t=…,v1=…, where v1 is the lower-case hex HMAC-SHA256 of t + "." + raw body under the endpoint's signing secret.
// src/webhook.rs: verify X-Webhook-Signature. hmac + sha2 + hex.
use hmac::{Hmac, Mac};
use sha2::Sha256;
const TOLERANCE: i64 = 300; // seconds
pub fn valid(header: &str, raw_body: &[u8], secret: &[u8], now: i64) -> bool {
let (mut t, mut v1) = ("", "");
for part in header.split(',') {
match part.split_once('=') {
Some(("t", v)) => t = v,
Some(("v1", v)) => v1 = v,
_ => {}
}
}
// Digits only: str::parse::<i64>() alone also accepts "+1764…".
if t.is_empty() || t.len() > 12 || !t.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
let ts: i64 = t.parse().unwrap();
if (now - ts).abs() > TOLERANCE {
return false;
}
let Ok(sig) = hex::decode(v1) else { return false };
let mut mac = Hmac::<Sha256>::new_from_slice(secret).expect("any key length");
mac.update(t.as_bytes());
mac.update(b".");
mac.update(raw_body);
mac.verify_slice(&sig).is_ok() // constant time; a wrong length is just false
}And the axum side, which also runs the invoice call from the command line:
// src/main.rs: the webhook endpoint (axum 0.8). Dashboard -> Developers -> Webhooks points here.
mod easyway;
mod webhook;
use axum::{body::Bytes, extract::DefaultBodyLimit, http::{HeaderMap, StatusCode}, routing::post, Router};
use std::time::{SystemTime, UNIX_EPOCH};
async fn easyway_webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
// Bytes, not Json<_>: the RAW body is what was signed.
let secret = std::env::var("EASYWAY_WEBHOOK_SECRET").expect("EASYWAY_WEBHOOK_SECRET");
let header = headers.get("x-webhook-signature").and_then(|v| v.to_str().ok()).unwrap_or("");
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
if !webhook::valid(header, &body, secret.as_bytes(), now) {
return StatusCode::BAD_REQUEST;
}
let Ok(event) = serde_json::from_slice::<serde_json::Value>(&body) else { return StatusCode::BAD_REQUEST };
// Store event["id"] and skip repeats: deliveries are retried until you answer 2xx.
if event["type"] == "invoice.paid" {
let inv = &event["data"]["invoice"];
println!("order {} paid: {} {}", inv["order_id"], inv["net_amount"], inv["pay_asset"]);
// mark_order_paid(...) here; send e-mails from a background task
}
StatusCode::OK
}
#[tokio::main]
async fn main() {
if let Some(order) = std::env::args().nth(1) {
// cargo run -- 2048: create an invoice for order 2048 ($149.00) and print where to send the customer.
let client = easyway::Client::from_env();
match client.create_invoice(order.parse().unwrap(), 14900).await {
Ok(inv) => println!("redirect (303) to {}", inv["payment_url"].as_str().unwrap_or_default()),
Err(e) => println!("{e:?}"),
}
return;
}
let app = Router::new()
.route("/webhooks/easyway", post(easyway_webhook))
.layer(DefaultBodyLimit::max(1_000_000));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}We sent signed deliveries to this server. The genuine one got 200 and printed the order. A changed body, a timestamp 400 seconds old, another secret, a missing or malformed header, a short or non-hex v1, and a delivery correctly signed over t=+1764… all got 400; a GET got 405.
| Rust pitfall | Fix |
|---|---|
Json<T> extractor | It parses the body before your code runs, and re-serialised JSON is not byte-identical to what was signed. Take Bytes, check the signature, then parse. |
str::parse::<i64>() on the timestamp | It accepts a leading +: "+1764" parses to 1764. Check that every byte is an ASCII digit first, as the code does. |
== on hex strings | A plain comparison stops at the first different byte. verify_slice from the hmac crate compares in constant time, and a wrong length is simply an error. |
| Body size | axum caps bodies at 2 MB by default; a webhook is a few kB, so DefaultBodyLimit::max lowers it. |
| Duplicates and speed | Deliveries are retried until you answer 2xx within 10 seconds. Store the event id, skip repeats, and send e-mails or licence keys from a spawned task. |
The webhook retries post explains duplicates and ordering, and the signature guide shows how to sign a test request with openssl.
Test it end to end
Set EASYWAY_API_KEY to a test key and EASYWAY_WEBHOOK_SECRET to the endpoint's secret, run cargo run behind a tunnel to port 8000, and add the tunnel URL in Dashboard → Developers → Webhooks. Create an invoice with cargo run -- 2048, open its payment_url and press Simulate payment: the real crediting code runs and a real invoice.paid delivery reaches your server. The sandbox guide covers underpaid and expired cases too.
Branch on the error code, never on message text. The fee is a flat 0.5% of each confirmed payment, see pricing. The same integration in other languages: Python, PHP, Node.js, Go, Java and Ruby; every endpoint is in the API docs.