snippe 0.1.0

Async Rust client for the Snippe payments API (Tanzania) — collections, hosted checkout sessions, disbursements, and verified webhooks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! HMAC-SHA256 webhook signature verification and typed event dispatch.
//!
//! Snippe POSTs JSON events to your `webhook_url` whenever a payment or payout
//! changes status. Each request carries:
//!
//! - `X-Webhook-Timestamp` — Unix-second timestamp of the event.
//! - `X-Webhook-Signature` — hex-encoded `HMAC-SHA256(signing_key, "{ts}.{raw_body}")`.
//! - `X-Webhook-Event` — event type **as a hint only** (use the verified
//!   payload's `type` field as the source of truth).
//!
//! ## Verifying correctly
//!
//! Two rules that are easy to get wrong, both enforced by [`Verifier`]:
//!
//! 1. **Sign over the raw request bytes.** Don't `serde_json::from_slice`
//!    then `serde_json::to_vec` — re-serialisation changes whitespace, key
//!    order, and number formatting, all of which break the HMAC. Read the
//!    body once as bytes (e.g. `axum::body::Bytes`, `actix_web::web::Bytes`,
//!    `hyper::body::to_bytes`) and pass that slice to [`Verifier::verify`].
//! 2. **Reject timestamps older than 5 minutes** to prevent replay attacks.
//!    [`Verifier`] does this by default with a 5-minute tolerance — adjust
//!    via [`Verifier::with_max_age`].
//!
//! ## Example
//!
//! ```
//! use snippe::webhook::{EventData, Verifier};
//!
//! fn handle(body: &[u8], timestamp: &str, signature: &str, secret: &str) {
//!     let verifier = Verifier::new(secret.as_bytes().to_vec());
//!     let event = match verifier.verify_typed(body, timestamp, signature) {
//!         Ok(ev) => ev,
//!         Err(e) => {
//!             eprintln!("rejected webhook: {e}");
//!             return;
//!         }
//!     };
//!
//!     // Deduplicate by event.id — Snippe may deliver the same event more
//!     // than once. Store seen IDs for at least a few hours.
//!     match event.data {
//!         EventData::PaymentCompleted(p) => println!("paid: {}", p.reference),
//!         EventData::PaymentFailed(p)    => println!("failed: {:?}", p.failure_reason),
//!         _ => {}
//!     }
//! }
//! ```
//!
//! For framework integration, read the request headers and raw body once
//! (e.g. `axum::body::Bytes`, `actix_web::web::Bytes`,
//! `hyper::body::to_bytes`) and pass them straight to [`Verifier::verify`] /
//! [`Verifier::verify_typed`].

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use hmac::{Hmac, Mac};
use serde::Deserialize;
use sha2::Sha256;

use crate::models::common::{Channel, Metadata, Money};
use crate::models::payout::Recipient;

type HmacSha256 = Hmac<Sha256>;

/// Default replay-protection window — 5 minutes.
pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(300);

/// HTTP header carrying the Unix-second timestamp.
pub const TIMESTAMP_HEADER: &str = "X-Webhook-Timestamp";

/// HTTP header carrying the hex-encoded HMAC-SHA256 signature.
pub const SIGNATURE_HEADER: &str = "X-Webhook-Signature";

/// HTTP header carrying the event-type hint. Use the verified body, not this.
pub const EVENT_HEADER: &str = "X-Webhook-Event";

