delopay 0.2.1

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
//! The `payouts` resource.

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::common::{Currency, ListResponse, PayoutType};
use crate::core::models::payout::PayoutResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Create a payout.
    pub async fn create(&self, params: &PayoutCreateRequest) -> Result<PayoutResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/payouts/create", Some(&body), &[], None)
            .await
    }

    /// Retrieve a payout by ID.
    pub async fn retrieve(&self, payout_id: &str) -> Result<PayoutResponse> {
        let path = format!("/payouts/{}", encode_segment(payout_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a payout before it is confirmed.
    pub async fn update(
        &self,
        payout_id: &str,
        params: &PayoutUpdateRequest,
    ) -> Result<PayoutResponse> {
        params.validate()?;
        let path = format!("/payouts/{}", encode_segment(payout_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Confirm a created payout, triggering the actual transfer. Pass `None`
    /// to confirm without changing anything.
    pub async fn confirm(
        &self,
        payout_id: &str,
        params: Option<&PayoutUpdateRequest>,
    ) -> Result<PayoutResponse> {
        let path = format!("/payouts/{}/confirm", encode_segment(payout_id));
        let body: Option<Vec<u8>> = match params {
            Some(p) => {
                p.validate()?;
                Some(to_json_vec(p)?)
            }
            None => None,
        };
        self.inner
            .request(HttpMethod::Post, &path, body.as_deref(), &[], None)
            .await
    }

    /// Fulfil a confirmed payout.
    pub async fn fulfill(&self, payout_id: &str) -> Result<PayoutResponse> {
        let path = format!("/payouts/{}/fulfill", encode_segment(payout_id));
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Cancel a payout.
    pub async fn cancel(&self, payout_id: &str) -> Result<PayoutResponse> {
        let path = format!("/payouts/{}/cancel", encode_segment(payout_id));
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// List payouts, optionally filtered.
    pub async fn list(
        &self,
        params: Option<&PayoutListParams>,
    ) -> Result<ListResponse<PayoutResponse>> {
        let query = params.map(PayoutListParams::to_query).unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/payouts/list", None, &query, None)
            .await
    }
}

/// Filter / pagination parameters for [`Payouts::list`]. Pages with a cursor:
/// pass the last payout's ID as `starting_after` to fetch the next page.
#[derive(Debug, Clone, Default)]
pub struct PayoutListParams {
    /// Only payouts for this customer.
    pub customer_id: Option<String>,
    /// Return payouts created after this payout ID (cursor).
    pub starting_after: Option<String>,
    /// Return payouts created before this payout ID (cursor).
    pub ending_before: Option<String>,
    /// Maximum number of payouts to return.
    pub limit: Option<i64>,
    /// Only payouts created at this ISO 8601 timestamp.
    pub created: Option<String>,
    /// Only payouts created at/after this ISO 8601 timestamp.
    pub start_time: Option<String>,
    /// Only payouts created at/before this ISO 8601 timestamp.
    pub end_time: Option<String>,
}

impl PayoutListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.customer_id {
            q.push(("customer_id", v.clone()));
        }
        if let Some(v) = &self.starting_after {
            q.push(("starting_after", v.clone()));
        }
        if let Some(v) = &self.ending_before {
            q.push(("ending_before", v.clone()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = &self.created {
            q.push(("created", v.clone()));
        }
        if let Some(v) = &self.start_time {
            q.push(("start_time", v.clone()));
        }
        if let Some(v) = &self.end_time {
            q.push(("end_time", v.clone()));
        }
        q
    }
}

/// Parameters for [`Payouts::update`] and the optional body of
/// [`Payouts::confirm`]. All fields are optional; only the set ones are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct PayoutUpdateRequest {
    /// Your own order reference for this payout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_order_reference_id: Option<String>,
    /// New amount in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<i64>,
    /// Three-letter ISO 4217 currency code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<Currency>,
    /// Routing override (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub routing: Option<Value>,
    /// Restrict which connectors may be used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector: Option<Vec<String>>,
    /// Confirm as part of the update.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirm: Option<bool>,
    /// Payout method family.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payout_type: Option<PayoutType>,
    /// Payout method data (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payout_method_data: Option<Value>,
    /// Billing address (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Value>,
    /// Customer to pay out to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Human-readable description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Redirect URL after any payout-side customer step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Recipient entity type, e.g. `"Individual"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entity_type: Option<String>,
    /// 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>,
}

/// Names of `PayoutUpdateRequest`'s fields, as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const PAYOUT_UPDATE_REQUEST_NAMED: &[&str] = &[
    "merchant_order_reference_id",
    "amount",
    "currency",
    "routing",
    "connector",
    "confirm",
    "payout_type",
    "payout_method_data",
    "billing",
    "customer_id",
    "description",
    "return_url",
    "entity_type",
    "metadata",
];

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

/// Parameters for [`Payouts::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PayoutCreateRequest {
    /// Amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Confirm immediately upon creation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirm: Option<bool>,
    /// Automatically fulfil once confirmed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_fulfill: Option<bool>,
    /// Payout method family.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payout_type: Option<PayoutType>,
    /// Payout method data (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payout_method_data: Option<Value>,
    /// Customer to pay out to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Human-readable description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Shop (business profile) ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Billing address (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Value>,
    /// 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>,
}

/// Names of `PayoutCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const PAYOUT_CREATE_REQUEST_NAMED: &[&str] = &[
    "amount",
    "currency",
    "confirm",
    "auto_fulfill",
    "payout_type",
    "payout_method_data",
    "customer_id",
    "description",
    "profile_id",
    "billing",
    "metadata",
];

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

impl PayoutCreateRequest {
    /// A new payout for `amount` (minor units) in `currency`.
    pub fn new(amount: i64, currency: impl Into<Currency>) -> Self {
        Self {
            amount,
            currency: currency.into(),
            ..Default::default()
        }
    }
}

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

    /// Every optional field populated so serialization emits the full key set.
    fn full_payout_create_request() -> PayoutCreateRequest {
        PayoutCreateRequest {
            amount: 100,
            currency: "EUR".to_string(),
            confirm: Some(true),
            auto_fulfill: Some(true),
            payout_type: Some("bank".to_string()),
            payout_method_data: Some(json!({"iban": "DE00"})),
            customer_id: Some("cus_1".to_string()),
            description: Some("payout desc".to_string()),
            profile_id: Some("pro_1".to_string()),
            billing: Some(json!({"country": "DE"})),
            metadata: Some(json!({"order_id": "o_1"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard: catches a new field added to `PayoutCreateRequest`
    /// without a matching update to `PAYOUT_CREATE_REQUEST_NAMED`.
    #[test]
    fn payout_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_payout_create_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                PAYOUT_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "PAYOUT_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or PayoutCreateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = PayoutCreateRequest::new(100, "EUR");
        req.extra.insert("amount".to_string(), json!(999));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// Every optional field populated so serialization emits the full key set.
    fn full_payout_update_request() -> PayoutUpdateRequest {
        PayoutUpdateRequest {
            merchant_order_reference_id: Some("ord_1".to_string()),
            amount: Some(100),
            currency: Some("EUR".to_string()),
            routing: Some(json!({"type": "single"})),
            connector: Some(vec!["stripe".to_string()]),
            confirm: Some(true),
            payout_type: Some("bank".to_string()),
            payout_method_data: Some(json!({"iban": "DE00"})),
            billing: Some(json!({"country": "DE"})),
            customer_id: Some("cus_1".to_string()),
            description: Some("desc".to_string()),
            return_url: Some("https://example.com/r".to_string()),
            entity_type: Some("Individual".to_string()),
            metadata: Some(json!({"k": "v"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard for `PAYOUT_UPDATE_REQUEST_NAMED`.
    #[test]
    fn payout_update_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_payout_update_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                PAYOUT_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "PAYOUT_UPDATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or PayoutUpdateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    use crate::http::mock::{Step, client_with};

    const PAYOUT_JSON: &str = r#"{
        "payout_id": "po_1", "merchant_id": "mer_1", "amount": 100,
        "currency": "EUR", "status": "requires_confirmation"
    }"#;

    #[tokio::test]
    async fn update_puts_to_the_payout_path() {
        // The verb is the point: `update` must be a PUT, not the POST every
        // other payout transition uses.
        let (client, mock) = client_with(vec![Step::ok(PAYOUT_JSON)]);
        let req = PayoutUpdateRequest {
            amount: Some(700),
            ..Default::default()
        };
        client.payouts().update("po_1", &req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/payouts/po_1");
        assert_eq!(seen[0].body_json()["amount"], 700);
    }

    #[tokio::test]
    async fn confirm_carries_the_optional_body() {
        let (client, mock) = client_with(vec![Step::ok(PAYOUT_JSON), Step::ok(PAYOUT_JSON)]);
        client.payouts().confirm("po_1", None).await.unwrap();
        let req = PayoutUpdateRequest {
            description: Some("go".to_string()),
            ..Default::default()
        };
        client.payouts().confirm("po_1", Some(&req)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/payouts/po_1/confirm");
        assert!(seen[0].body.is_none(), "None params must send no body");
        assert_eq!(seen[1].body_json()["description"], "go");
    }

    #[tokio::test]
    async fn list_serializes_cursor_params() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"size":0,"data":[]}"#)]);
        let params = PayoutListParams {
            starting_after: Some("po_9".to_string()),
            limit: Some(25),
            ..Default::default()
        };
        client.payouts().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payouts/list?starting_after=po_9&limit=25"
        );
    }
}