1 unstable release
new 0.1.0 | Mar 16, 2025 |
---|
#52 in Magic Beans
40 downloads per month
29KB
390 lines
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)
- 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
:
[dependencies]
sagapay-sdk = "0.1.0"
tokio = { version = "1.0", features = ["full"] }
## Quick Start
```rust
use sagapay::{Client, Config, CreateDepositParams, NetworkType};
#[tokio::main]
async fn main() -> Result<(), sagapay::Error> {
// Initialize the SagaPay client
let client = Client::new(Config {
api_key: "your-api-key".to_string(),
api_secret: "your-api-secret".to_string(),
..Config::default()
});
// Create a deposit address
let deposit = client.create_deposit(CreateDepositParams {
network_type: NetworkType::BEP20,
contract_address: "0".to_string(), // Use '0' for native coins
amount: "1.5".to_string(),
ipn_url: "https://yourwebsite.com/webhook".to_string(),
udf: Some("order-123".to_string()),
address_type: Some("TEMPORARY".to_string()),
}).await?;
println!("Deposit address created: {}", deposit.address);
println!("Expires at: {}", deposit.expires_at);
Ok(())
}
API Reference
Create Deposit
let deposit = client.create_deposit(CreateDepositParams {
network_type: NetworkType::BEP20, // Required: Blockchain network type
contract_address: "0".to_string(), // Required: Contract address or '0' for native coins
amount: "1.5".to_string(), // Required: Expected deposit amount
ipn_url: "https://example.com/webhook", // Required: URL for notifications
udf: Some("order-123".to_string()), // Optional: User-defined field
address_type: Some("TEMPORARY".to_string()), // Optional: TEMPORARY or PERMANENT
}).await?;
Create Withdrawal
let withdrawal = client.create_withdrawal(CreateWithdrawalParams {
network_type: NetworkType::ERC20,
contract_address: "0xdAC17F958D2ee523a2206206994597C13D831ec7".to_string(), // USDT
address: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e".to_string(),
amount: "10.5".to_string(),
ipn_url: "https://example.com/webhook".to_string(),
udf: Some("withdrawal-456".to_string()),
}).await?;
Check Transaction Status
let status = client.check_transaction_status(
"0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
TransactionType::Deposit
).await?;
Fetch Wallet Balance
let balance = client.fetch_wallet_balance(
"0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
NetworkType::ERC20,
"0xdAC17F958D2ee523a2206206994597C13D831ec7" // USDT on Ethereum
).await?;
Handling Webhooks (IPN)
SagaPay sends webhook notifications to your specified ipnUrl
when transaction statuses change. Use the WebhookHandler to process these notifications:
use sagapay::{WebhookHandler, Error};
use std::collections::HashMap;
// In your webhook endpoint handler:
async fn handle_webhook(
headers: HashMap<String, String>,
body: String
) -> Result<(), Error> {
let api_secret = "your-api-secret";
let handler = WebhookHandler::new(api_secret);
// Get signature from headers
let signature = headers.get("x-sagapay-signature")
.ok_or(Error::InvalidSignature)?;
// Process and validate the webhook
let webhook_data = handler.process_webhook(&body, signature)?;
// Handle the validated webhook data based on status
match webhook_data.status {
TransactionStatus::Completed => {
// Payment successful
// Update your database or trigger actions
},
TransactionStatus::Failed => {
// Handle failed transaction
},
_ => { /* Handle other statuses */ }
}
Ok(())
}
Webhook Payload Format
When SagaPay sends a webhook to your endpoint, it will include the following payload:
{
"id": "transaction-uuid",
"type": "deposit|withdrawal",
"status": "PENDING|PROCESSING|COMPLETED|FAILED|CANCELLED",
"address": "0x123abc...",
"networkType": "ERC20|BEP20|TRC20|POLYGON|SOLANA",
"amount": "10.5",
"udf": "your-optional-user-defined-field",
"txHash": "0xabc123...",
"timestamp": "2025-03-16T14:30:00Z"
}
Error Handling
The SDK provides a comprehensive error handling system using the thiserror
crate:
match client.create_deposit(params).await {
Ok(deposit) => {
println!("Success! Address: {}", deposit.address);
},
Err(e) => match e {
Error::NetworkError(err) => {
eprintln!("Network error: {}", err);
},
Error::ApiError { status_code, message, .. } => {
eprintln!("API error {}: {}", status_code, message);
},
Error::InvalidSignature => {
eprintln!("Invalid webhook signature");
},
_ => {
eprintln!("Other error: {}", e);
}
}
}
License
This SDK is released under the MIT License.
Support
For questions or support, please contact support@sagapay.net or visit https://sagapay.net.
Dependencies
~8–21MB
~297K SLoC