/// Errors returned by webhook verification.
#[derive(Debug, thiserror::Error)]
pub enum WebhookError {
    /// A required header was missing.
    #[error("missing header {0}")]
    MissingHeader(&'static str),
    /// The timestamp header could not be parsed as a Unix-second integer.
    #[error("invalid X-Webhook-Timestamp header: {0}")]
    InvalidTimestamp(String),
    /// The timestamp is older than the configured tolerance.
    #[error("webhook timestamp is too old (age = {0:?})")]
    TimestampTooOld(Duration),
    /// The signature was not valid hex.
    #[error("invalid signature encoding: {0}")]
    InvalidSignatureEncoding(#[source] hex::FromHexError),
    /// The signature did not match the computed HMAC.
    #[error("webhook signature mismatch")]
    SignatureMismatch,
    /// The body was not valid JSON, or didn't match the expected event shape.
    #[error("invalid JSON body: {0}")]
    InvalidJson(#[source] serde_json::Error),
}

/// Verifies webhook signatures using a shared signing key.
///
/// Construct one verifier per signing secret at startup and reuse it for
/// every incoming webhook — verification is allocation-light and the verifier
/// is `Clone + Send + Sync`.
#[derive(Clone)]
pub struct Verifier {
    signing_key: Vec<u8>,
    max_age: Duration,
}

impl std::fmt::Debug for Verifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Verifier")
            .field("signing_key", &"<redacted>")
            .field("max_age", &self.max_age)
            .finish()
    }
}

impl Verifier {
    /// Construct a verifier with the default 5-minute timestamp tolerance.
    pub fn new(signing_key: impl Into<Vec<u8>>) -> Self {
        Self {
            signing_key: signing_key.into(),
            max_age: DEFAULT_MAX_AGE,
        }
    }

    /// Override the timestamp tolerance. Stricter values reduce the replay
    /// window; looser values accommodate clock skew between Snippe and your
    /// servers.
    pub fn with_max_age(mut self, age: Duration) -> Self {
        self.max_age = age;
        self
    }

    /// Configured tolerance window.
    pub fn max_age(&self) -> Duration {
        self.max_age
    }

    /// Verify a webhook against the raw request body and the
    /// timestamp / signature header values.
    ///
    /// Returns the event in raw form on success — the body is parsed once
    /// JSON validation succeeds. Use [`Self::verify_typed`] for a typed
    /// dispatch enum, or call [`RawEvent::try_into_event`] yourself.
    pub fn verify(
        &self,
        body: &[u8],
        timestamp: &str,
        signature: &str,
    ) -> Result<RawEvent, WebhookError> {
        if timestamp.is_empty() {
            return Err(WebhookError::MissingHeader(TIMESTAMP_HEADER));
        }
        if signature.is_empty() {
            return Err(WebhookError::MissingHeader(SIGNATURE_HEADER));
        }

        let ts: u64 = timestamp
            .parse()
            .map_err(|_| WebhookError::InvalidTimestamp(timestamp.to_string()))?;

        // Replay protection — only enforced when we can read the wall clock
        // (which should always succeed; we're being defensive).
        if let Some(now) = unix_now() {
            let age_secs = now.saturating_sub(ts);
            if age_secs > self.max_age.as_secs() {
                return Err(WebhookError::TimestampTooOld(Duration::from_secs(age_secs)));
            }
        }

        let provided = hex::decode(signature).map_err(WebhookError::InvalidSignatureEncoding)?;

        let mut mac = <HmacSha256 as Mac>::new_from_slice(&self.signing_key)
            .expect("HmacSha256 accepts a key of any length");
        mac.update(timestamp.as_bytes());
        mac.update(b".");
        mac.update(body);
        // Mac::verify_slice runs in constant time.
        mac.verify_slice(&provided)
            .map_err(|_| WebhookError::SignatureMismatch)?;

        serde_json::from_slice(body).map_err(WebhookError::InvalidJson)
    }

    /// Verify and dispatch to a typed [`Event`].
    ///
    /// Unknown event types are returned as [`EventData::Unknown`] — they
    /// don't fail verification.
    pub fn verify_typed(
        &self,
        body: &[u8],
        timestamp: &str,
        signature: &str,
    ) -> Result<Event, WebhookError> {
        let raw = self.verify(body, timestamp, signature)?;
        raw.try_into_event().map_err(WebhookError::InvalidJson)
    }
}

fn unix_now() -> Option<u64> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .ok()
        .map(|d| d.as_secs())
}

