bitmomo 0.1.0

BitMomo merchant SDK: accept crypto payments and verify webhooks in Rust
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
use std::time::Duration;

use reqwest::header::{ACCEPT, CONTENT_TYPE, RETRY_AFTER};
use reqwest::{redirect, Method, Url};
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::decimal::is_plain_decimal;
use crate::models::{parse_rates, PaymentLinks};
use crate::{
    Balances, CreatePaymentLinkParams, CreatePaymentParams, CreatedPayment, Error, ExchangeRate,
    ListPaymentsParams, Payment, PaymentLink, PaymentList, PaymentStatus, PayoutParams,
    PayoutResponse, RotatedWebhookSecret, UpdateWebhookConfigParams, WebhookConfig,
};

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 2;
const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
const NETWORK_MESSAGE: &str = "Network error — check your connection and base URL";

/// Async client for the BitMomo merchant API. Cheap to clone; clones share
/// one connection pool.
///
/// Reads retry on 429 and 5xx (twice by default, honouring `Retry-After` up
/// to 60 seconds). Writes are never retried for you: keep the idempotency key
/// and retry with the same one. Redirects are refused, so the API key is
/// never sent to another host.
#[derive(Debug, Clone)]
pub struct Client {
    http: reqwest::Client,
    base_url: String,
    api_key: String,
    max_retries: u32,
}

/// Configures a [`Client`].
#[derive(Debug, Clone)]
pub struct ClientBuilder {
    api_key: String,
    base_url: String,
    timeout: Duration,
    max_retries: u32,
}

impl ClientBuilder {
    /// Per-request timeout (default 30 seconds).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// How many times reads are retried on 429 and 5xx (default 2).
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Build the client. Fails when the API key is empty or the base URL is
    /// not an HTTPS origin (plain HTTP is allowed only for localhost).
    pub fn build(self) -> Result<Client, Error> {
        if self.api_key.is_empty() {
            return Err(Error::invalid("api_key is required"));
        }
        let base_url = api_origin(&self.base_url)?;
        let http = reqwest::Client::builder()
            .timeout(self.timeout)
            .redirect(redirect::Policy::none())
            .user_agent(format!("bitmomo-rust/{}", crate::VERSION))
            .build()
            .map_err(|e| {
                Error::invalid(format!("could not build the HTTP client: {e}")).with_source(e)
            })?;
        Ok(Client {
            http,
            base_url,
            api_key: self.api_key,
            max_retries: self.max_retries,
        })
    }
}

fn api_origin(raw: &str) -> Result<String, Error> {
    let invalid = || Error::invalid("an explicit valid base_url is required");
    if raw.is_empty() {
        return Err(invalid());
    }
    let url = Url::parse(raw).map_err(|_| invalid())?;
    let host = url.host_str().ok_or_else(invalid)?.to_string();
    let scheme = url.scheme();
    let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "[::1]");
    if (scheme != "https" && !(scheme == "http" && loopback))
        || !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some_and(|q| !q.is_empty())
        || url.fragment().is_some()
        || url.path() != "/"
    {
        return Err(Error::invalid(
            "base_url must be an HTTPS origin (loopback HTTP is allowed), without credentials, path, query or fragment",
        ));
    }
    Ok(match url.port() {
        Some(port) => format!("{scheme}://{host}:{port}"),
        None => format!("{scheme}://{host}"),
    })
}

/// Percent-encode one path segment (everything but unreserved characters).
fn segment(name: &str, value: &str) -> Result<String, Error> {
    if value.is_empty() {
        return Err(Error::invalid(format!("{name} is required")));
    }
    let mut out = String::with_capacity(value.len());
    for b in value.bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    Ok(out)
}

pub(crate) fn retry_delay(retry_after: Option<&str>, attempt: u32) -> Duration {
    if let Some(seconds) = retry_after.and_then(|v| v.trim().parse::<f64>().ok()) {
        if seconds.is_finite() && seconds >= 0.0 {
            return Duration::from_secs_f64(seconds).min(MAX_RETRY_AFTER);
        }
    }
    Duration::from_millis(250u64 << attempt.min(16))
}

