delopay 0.3.0

Official Rust SDK for the DeloPay payments API
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
//! The `merchant_accounts` resource: the top-level merchant account objects
//! that own shops (business profiles) and connectors.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::merchant_account::MerchantAccountResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `merchant_accounts` resource, obtained via
/// [`crate::Delopay::merchant_accounts`].
#[derive(Debug, Clone)]
pub struct MerchantAccounts {
    inner: Arc<Inner>,
}

impl MerchantAccounts {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Create a merchant account. `POST /accounts`
    pub async fn create(
        &self,
        params: &MerchantAccountCreateRequest,
    ) -> Result<MerchantAccountResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/accounts", Some(&body), &[], None)
            .await
    }

    /// Retrieve a merchant account. `GET /accounts/{account_id}`
    pub async fn retrieve(&self, account_id: &str) -> Result<MerchantAccountResponse> {
        let path = format!("/accounts/{}", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a merchant account. `POST /accounts/{account_id}`
    pub async fn update(
        &self,
        account_id: &str,
        params: &MerchantAccountUpdateRequest,
    ) -> Result<MerchantAccountResponse> {
        params.validate()?;
        let path = format!("/accounts/{}", encode_segment(account_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a merchant account. `DELETE /accounts/{account_id}`
    pub async fn delete(&self, account_id: &str) -> Result<MerchantAccountResponse> {
        let path = format!("/accounts/{}", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// List all merchant accounts. `GET /accounts/list`
    pub async fn list(&self) -> Result<Vec<MerchantAccountResponse>> {
        self.inner
            .request(HttpMethod::Get, "/accounts/list", None, &[], None)
            .await
    }

    /// Toggle the key-value store for a merchant.
    /// `POST /accounts/{account_id}/kv`
    pub async fn toggle_kv(&self, account_id: &str) -> Result<Value> {
        let path = format!("/accounts/{}/kv", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Get the key-value store status for a merchant.
    /// `GET /accounts/{account_id}/kv`
    pub async fn kv_status(&self, account_id: &str) -> Result<Value> {
        let path = format!("/accounts/{}/kv", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Transfer keys between merchants. `POST /accounts/transfer`
    ///
    /// Open body shape — see the API reference.
    pub async fn transfer_keys(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/accounts/transfer",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// Placeholder printed in place of a credential-bearing field.
const REDACTED: &str = "[redacted]";

/// `Some("[redacted]")` when the credential field is set, `None` when it is
/// not.
fn redact(v: Option<&Value>) -> Option<&'static str> {
    v.map(|_| REDACTED)
}

/// Parameters for [`MerchantAccounts::create`].
///
/// `Debug` is hand-written: `webhook_details` carries outgoing-webhook
/// credentials (basic-auth username/password, custom auth headers), so a
/// derived `Debug` would leak them into logs.
#[derive(Clone, Default, Serialize)]
pub struct MerchantAccountCreateRequest {
    /// The merchant account ID to create. Required by the API.
    pub merchant_id: String,
    /// Display name for the merchant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_name: Option<String>,
    /// Default URL customers are returned to after a payment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Outgoing-webhook configuration (open shape). **May hold credentials.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_details: Option<Value>,
    /// Whether this merchant may own sub-merchants.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub_merchants_enabled: Option<bool>,
    /// Parent merchant, when this account is a sub-merchant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_merchant_id: Option<String>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Publishable (client-side) key to assign.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub publishable_key: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for MerchantAccountCreateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MerchantAccountCreateRequest")
            .field("merchant_id", &self.merchant_id)
            .field("merchant_name", &self.merchant_name)
            .field("return_url", &self.return_url)
            .field("webhook_details", &redact(self.webhook_details.as_ref()))
            .field("sub_merchants_enabled", &self.sub_merchants_enabled)
            .field("parent_merchant_id", &self.parent_merchant_id)
            .field("metadata", &self.metadata)
            .field("publishable_key", &self.publishable_key)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `MerchantAccountCreateRequest`'s fields, as they appear on the
/// wire (`extra` excluded).
const MERCHANT_ACCOUNT_CREATE_REQUEST_NAMED: &[&str] = &[
    "merchant_id",
    "merchant_name",
    "return_url",
    "webhook_details",
    "sub_merchants_enabled",
    "parent_merchant_id",
    "metadata",
    "publishable_key",
];

impl ValidateRequest for MerchantAccountCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if MERCHANT_ACCOUNT_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on \
                     MerchantAccountCreateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl MerchantAccountCreateRequest {
    /// A request creating the merchant account with the given ID.
    pub fn new(merchant_id: impl Into<String>) -> Self {
        Self {
            merchant_id: merchant_id.into(),
            ..Default::default()
        }
    }

    /// Set the merchant's display name.
    #[must_use]
    pub fn merchant_name(mut self, name: impl Into<String>) -> Self {
        self.merchant_name = Some(name.into());
        self
    }

    /// Set the default return URL.
    #[must_use]
    pub fn return_url(mut self, url: impl Into<String>) -> Self {
        self.return_url = Some(url.into());
        self
    }

    /// Set the outgoing-webhook configuration.
    #[must_use]
    pub fn webhook_details(mut self, details: Value) -> Self {
        self.webhook_details = Some(details);
        self
    }
}

/// Parameters for [`MerchantAccounts::update`].
///
/// `Debug` is hand-written for the same reason as
/// [`MerchantAccountCreateRequest`]: `webhook_details` is redacted.
#[derive(Clone, Default, Serialize)]
pub struct MerchantAccountUpdateRequest {
    /// The merchant account being updated. Required by the API.
    pub merchant_id: String,
    /// Display name for the merchant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_name: Option<String>,
    /// Default URL customers are returned to after a payment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Outgoing-webhook configuration (open shape). **May hold credentials.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_details: Option<Value>,
    /// Whether this merchant may own sub-merchants.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub_merchants_enabled: Option<bool>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for MerchantAccountUpdateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MerchantAccountUpdateRequest")
            .field("merchant_id", &self.merchant_id)
            .field("merchant_name", &self.merchant_name)
            .field("return_url", &self.return_url)
            .field("webhook_details", &redact(self.webhook_details.as_ref()))
            .field("sub_merchants_enabled", &self.sub_merchants_enabled)
            .field("metadata", &self.metadata)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `MerchantAccountUpdateRequest`'s fields, as they appear on the
/// wire (`extra` excluded).
const MERCHANT_ACCOUNT_UPDATE_REQUEST_NAMED: &[&str] = &[
    "merchant_id",
    "merchant_name",
    "return_url",
    "webhook_details",
    "sub_merchants_enabled",
    "metadata",
];

impl ValidateRequest for MerchantAccountUpdateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if MERCHANT_ACCOUNT_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on \
                     MerchantAccountUpdateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl MerchantAccountUpdateRequest {
    /// A request updating the merchant account with the given ID.
    pub fn new(merchant_id: impl Into<String>) -> Self {
        Self {
            merchant_id: merchant_id.into(),
            ..Default::default()
        }
    }

    /// Set the merchant's display name.
    #[must_use]
    pub fn merchant_name(mut self, name: impl Into<String>) -> Self {
        self.merchant_name = Some(name.into());
        self
    }

    /// Set the default return URL.
    #[must_use]
    pub fn return_url(mut self, url: impl Into<String>) -> Self {
        self.return_url = Some(url.into());
        self
    }

    /// Set the outgoing-webhook configuration.
    #[must_use]
    pub fn webhook_details(mut self, details: Value) -> Self {
        self.webhook_details = Some(details);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with};
    use serde_json::json;

    const ACCOUNT_JSON: &str = r#"{
        "merchant_id": "mer_1",
        "merchant_name": "Acme",
        "organization_id": "org_1",
        "merchant_account_type": "standard",
        "enable_payment_response_hash": true,
        "redirect_to_merchant_with_http_post": false,
        "primary_business_details": [],
        "is_recon_enabled": false,
        "recon_status": "not_requested"
    }"#;

    fn full_create_request() -> MerchantAccountCreateRequest {
        MerchantAccountCreateRequest {
            merchant_id: "mer_1".to_string(),
            merchant_name: Some("Acme".to_string()),
            return_url: Some("https://acme.test/return".to_string()),
            webhook_details: Some(json!({"webhook_password": "hunter2"})),
            sub_merchants_enabled: Some(true),
            parent_merchant_id: Some("mer_parent".to_string()),
            metadata: Some(json!({"tier": "gold"})),
            publishable_key: Some("pk_test_1".to_string()),
            extra: serde_json::Map::new(),
        }
    }

    fn full_update_request() -> MerchantAccountUpdateRequest {
        MerchantAccountUpdateRequest {
            merchant_id: "mer_1".to_string(),
            merchant_name: Some("Acme".to_string()),
            return_url: Some("https://acme.test/return".to_string()),
            webhook_details: Some(json!({"webhook_password": "hunter2"})),
            sub_merchants_enabled: Some(true),
            metadata: Some(json!({"tier": "gold"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard for `MERCHANT_ACCOUNT_CREATE_REQUEST_NAMED`.
    #[test]
    fn merchant_account_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_create_request()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                MERCHANT_ACCOUNT_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "MERCHANT_ACCOUNT_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `MERCHANT_ACCOUNT_UPDATE_REQUEST_NAMED`.
    #[test]
    fn merchant_account_update_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_update_request()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                MERCHANT_ACCOUNT_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "MERCHANT_ACCOUNT_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_colliding_extra_keys() {
        let mut create = MerchantAccountCreateRequest::new("mer_1");
        create
            .extra
            .insert("merchant_name".to_string(), json!("collide"));
        match create.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("merchant_name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut update = MerchantAccountUpdateRequest::new("mer_1");
        update.extra.insert("metadata".to_string(), json!({}));
        assert!(matches!(
            update.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    /// Webhook credentials must never reach a log line.
    #[test]
    fn debug_redacts_webhook_details() {
        let created = format!("{:?}", full_create_request());
        assert!(!created.contains("hunter2"), "{created}");
        assert!(
            created.contains("webhook_details: Some(\"[redacted]\")"),
            "{created}"
        );
        assert!(created.contains("mer_1"), "{created}");

        let updated = format!("{:?}", full_update_request());
        assert!(!updated.contains("hunter2"), "{updated}");
        assert!(
            updated.contains("webhook_details: Some(\"[redacted]\")"),
            "{updated}"
        );
    }

    /// An unset `webhook_details` must be distinguishable from a set one.
    #[test]
    fn debug_shows_none_for_unset_webhook_details() {
        let rendered = format!("{:?}", MerchantAccountCreateRequest::new("mer_1"));
        assert!(rendered.contains("webhook_details: None"), "{rendered}");
    }

    #[tokio::test]
    async fn create_posts_to_accounts() {
        let (client, mock) = client_with(vec![Step::ok(ACCOUNT_JSON)]);
        let req = MerchantAccountCreateRequest::new("mer_1").merchant_name("Acme");
        let created = client.merchant_accounts().create(&req).await.unwrap();
        assert_eq!(created.merchant_id, "mer_1");
        assert_eq!(created.merchant_name.as_deref(), Some("Acme"));
        assert_eq!(created.enable_payment_response_hash, Some(true));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/accounts");
        assert_eq!(seen[0].body_json()["merchant_name"], "Acme");
    }

    #[tokio::test]
    async fn retrieve_update_and_delete_hit_the_account_path() {
        let (client, mock) = client_with(vec![
            Step::ok(ACCOUNT_JSON),
            Step::ok(ACCOUNT_JSON),
            Step::ok(ACCOUNT_JSON),
        ]);
        let accounts = client.merchant_accounts();
        let retrieved = accounts.retrieve("mer/1").await.unwrap();
        assert_eq!(retrieved.organization_id.as_deref(), Some("org_1"));
        accounts
            .update(
                "mer_1",
                &MerchantAccountUpdateRequest::new("mer_1").return_url("https://a.test"),
            )
            .await
            .unwrap();
        accounts.delete("mer_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/accounts/mer%2F1")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("POST", "https://api.test/accounts/mer_1")
        );
        assert_eq!(seen[1].body_json()["return_url"], "https://a.test");
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("DELETE", "https://api.test/accounts/mer_1")
        );
    }

    #[tokio::test]
    async fn list_kv_and_transfer_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok("[]"),
            Step::ok(r#"{"kv_enabled":true}"#),
            Step::ok(r#"{"kv_enabled":true}"#),
            Step::ok(r#"{"transferred":1}"#),
        ]);
        let accounts = client.merchant_accounts();
        assert!(accounts.list().await.unwrap().is_empty());
        accounts.toggle_kv("mer_1").await.unwrap();
        accounts.kv_status("mer_1").await.unwrap();
        accounts
            .transfer_keys(&json!({"from": "mer_1", "to": "mer_2"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/accounts/list")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("POST", "https://api.test/accounts/mer_1/kv")
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("GET", "https://api.test/accounts/mer_1/kv")
        );
        assert_eq!(
            (seen[3].method, seen[3].url.as_str()),
            ("POST", "https://api.test/accounts/transfer")
        );
        assert_eq!(seen[3].body_json()["to"], "mer_2");
    }
}