/// A verified webhook event in raw form.
///
/// The envelope fields are extracted; `data` remains as a [`serde_json::Value`]
/// so unknown event types deserialise without losing information.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RawEvent {
    /// Unique event ID — use this as your deduplication key (Snippe may
    /// deliver the same event more than once).
    pub id: String,
    /// Event type, e.g. `payment.completed`. Always trust this over the
    /// `X-Webhook-Event` header.
    #[serde(rename = "type")]
    pub event_type: String,
    /// API version that produced the event.
    pub api_version: String,
    /// ISO-8601 timestamp of when the event was created.
    pub created_at: String,
    /// Event payload. Shape depends on `event_type`.
    pub data: serde_json::Value,
}

impl RawEvent {
    /// Parse `data` into the typed [`Event`] enum.
    pub fn try_into_event(self) -> Result<Event, serde_json::Error> {
        let RawEvent {
            id,
            event_type,
            api_version,
            created_at,
            data,
        } = self;

        let payload = match event_type.as_str() {
            "payment.completed" => EventData::PaymentCompleted(serde_json::from_value(data)?),
            "payment.failed" => EventData::PaymentFailed(serde_json::from_value(data)?),
            "payment.voided" => EventData::PaymentVoided(serde_json::from_value(data)?),
            "payment.expired" => EventData::PaymentExpired(serde_json::from_value(data)?),
            "payout.completed" => EventData::PayoutCompleted(serde_json::from_value(data)?),
            "payout.failed" => EventData::PayoutFailed(serde_json::from_value(data)?),
            "payout.reversed" => EventData::PayoutReversed(serde_json::from_value(data)?),
            other => EventData::Unknown {
                event_type: other.to_string(),
                data,
            },
        };

        Ok(Event {
            id,
            api_version,
            created_at,
            data: payload,
        })
    }
}

/// A verified webhook event with its payload parsed into a typed enum.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Event {
    /// Unique event ID — use as a deduplication key.
    pub id: String,
    /// API version that produced the event.
    pub api_version: String,
    /// ISO-8601 timestamp.
    pub created_at: String,
    /// Typed payload.
    pub data: EventData,
}

/// Typed event payload, dispatched on `event.type`.
///
/// New variants may be added in minor releases as Snippe ships new events.
/// The [`EventData::Unknown`] variant catches payloads this SDK version
/// doesn't recognise — verification still succeeds for them.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum EventData {
    /// `payment.completed` — funds received.
    PaymentCompleted(PaymentEventData),
    /// `payment.failed` — declined, timed out, or otherwise failed.
    PaymentFailed(PaymentEventData),
    /// `payment.voided` — cancelled before completion.
    PaymentVoided(PaymentEventData),
    /// `payment.expired` — 4-hour timeout reached without authorisation.
    PaymentExpired(PaymentEventData),
    /// `payout.completed` — recipient received funds.
    PayoutCompleted(PayoutEventData),
    /// `payout.failed` — see `failure_reason`.
    PayoutFailed(PayoutEventData),
    /// `payout.reversed` — reversed after completion.
    PayoutReversed(PayoutEventData),
    /// An event type not enumerated by this SDK version.
    Unknown {
        /// Raw event-type string.
        event_type: String,
        /// Raw `data` payload.
        data: serde_json::Value,
    },
}

/// Payment event payload — `payment.*` events.
///
/// Note: `amount` is a [`Money`] object (`{value, currency}`), not a plain
/// integer like in payment request bodies. This is the most common parsing
/// gotcha when integrating Snippe webhooks.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentEventData {
    /// Snippe-side payment reference.
    pub reference: String,
    /// Upstream processor reference (Selcom, etc.) — useful for support.
    #[serde(default)]
    pub external_reference: Option<String>,
    /// Status string at the time of the event.
    pub status: String,
    /// Amount block.
    pub amount: Money,
    /// Settlement breakdown — gross / fees / net (completed events only).
    #[serde(default)]
    pub settlement: Option<Settlement>,
    /// Payment channel.
    #[serde(default)]
    pub channel: Option<Channel>,
    /// Customer information.
    #[serde(default)]
    pub customer: Option<EventCustomer>,
    /// Echoed-back metadata.
    #[serde(default)]
    pub metadata: Option<Metadata>,
    /// ISO-8601 completion timestamp.
    #[serde(default)]
    pub completed_at: Option<String>,
    /// Failure reason — populated on `payment.failed`.
    #[serde(default)]
    pub failure_reason: Option<String>,
}

