use hmac::{Hmac, KeyInit, Mac};
use sagapay::{DEFAULT_MAX_AGE, Error, IpnType, SIGNATURE_HEADER, WebhookHandler, WebhookPayload};
use sha2::Sha256;
use std::collections::{HashMap, HashSet};
const SAMPLE_BODY: &str = r#"{
"id": "8b7c1f2e-0f1a-4a4c-9c6b-1f0c7d5a2b3e",
"type": "DEPOSIT",
"status": "COMPLETED",
"address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
"networkType": "BEP20",
"asset": "USDT",
"contractAddress": "0x55d398326f99059fF775485246999027B3197955",
"amount": "1.5",
"udf": "order-123",
"txHash": "0xabc123",
"timestamp": "2025-03-16T14:30:00.000Z"
}"#;
const DEMO_SECRET: &str = "demo-signing-secret";
fn main() {
println!("This is an example webhook handler implementation.");
println!("In a real app, integrate this with your web framework.");
println!();
let signing_secret =
std::env::var("SAGAPAY_SIGNING_SECRET").unwrap_or_else(|_| DEMO_SECRET.to_string());
let webhook_handler = WebhookHandler::new(signing_secret.clone());
let mut headers = HashMap::new();
headers.insert(
SIGNATURE_HEADER.to_string(),
sign(&signing_secret, SAMPLE_BODY),
);
let mut processed = HashSet::new();
for _ in 0..2 {
match handle_webhook(&webhook_handler, &headers, SAMPLE_BODY, &mut processed) {
Ok(()) => {}
Err(err) => eprintln!("Rejected webhook: {}", err),
}
}
let tampered = SAMPLE_BODY.replace("\"1.5\"", "\"1500\"");
if let Err(err) = handle_webhook(&webhook_handler, &headers, &tampered, &mut processed) {
println!("Tampered body rejected: {}", err);
}
let strict = WebhookHandler::new(signing_secret).with_max_age(DEFAULT_MAX_AGE);
if let Err(err) = handle_webhook(&strict, &headers, SAMPLE_BODY, &mut HashSet::new()) {
println!("Old notification rejected: {}", err);
}
}
fn handle_webhook(
webhook_handler: &WebhookHandler,
headers: &HashMap<String, String>,
body: &str,
processed: &mut HashSet<String>,
) -> Result<(), Error> {
let webhook = webhook_handler.process_webhook_from_request(headers, body)?;
if !processed.insert(webhook.id.clone()) {
println!("Duplicate notification {} - already handled.", webhook.id);
return Ok(());
}
fulfil(&webhook);
Ok(())
}
fn fulfil(webhook: &WebhookPayload) {
println!("SagaPay Webhook received:");
println!(" Transaction ID: {}", webhook.id);
println!(" Type: {:?}", webhook.transaction_type);
println!(" Asset: {:?}", webhook.asset);
println!(" Amount: {}", webhook.amount);
match webhook.transaction_type {
IpnType::Deposit => {
println!(
"Deposit completed: {} received at {}",
webhook.amount, webhook.address
);
}
IpnType::Withdrawal => {
println!(
"Withdrawal completed: {} sent to {}",
webhook.amount, webhook.address
);
}
}
}
fn sign(secret: &str, body: &str) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("any key size");
mac.update(body.as_bytes());
format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
}