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
//! Payment request and response types.

use serde::{Deserialize, Serialize};

use super::common::{Currency, Customer, Metadata, Money, PaymentAmount};

/// Payment lifecycle status.
///
/// `Other(String)` is a forward-compatibility hatch — when Snippe adds a new
/// status this variant captures it without breaking deserialisation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PaymentStatus {
    /// Created, waiting for the customer to authorise.
    Pending,
    /// Successful — funds received.
    Completed,
    /// Declined, timed out, or otherwise failed.
    Failed,
    /// Cancelled before completion.
    Voided,
    /// Not authorised within the 4-hour window.
    Expired,
    /// A status string this SDK version doesn't recognise.
    Other(String),
}

impl PaymentStatus {
    /// Wire-form string.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Pending => "pending",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Voided => "voided",
            Self::Expired => "expired",
            Self::Other(s) => s.as_str(),
        }
    }

    /// True for `completed`, `failed`, `voided`, or `expired` — i.e. the
    /// payment has reached its terminal state and won't transition again.
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Voided | Self::Expired
        )
    }
}

impl<'de> Deserialize<'de> for PaymentStatus {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(d)?;
        Ok(match s.as_str() {
            "pending" => Self::Pending,
            "completed" => Self::Completed,
            "failed" => Self::Failed,
            "voided" => Self::Voided,
            "expired" => Self::Expired,
            _ => Self::Other(s),
        })
    }
}

impl Serialize for PaymentStatus {
    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        s.serialize_str(self.as_str())
    }
}

/// Payment channel — `mobile`, `card`, or `dynamic-qr`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PaymentType {
    /// Mobile money (USSD push).
    Mobile,
    /// Hosted card checkout (Selcom).
    Card,
    /// Dynamic QR for scan-to-pay.
    DynamicQr,
    /// A type this SDK version doesn't recognise.
    Other(String),
}

impl PaymentType {
    /// Wire-form string.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Mobile => "mobile",
            Self::Card => "card",
            Self::DynamicQr => "dynamic-qr",
            Self::Other(s) => s.as_str(),
        }
    }
}

impl<'de> Deserialize<'de> for PaymentType {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(d)?;
        Ok(match s.as_str() {
            "mobile" => Self::Mobile,
            "card" => Self::Card,
            "dynamic-qr" => Self::DynamicQr,
            _ => Self::Other(s),
        })
    }
}

impl Serialize for PaymentType {
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        ser.serialize_str(self.as_str())
    }
}

/// Request body for `POST /v1/payments`. Internally tagged on `payment_type`.
///
/// Use the matching `MobilePayment::new`, `CardPayment::new`, or
/// `QrPayment::new` constructor for the variant you need.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "payment_type", rename_all = "kebab-case")]
pub enum CreatePaymentRequest {
    /// Mobile-money payment (USSD push).
    Mobile(MobilePayment),
    /// Card payment via the hosted Selcom checkout.
    Card(CardPayment),
    /// Dynamic QR for scan-to-pay.
    DynamicQr(QrPayment),
}

/// Hosted-checkout details shared by card and dynamic-qr payments.
///
/// Includes the redirect URLs — both must be HTTPS and ≤ 500 characters.
#[derive(Debug, Clone, Serialize)]
pub struct HostedPaymentDetails {
    /// Amount in TZS (smallest unit).
    pub amount: u64,
    /// Currency. Must be `TZS`.
    pub currency: Currency,
    /// Redirect URL after successful charge. HTTPS only.
    pub redirect_url: String,
    /// Redirect URL after cancel / decline. HTTPS only.
    pub cancel_url: String,
}

impl HostedPaymentDetails {
    /// Construct a TZS hosted-payment details block.
    pub fn tzs(
        amount: u64,
        redirect_url: impl Into<String>,
        cancel_url: impl Into<String>,
    ) -> Self {
        Self {
            amount,
            currency: Currency::Tzs,
            redirect_url: redirect_url.into(),
            cancel_url: cancel_url.into(),
        }
    }
}

/// Mobile-money payment payload (USSD push).
///
/// Required fields: amount, phone number, customer (firstname / lastname /
/// email). The customer's phone receives a USSD prompt; they enter their
/// mobile-money PIN to authorise.
#[derive(Debug, Clone, Serialize)]
pub struct MobilePayment {
    /// Amount and currency block.
    pub details: PaymentAmount,
    /// Customer's phone number, e.g. `"255781000000"` or `"+255781000000"`.
    pub phone_number: String,
    /// Customer block (firstname / lastname / email required).
    pub customer: Customer,
    /// Per-payment HTTPS webhook URL override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// Echoed-back metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

impl MobilePayment {
    /// Construct a mobile-money payment with the required fields.
    pub fn new(amount: u64, phone_number: impl Into<String>, customer: Customer) -> Self {
        Self {
            details: PaymentAmount::tzs(amount),
            phone_number: phone_number.into(),
            customer,
            webhook_url: None,
            metadata: None,
        }
    }