/// Payout event payload — `payout.*` events.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PayoutEventData {
    /// Snippe-side payout reference.
    pub reference: String,
    /// Upstream processor reference.
    #[serde(default)]
    pub external_reference: Option<String>,
    /// Status string at the time of the event.
    pub status: String,
    /// Amount sent to the recipient.
    pub amount: Money,
    /// Fee charged by Snippe.
    #[serde(default)]
    pub fees: Option<Money>,
    /// Total deducted from the merchant balance.
    #[serde(default)]
    pub total: Option<Money>,
    /// Channel descriptor.
    #[serde(default)]
    pub channel: Option<Channel>,
    /// Recipient block.
    #[serde(default)]
    pub recipient: Option<Recipient>,
    /// Echoed-back metadata.
    #[serde(default)]
    pub metadata: Option<Metadata>,
    /// ISO-8601 completion timestamp.
    #[serde(default)]
    pub completed_at: Option<String>,
    /// Failure reason — populated on `payout.failed`.
    #[serde(default)]
    pub failure_reason: Option<String>,
}

/// Settlement breakdown returned on completed payment events.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Settlement {
    /// Gross amount before fees.
    pub gross: Money,
    /// Fees charged by Snippe.
    pub fees: Money,
    /// Net amount credited to the merchant balance.
    pub net: Money,
}

