SagaPay Rust SDK
Rust SDK for SagaPay - the world's first free, non-custodial blockchain payment gateway service provider. This library enables Rust developers to seamlessly integrate cryptocurrency payments without holding customer funds. With enterprise-grade security and zero transaction fees, SagaPay empowers merchants to accept crypto payments across multiple blockchains while maintaining full control of their digital assets.
Features
- Deposit address generation
- Withdrawal processing
- Transaction status checking
- Wallet balance fetching
- Webhook notifications (IPN) with signature checking and server-side verification
- Multi-chain support (ERC20, BEP20, TRC20, POLYGON, SOLANA)
- Custom UDF field support
- Non-custodial architecture
- Async support with tokio
Installation
Add this to your Cargo.toml:
[]
= "0.3.0"
= { = "1", = ["full"] }
The crate is published and imported as sagapay.
Requires Rust 1.85 or newer (edition 2024).
Quick Start
use ;
async
API Reference
Create Deposit
let deposit = client.create_deposit.await?;
Create Withdrawal
Withdrawals need an API key created with Withdrawals turned on, which requires two-factor authentication on your account.
let withdrawal = client.create_withdrawal_idempotent.await?;
create_withdrawal_idempotent sends the key (1-128 letters, digits, - or _) as an Idempotency-Key header, so that a retry after a timeout or network error cannot send the money twice. For 24 hours, a repeat with the same key returns the first withdrawal instead of creating another; while the first request is still running, a repeat fails with a 409 Error::ApiError. Use one key per payout, such as your own payout id. create_withdrawal takes the same parameters without a key.
Check Transaction Status
// By address
let status = client.check_transaction_status.await?;
// By transaction ID
let status = client.check_transaction_status.await?;
TransactionType is the lowercase form used by this query (deposit / withdrawal).
Deposit items carry confirmations, withdrawal items carry fee and processed_at.
Fetch Wallet Balance
// Token balance
let balance = client.fetch_wallet_balance.await?;
// Native coin balance - pass None to omit the contract address
let native = client.fetch_wallet_balance.await?;
The response's contract_address is "0" for native coins. Here token carries
only symbol, name and decimals, so token.network_type and
token.contract_address are None - check_transaction_status fills them in.
Verify an IPN
use ;
let result = client.verify_ipn.await?;
if result.verified
Check the webhook signature first (see below); this network call is an extra check on top of it.
The API key and secret are read from the client Config and sent in the request
body - /verify-ipn is the one endpoint that takes no auth headers.
Handling Webhooks (IPN)
SagaPay sends webhook notifications to your specified ipnUrl when a transaction completes. Each one carries a signature over the exact raw request body:
X-Sagapay-Merchant-Signature: sha256=<hex HMAC-SHA256 of the raw body>
It is keyed with your signing secret. Copy it from the dashboard: Webhooks → Signing secret. It is not your API secret, and nobody else's secret can produce a valid signature for your notifications. WebhookHandler checks the signature on every notification, and a handler created with an empty secret rejects them all.
use ;
use HashMap;
// In your webhook endpoint handler. Answer 401 on Err; answer 2xx within 20
// seconds otherwise. If your own processing fails, answer 5xx so SagaPay retries.
If you have the header yourself, handler.process_webhook(body, signature) takes it as an Option<&str>. sagapay::SIGNATURE_HEADER holds the header name. Verify against the raw bytes you received: re-serializing the JSON changes the digest. The handler accepts both the sha256=-prefixed form and a bare hex digest, and compares in constant time.
The old X-Sagapay-Signature header was keyed with a secret shared by every merchant. It is retired: SagaPay no longer sends it, and this SDK no longer reads it.
Replay protection
A captured webhook still has a valid signature, so the signature alone does not stop someone resending it. Protect against that:
- Process each
idonce. Record the ids you have handled (a unique column works) and answer duplicates with a 200 without acting on them again. This is the main defence and also covers normal retries. - Optionally check the age with
with_max_age, orsagapay::is_ipn_fresh(&webhook, max_age, Utc::now()). Keep the limit above the retry schedule (about 7.5 hours): retries reuse the originaltimestamp. A notification you resend from the dashboard also keeps it, so a resend older than your limit will be refused. - Check what you are crediting. Match
asset,contract_address,amountandaddressagainst the order before you fulfil it.
Webhook Payload Format
When SagaPay sends a webhook to your endpoint, it will include the following payload:
typeis uppercase (DEPOSITorWITHDRAWAL) and maps toIpnType. This is distinct from the lowercaseTransactionTypeused bycheck_transaction_status.statusisCOMPLETED- the only status currently notified.networkTypeis one ofERC20,BEP20,TRC20,POLYGON,SOLANA.assetandcontractAddress(contract_addressin Rust) say what was received;contractAddressisnullfor the chain's native coin.networkTypealone does not tell 100 TRX from 100 USDT.udfandtxHashmay benull.timestampis set when the transaction completes and does not change on retries.- SagaPay makes up to 6 delivery attempts, retrying after 1 min, 5 min, 15 min, 1 h and 6 h.
Error Handling
The SDK provides a comprehensive error handling system using the thiserror crate:
match client.create_deposit.await
ApiError::message is the human readable text from the response body, which the
API returns as { "error": "..." }.
License
This SDK is released under the MIT License.
Support
For questions or support, please contact support@sagapay.io or visit https://sagapay.io.