    /// Set the per-payment webhook URL (HTTPS, ≤ 500 chars).
    pub fn with_webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }

    /// Attach echoed-back metadata.
    pub fn with_metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Card payment payload — uses the hosted Selcom checkout.
///
/// Card payments require the full customer address block (`address`, `city`,
/// `state`, `postcode`, `country`) — set them on the [`Customer`] before
/// constructing.
#[derive(Debug, Clone, Serialize)]
pub struct CardPayment {
    /// Hosted-payment details (amount, redirect, cancel URLs).
    pub details: HostedPaymentDetails,
    /// Customer phone number.
    pub phone_number: String,
    /// Full customer block including address fields.
    pub customer: Customer,
    /// Per-payment HTTPS webhook URL override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// Echoed-back metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

impl CardPayment {
    /// Construct a card payment with the required fields.
    pub fn new(
        details: HostedPaymentDetails,
        phone_number: impl Into<String>,
        customer: Customer,
    ) -> Self {
        Self {
            details,
            phone_number: phone_number.into(),
            customer,
            webhook_url: None,
            metadata: None,
        }
    }

    /// Set the per-payment webhook URL.
    pub fn with_webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }

    /// Attach echoed-back metadata.
    pub fn with_metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Dynamic-QR payment payload.
///
/// QR payments only strictly require the amount block; phone number and
/// customer are optional but recommended for reconciliation.
#[derive(Debug, Clone, Serialize)]
pub struct QrPayment {
    /// Hosted-payment details (amount, redirect, cancel URLs).
    pub details: HostedPaymentDetails,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional customer phone number.
    pub phone_number: Option<String>,
    /// Optional customer block.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer: Option<Customer>,
    /// Optional per-payment HTTPS webhook URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// Echoed-back metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

impl QrPayment {
    /// Construct a QR payment with only the amount block.
    pub fn new(details: HostedPaymentDetails) -> Self {
        Self {
            details,
            phone_number: None,
            customer: None,
            webhook_url: None,
            metadata: None,
        }
    }

    /// Add a customer block.
    pub fn with_customer(mut self, customer: Customer) -> Self {
        self.customer = Some(customer);
        self
    }

    /// Add a customer phone number.
    pub fn with_phone_number(mut self, phone: impl Into<String>) -> Self {
        self.phone_number = Some(phone.into());
        self
    }

    /// Set the per-payment HTTPS webhook URL.
    pub fn with_webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }

    /// Attach echoed-back metadata.
    pub fn with_metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Payment record returned by `POST /v1/payments`, `GET /v1/payments/{ref}`,
/// and `GET /v1/payments/search`.
///
/// Fields are populated based on the channel:
/// - All channels: `reference`, `status`, `payment_type`, `amount`, `expires_at`.
/// - Card: `payment_url`, `payment_token`.
/// - QR: `payment_url`, `payment_token`, `payment_qr_code`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Payment {
    /// Snippe-side reference for the payment. Persist this — it's how you
    /// look the payment up later.
    pub reference: String,
    /// Current status.
    pub status: PaymentStatus,
    /// Channel.
    pub payment_type: PaymentType,
    /// Amount block (note: `{value, currency}` shape on responses).
    pub amount: Money,
    /// ISO-8601 timestamp at which a pending payment expires.
    pub expires_at: String,
    /// Hosted checkout URL — present for `card` and `dynamic-qr`.
    #[serde(default)]
    pub payment_url: Option<String>,
    /// Short numeric token — present for `card` and `dynamic-qr`.
    #[serde(default)]
    pub payment_token: Option<String>,
    /// EMV QR payload string — present for `dynamic-qr`. Render as a QR image
    /// using any QR library (`qrcode` etc.) on the consumer side.
    #[serde(default)]
    pub payment_qr_code: Option<String>,
    /// API version that produced the record.
    #[serde(default)]
    pub api_version: Option<String>,
    /// Echoed-back metadata.
    #[serde(default)]
    pub metadata: Option<Metadata>,
}

/// Account balance, returned by `GET /v1/payments/balance`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Balance {
    /// Funds available for immediate use (e.g. payouts).
    pub available: Money,
    /// Total funds, including any still settling.
    pub balance: Money,
}

/// Query parameters for `GET /v1/payments`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListPaymentsParams {
    /// Items per page.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    /// Filter by status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<PaymentStatus>,
    /// Filter by channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<PaymentType>,
}