/// Customer block carried on payment events.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct EventCustomer {
    /// Customer name.
    #[serde(default)]
    pub name: Option<String>,
    /// Customer phone number.
    #[serde(default)]
    pub phone: Option<String>,
    /// Customer email.
    #[serde(default)]
    pub email: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use hmac::Mac;

    fn sign(key: &[u8], timestamp: &str, body: &[u8]) -> String {
        let mut mac = <HmacSha256 as Mac>::new_from_slice(key).unwrap();
        mac.update(timestamp.as_bytes());
        mac.update(b".");
        mac.update(body);
        hex::encode(mac.finalize().into_bytes())
    }

    fn current_ts() -> String {
        unix_now().unwrap().to_string()
    }

    fn payment_completed_body(ts: &str) -> Vec<u8> {
        let _ = ts;
        let body = serde_json::json!({
            "id": "evt_a1b2c3d4",
            "type": "payment.completed",
            "api_version": "2026-01-25",
            "created_at": "2026-01-24T10:30:00Z",
            "data": {
                "reference": "pi_a1b2c3",
                "external_reference": "SEL123",
                "status": "completed",
                "amount": {"value": 50000, "currency": "TZS"},
                "settlement": {
                    "gross": {"value": 50000, "currency": "TZS"},
                    "fees":  {"value": 1000,  "currency": "TZS"},
                    "net":   {"value": 49000, "currency": "TZS"}
                },
                "channel": {"type": "mobile_money", "provider": "mpesa"},
                "customer": {"phone": "+255712345678", "name": "John", "email": "j@x.com"},
                "metadata": {"order_id": "ORD-1"},
                "completed_at": "2026-01-24T10:30:00Z"
            }
        });
        serde_json::to_vec(&body).unwrap()
    }

    #[test]
    fn verifies_valid_signature() {
        let key = b"super_secret_signing_key";
        let ts = current_ts();
        let body = payment_completed_body(&ts);
        let sig = sign(key, &ts, &body);

        let v = Verifier::new(key.to_vec());
        let event = v.verify_typed(&body, &ts, &sig).expect("verifies");
        assert_eq!(event.id, "evt_a1b2c3d4");

        match event.data {
            EventData::PaymentCompleted(p) => {
                assert_eq!(p.reference, "pi_a1b2c3");
                assert_eq!(p.amount.value, 50000);
                assert_eq!(p.settlement.unwrap().net.value, 49000);
            }
            other => panic!("wrong event variant: {other:?}"),
        }
    }

    #[test]
    fn rejects_bad_signature() {
        let key = b"super_secret";
        let ts = current_ts();
        let body = payment_completed_body(&ts);

        // Sign with a different key
        let bad_sig = sign(b"other_key", &ts, &body);
        let v = Verifier::new(key.to_vec());
        let err = v.verify(&body, &ts, &bad_sig).unwrap_err();
        assert!(matches!(err, WebhookError::SignatureMismatch));
    }

    #[test]
    fn rejects_old_timestamp() {
        let key = b"k";
        let body = b"{}";
        let old = "1000000000"; // year 2001
        let sig = sign(key, old, body);
        let v = Verifier::new(key.to_vec());
        let err = v.verify(body, old, &sig).unwrap_err();
        assert!(matches!(err, WebhookError::TimestampTooOld(_)));
    }

    #[test]
    fn rejects_tampered_body() {
        let key = b"k";
        let ts = current_ts();
        let body = payment_completed_body(&ts);
        let sig = sign(key, &ts, &body);

        // Mutate one byte after signing
        let mut tampered = body.clone();
        let last = tampered.len() - 5;
        tampered[last] ^= 0x01;

        let v = Verifier::new(key.to_vec());
        assert!(matches!(
            v.verify(&tampered, &ts, &sig).unwrap_err(),
            WebhookError::SignatureMismatch
        ));
    }

    #[test]
    fn missing_signature_header() {
        let v = Verifier::new(b"k".to_vec());
        let err = v.verify(b"{}", "0", "").unwrap_err();
        match err {
            WebhookError::MissingHeader(name) => assert_eq!(name, SIGNATURE_HEADER),
            other => panic!("expected MissingHeader, got {other:?}"),
        }
    }

    #[test]
    fn missing_timestamp_header() {
        let v = Verifier::new(b"k".to_vec());
        let err = v.verify(b"{}", "", "deadbeef").unwrap_err();
        match err {
            WebhookError::MissingHeader(name) => assert_eq!(name, TIMESTAMP_HEADER),
            other => panic!("expected MissingHeader, got {other:?}"),
        }
    }

    #[test]
    fn unknown_event_type_returns_unknown_variant() {
        let key = b"k";
        let ts = current_ts();
        let body = serde_json::to_vec(&serde_json::json!({
            "id": "evt_x",
            "type": "payment.invented",
            "api_version": "2026-01-25",
            "created_at": "2026-01-24T10:30:00Z",
            "data": {"foo": "bar"}
        }))
        .unwrap();
        let sig = sign(key, &ts, &body);

        let v = Verifier::new(key.to_vec());
        let event = v.verify_typed(&body, &ts, &sig).unwrap();
        match event.data {
            EventData::Unknown { event_type, data } => {
                assert_eq!(event_type, "payment.invented");
                assert_eq!(data["foo"], "bar");
            }
            other => panic!("expected Unknown, got {other:?}"),
        }
    }

    #[test]
    fn payout_completed_parses() {
        let key = b"k";
        let ts = current_ts();
        let body = serde_json::to_vec(&serde_json::json!({
            "id": "evt_p",
            "type": "payout.completed",
            "api_version": "2026-01-25",
            "created_at": "2026-01-24T10:30:00Z",
            "data": {
                "reference": "po_1",
                "status": "completed",
                "amount": {"value": 5000, "currency": "TZS"},
                "fees":   {"value": 1500, "currency": "TZS"},
                "total":  {"value": 6500, "currency": "TZS"},
                "channel": {"type": "mobile_money", "provider": "airtel"},
                "recipient": {"name": "Jane", "phone": "255712345678"}
            }
        })).unwrap();
        let sig = sign(key, &ts, &body);
        let v = Verifier::new(key.to_vec());
        let event = v.verify_typed(&body, &ts, &sig).unwrap();
        match event.data {
            EventData::PayoutCompleted(p) => {
                assert_eq!(p.reference, "po_1");
                assert_eq!(p.total.unwrap().value, 6500);
            }
            other => panic!("expected PayoutCompleted, got {other:?}"),
        }
    }
}