fn network(error: reqwest::Error) -> Error {
    Error::new(0, "NETWORK_ERROR", NETWORK_MESSAGE).with_source(error)
}

fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, Error> {
    if bytes.is_empty() {
        return Err(Error::schema("the response body is empty"));
    }
    serde_json::from_slice(bytes).map_err(|e| {
        Error::schema(format!("the response does not match the contract: {e}")).with_source(e)
    })
}

fn json_body<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, Error> {
    serde_json::to_vec(value)
        .map_err(|e| Error::invalid(format!("could not encode the request: {e}")).with_source(e))
}

struct Call {
    method: Method,
    path: String,
    query: Vec<(&'static str, String)>,
    body: Option<Vec<u8>>,
    idempotency_key: Option<String>,
}

impl Call {
    fn new(method: Method, path: impl Into<String>) -> Self {
        Call {
            method,
            path: path.into(),
            query: Vec::new(),
            body: None,
            idempotency_key: None,
        }
    }
}

impl Client {
    /// A client with default settings. See [`Client::builder`].
    pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Result<Self, Error> {
        Client::builder(api_key, base_url).build()
    }

    /// Configure a client, for example `Client::builder(key, url).timeout(..).build()`.
    pub fn builder(api_key: impl Into<String>, base_url: impl Into<String>) -> ClientBuilder {
        ClientBuilder {
            api_key: api_key.into(),
            base_url: base_url.into(),
            timeout: DEFAULT_TIMEOUT,
            max_retries: DEFAULT_MAX_RETRIES,
        }
    }

    /// The normalized API origin.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    async fn execute(&self, call: Call) -> Result<Vec<u8>, Error> {
        let url = format!("{}{}", self.base_url, call.path);
        let mut attempt = 0u32;
        loop {
            let mut request = self
                .http
                .request(call.method.clone(), &url)
                .header(ACCEPT, "application/json")
                .header("X-API-Key", &self.api_key);
            if !call.query.is_empty() {
                request = request.query(&call.query);
            }
            if let Some(body) = &call.body {
                request = request
                    .header(CONTENT_TYPE, "application/json")
                    .body(body.clone());
            }
            if let Some(key) = &call.idempotency_key {
                request = request.header("Idempotency-Key", key);
            }
            let response = request.send().await.map_err(network)?;
            let status = response.status().as_u16();
            let retry_after = response
                .headers()
                .get(RETRY_AFTER)
                .and_then(|v| v.to_str().ok())
                .map(str::to_string);
            let bytes = response.bytes().await.map_err(network)?;
            if call.method == Method::GET
                && attempt < self.max_retries
                && (status == 429 || (500..=599).contains(&status))
            {
                tokio::time::sleep(retry_delay(retry_after.as_deref(), attempt)).await;
                attempt += 1;
                continue;
            }
            if !(200..=299).contains(&status) {
                return Err(Error::from_response(
                    status,
                    &String::from_utf8_lossy(&bytes),
                ));
            }
            return Ok(bytes.to_vec());
        }
    }

    async fn fetch<T: DeserializeOwned>(&self, call: Call) -> Result<T, Error> {
        decode(&self.execute(call).await?)
    }

    /// Create a payment. Set `idempotency_key` and reuse it on retry so a
    /// retried request cannot create a second payment.
    pub async fn create_payment(
        &self,
        params: &CreatePaymentParams,
    ) -> Result<CreatedPayment, Error> {
        if !is_plain_decimal(params.amount.as_str()) {
            return Err(Error::invalid(
                "amount must be a decimal such as \"150.00\"",
            ));
        }
        if params.crypto_type.is_empty() {
            return Err(Error::invalid("crypto_type is required"));
        }
        let mut call = Call::new(Method::POST, "/api/v1/gateway/payments");
        call.body = Some(json_body(params)?);
        self.fetch(call).await
    }