impl ListPaymentsParams {
    /// Construct empty params.
    pub fn new() -> Self {
        Self::default()
    }
    /// Items per page.
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }
    /// 1-based page number.
    pub fn page(mut self, page: u32) -> Self {
        self.page = Some(page);
        self
    }
    /// Filter by status.
    pub fn status(mut self, status: PaymentStatus) -> Self {
        self.status = Some(status);
        self
    }
    /// Filter by channel.
    pub fn payment_type(mut self, t: PaymentType) -> Self {
        self.payment_type = Some(t);
        self
    }
}

/// Query parameters for `GET /v1/payments/search`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SearchPaymentsParams {
    /// Search by Snippe reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    /// Search by upstream processor reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_reference: Option<String>,
    /// Search by customer phone number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_number: Option<String>,
    /// Search by customer email.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Page size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
}

impl SearchPaymentsParams {
    /// Construct empty params.
    pub fn new() -> Self {
        Self::default()
    }
    /// Filter by Snippe reference.
    pub fn reference(mut self, r: impl Into<String>) -> Self {
        self.reference = Some(r.into());
        self
    }
    /// Filter by upstream processor reference.
    pub fn external_reference(mut self, r: impl Into<String>) -> Self {
        self.external_reference = Some(r.into());
        self
    }
    /// Filter by phone number.
    pub fn phone_number(mut self, p: impl Into<String>) -> Self {
        self.phone_number = Some(p.into());
        self
    }
    /// Filter by email.
    pub fn email(mut self, e: impl Into<String>) -> Self {
        self.email = Some(e.into());
        self
    }
}

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

    #[test]
    fn mobile_payment_serialises_with_payment_type_tag() {
        let req = CreatePaymentRequest::Mobile(MobilePayment::new(
            500,
            "255781000000",
            Customer::new("Jane", "Doe", "jane@example.com"),
        ));
        let json = serde_json::to_value(&req).unwrap();
        assert_eq!(json["payment_type"], "mobile");
        assert_eq!(json["details"]["amount"], 500);
        assert_eq!(json["details"]["currency"], "TZS");
        assert_eq!(json["phone_number"], "255781000000");
        assert!(json.get("webhook_url").is_none());
    }

    #[test]
    fn card_payment_serialises_with_redirect_urls() {
        let details = HostedPaymentDetails::tzs(
            1000,
            "https://example.com/done",
            "https://example.com/cancel",
        );
        let customer = Customer::new("Jane", "Doe", "j@d.com")
            .with_address("addr")
            .with_city("DSM")
            .with_state("DSM")
            .with_postcode("14101")
            .with_country("TZ");
        let req =
            CreatePaymentRequest::Card(CardPayment::new(details, "255781000000", customer));
        let json = serde_json::to_value(&req).unwrap();
        assert_eq!(json["payment_type"], "card");
        assert_eq!(json["details"]["redirect_url"], "https://example.com/done");
        assert_eq!(json["customer"]["country"], "TZ");
    }

    #[test]
    fn qr_payment_uses_dynamic_qr_tag() {
        let details = HostedPaymentDetails::tzs(500, "https://x/d", "https://x/c");
        let req = CreatePaymentRequest::DynamicQr(QrPayment::new(details));
        let json = serde_json::to_value(&req).unwrap();
        assert_eq!(json["payment_type"], "dynamic-qr");
    }

    #[test]
    fn payment_response_deserialises() {
        let body = serde_json::json!({
            "reference": "9015c155",
            "status": "pending",
            "payment_type": "mobile",
            "amount": {"value": 500, "currency": "TZS"},
            "expires_at": "2026-01-25T05:04:54Z",
            "api_version": "2026-01-25"
        });
        let payment: Payment = serde_json::from_value(body).unwrap();
        assert_eq!(payment.reference, "9015c155");
        assert_eq!(payment.status, PaymentStatus::Pending);
        assert_eq!(payment.amount.value, 500);
        assert!(!payment.status.is_terminal());
    }

    #[test]
    fn unknown_status_falls_back_to_other() {
        let body = serde_json::json!({
            "reference": "x",
            "status": "future-status",
            "payment_type": "mobile",
            "amount": {"value": 500, "currency": "TZS"},
            "expires_at": "2026-01-25T05:04:54Z"
        });
        let p: Payment = serde_json::from_value(body).unwrap();
        match p.status {
            PaymentStatus::Other(s) => assert_eq!(s, "future-status"),
            other => panic!("expected Other, got {:?}", other),
        }
    }
}