    /// The full payment.
    pub async fn get_payment(&self, payment_id: &str) -> Result<Payment, Error> {
        let path = format!(
            "/api/v1/gateway/payments/{}",
            segment("payment_id", payment_id)?
        );
        self.fetch(Call::new(Method::GET, path)).await
    }

    /// The payment's current status. Unknown values are refused rather than passed on.
    pub async fn get_payment_status(&self, payment_id: &str) -> Result<PaymentStatus, Error> {
        let path = format!(
            "/api/v1/payments/{}/status",
            segment("payment_id", payment_id)?
        );
        let raw: Value = self.fetch(Call::new(Method::GET, path)).await?;
        match raw.as_str().map(PaymentStatus::parse) {
            Some(status) if status.is_known() => Ok(status),
            _ => Err(Error::new(
                500,
                "INTERNAL_ERROR",
                format!("Unexpected payment status payload for {payment_id}"),
            )),
        }
    }

    /// A page of payments, newest first.
    pub async fn list_payments(&self, params: &ListPaymentsParams) -> Result<PaymentList, Error> {
        let mut call = Call::new(Method::GET, "/api/v1/gateway/payments");
        if let Some(page) = params.page {
            call.query.push(("page", page.to_string()));
        }
        if let Some(limit) = params.limit {
            call.query.push(("limit", limit.to_string()));
        }
        if let Some(status) = &params.status {
            call.query
                .push(("status_filter", status.as_str().to_string()));
        }
        self.fetch(call).await
    }

    /// Withdraw to the merchant's payout method. `idempotency_key` is
    /// required; reuse it on retry so the server returns the original payout.
    pub async fn request_payout(&self, params: &PayoutParams) -> Result<PayoutResponse, Error> {
        let key = params.idempotency_key.trim();
        if key.is_empty() {
            return Err(Error::new(
                0,
                "MISSING_IDEMPOTENCY_KEY",
                "bitmomo: request_payout requires idempotency_key. Mint one with new_idempotency_key() and \
                 reuse it across retries; a fresh key per call creates a second withdrawal.",
            ));
        }
        if !is_plain_decimal(params.amount.as_str()) {
            return Err(Error::invalid(
                "amount must be a decimal such as \"150.00\"",
            ));
        }
        let mut body = serde_json::Map::new();
        body.insert(
            "amount".into(),
            Value::String(params.amount.as_str().to_string()),
        );
        if let Some(method) = &params.settlement_method {
            body.insert("settlement_method".into(), Value::String(method.clone()));
        }
        let mut call = Call::new(Method::POST, "/api/v1/gateway/payouts");
        call.body = Some(json_body(&body)?);
        call.idempotency_key = Some(key.to_string());
        self.fetch(call).await
    }

    /// Current rates, sorted by crypto type then fiat currency.
    pub async fn get_rates(&self) -> Result<Vec<ExchangeRate>, Error> {
        let raw: Value = self.fetch(Call::new(Method::GET, "/api/v1/rates")).await?;
        parse_rates(&raw)
    }

    /// The merchant's balances in the key's environment.
    pub async fn get_balances(&self) -> Result<Balances, Error> {
        self.fetch(Call::new(Method::GET, "/api/v1/gateway/balances"))
            .await
    }

    /// The webhook settings.
    pub async fn get_webhook_config(&self) -> Result<WebhookConfig, Error> {
        self.fetch(Call::new(Method::GET, "/api/v1/gateway/webhooks/config"))
            .await
    }

    /// Replace the webhook settings. A first-time setup returns the signing
    /// secret once, in `WebhookConfig::secret`.
    pub async fn update_webhook_config(
        &self,
        params: &UpdateWebhookConfigParams,
    ) -> Result<WebhookConfig, Error> {
        if params.url.is_empty() {
            return Err(Error::invalid("url is required"));
        }
        let mut call = Call::new(Method::PUT, "/api/v1/gateway/webhooks/config");
        call.body = Some(json_body(params)?);
        self.fetch(call).await
    }

    /// Issue a new signing secret. Keep accepting the old one during the grace period.
    pub async fn rotate_webhook_secret(&self) -> Result<RotatedWebhookSecret, Error> {
        self.fetch(Call::new(
            Method::POST,
            "/api/v1/gateway/webhooks/config/rotate",
        ))
        .await
    }

    /// Remove the webhook settings.
    pub async fn delete_webhook_config(&self) -> Result<(), Error> {
        self.execute(Call::new(Method::DELETE, "/api/v1/gateway/webhooks/config"))
            .await?;
        Ok(())
    }

    /// Create a reusable payment link.
    pub async fn create_payment_link(
        &self,
        params: &CreatePaymentLinkParams,
    ) -> Result<PaymentLink, Error> {
        if params.name.is_empty() {
            return Err(Error::invalid("name is required"));
        }
        if params.preset_amount_ghs.is_some_and(|a| !a.is_finite()) {
            return Err(Error::invalid("preset_amount_ghs must be finite"));
        }
        let mut call = Call::new(Method::POST, "/api/v1/gateway/payment-links");
        call.body = Some(json_body(params)?);
        self.fetch(call).await
    }

    /// Every payment link.
    pub async fn list_payment_links(&self) -> Result<Vec<PaymentLink>, Error> {
        let links: PaymentLinks = self
            .fetch(Call::new(Method::GET, "/api/v1/gateway/payment-links"))
            .await?;
        Ok(links.payment_links)
    }

    /// One payment link with its statistics.
    pub async fn get_payment_link(&self, link_id: &str) -> Result<PaymentLink, Error> {
        let path = format!(
            "/api/v1/gateway/payment-links/{}",
            segment("link_id", link_id)?
        );
        self.fetch(Call::new(Method::GET, path)).await
    }
}

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

    #[test]
    fn retry_delays() {
        assert_eq!(retry_delay(None, 0), Duration::from_millis(250));
        assert_eq!(retry_delay(None, 1), Duration::from_millis(500));
        assert_eq!(retry_delay(Some("2"), 0), Duration::from_secs(2));
        assert_eq!(retry_delay(Some(" 1.5 "), 0), Duration::from_millis(1500));
        assert_eq!(retry_delay(Some("86400"), 0), MAX_RETRY_AFTER);
        assert_eq!(retry_delay(Some("soon"), 1), Duration::from_millis(500));
        assert_eq!(retry_delay(Some("-1"), 0), Duration::from_millis(250));
    }

    #[test]
    fn base_url_rules() {
        for (input, origin) in [
            ("https://api.dev.bitmomo.app", "https://api.dev.bitmomo.app"),
            (
                "https://API.dev.bitmomo.app/",
                "https://api.dev.bitmomo.app",
            ),
            (
                "https://api.dev.bitmomo.app:8443",
                "https://api.dev.bitmomo.app:8443",
            ),
            ("http://localhost:3000", "http://localhost:3000"),
            ("http://127.0.0.1:3000/", "http://127.0.0.1:3000"),
            ("http://[::1]:3000", "http://[::1]:3000"),
        ] {
            assert_eq!(api_origin(input).unwrap(), origin, "{input}");
        }
        for input in [
            "",
            "api.dev.bitmomo.app",
            "http://api.dev.bitmomo.app",
            "https://user:pass@api.dev.bitmomo.app",
            "https://api.dev.bitmomo.app/api/v1",
            "https://api.dev.bitmomo.app?x=1",
            "https://api.dev.bitmomo.app#frag",
            "ftp://api.dev.bitmomo.app",
            "https://api.dev.bitmomo.app:notaport",
        ] {
            assert!(api_origin(input).is_err(), "{input}");
        }
    }

    #[test]
    fn segments_are_percent_encoded() {
        assert_eq!(segment("id", "a/b?c").unwrap(), "a%2Fb%3Fc");
        assert_eq!(segment("id", "8d0b6a52-1c4e").unwrap(), "8d0b6a52-1c4e");
        assert!(segment("id", "").is_err());
    }
}