delopay 0.7.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
//! The payment intent model.

use std::fmt;

use serde::Deserialize;
use serde_json::Value;

use crate::core::models::common::{
    AttemptStatus, Currency, IntentStatus, PaymentMethod, PaymentMethodType,
};

/// A payment intent as returned by the API.
///
/// Unmodeled fields are preserved in [`extra`](PaymentResponse::extra) so new
/// API fields never break deserialization.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentResponse {
    /// Unique payment intent ID.
    pub payment_id: String,
    /// Merchant account ID that owns this payment.
    pub merchant_id: String,
    /// Current lifecycle status.
    pub status: IntentStatus,
    /// Authorized amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,

    /// Net amount after discounts and tax, in minor units.
    #[serde(default)]
    pub net_amount: Option<i64>,
    /// Amount still available to capture, in minor units.
    #[serde(default)]
    pub amount_capturable: Option<i64>,
    /// Actual captured amount, in minor units (present after capture).
    #[serde(default)]
    pub amount_received: Option<i64>,
    /// Client secret for client-side confirmation. Do not log or share it:
    /// it authorises completing this payment. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Connector used to process this payment.
    #[serde(default)]
    pub connector: Option<String>,
    /// Associated customer ID.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Payment method family used.
    #[serde(default)]
    pub payment_method: Option<PaymentMethod>,
    /// Gateway error code, if the payment failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, if the payment failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Instructions for additional customer action (3DS redirect, etc.).
    #[serde(default)]
    pub next_action: Option<Value>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created: Option<String>,
    /// When the payment (its client secret / hosted checkout link) expires —
    /// the backend's *resolved* `session_expiry`, which may differ from the
    /// requested one if it was omitted or clamped. RFC 3339. Absent on
    /// backends predating the field; `null` when no expiry applies.
    #[serde(default)]
    pub expires_on: Option<String>,
    /// Arbitrary metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Which environment this payment ran in. Echoes the `test_mode` sent at
    /// create; filled in from the processor's own setting when none was sent,
    /// and `None` for a payment that never reached a processor. `None` counts
    /// as live wherever it is filtered on.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `client_secret` authorises client-side
// confirmation of this payment, so anything holding it can complete the
// charge. A `{:?}` on a payment is the most likely way it reaches a log, and
// payments are logged constantly. The field's presence is still visible --
// `Some("[redacted]")` vs `None` -- because whether a secret was issued is
// often what you are debugging.
//
// Only the *modeled* secret is covered: `extra` is printed in full, so a
// secret the API starts returning under an unmodeled key would still show up
// here until it is modeled.
impl fmt::Debug for PaymentResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PaymentResponse")
            .field("payment_id", &self.payment_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("amount", &self.amount)
            .field("currency", &self.currency)
            .field("net_amount", &self.net_amount)
            .field("amount_capturable", &self.amount_capturable)
            .field("amount_received", &self.amount_received)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("connector", &self.connector)
            .field("customer_id", &self.customer_id)
            .field("profile_id", &self.profile_id)
            .field("payment_method", &self.payment_method)
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("next_action", &self.next_action)
            .field("created", &self.created)
            .field("expires_on", &self.expires_on)
            .field("metadata", &self.metadata)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A single attempt made on a payment, with its full failure detail. Returned
/// in the `data` array of `Payments::list_attempts` — useful for surfacing
/// retries across connectors (e.g. "attempt 1 stripe → insufficient_funds,
/// attempt 2 adyen → success").
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentAttemptResponse {
    /// Unique identifier for this attempt.
    pub attempt_id: String,
    /// Status of this attempt (distinct from the parent intent's status).
    pub status: AttemptStatus,

    /// Attempt amount in minor units.
    #[serde(default)]
    pub amount: Option<i64>,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Connector (gateway) this attempt was routed to, e.g. `"stripe"`.
    #[serde(default)]
    pub connector: Option<String>,
    /// Connector's transaction identifier for this attempt.
    #[serde(default)]
    pub connector_transaction_id: Option<String>,
    /// Payment method family used for this attempt.
    #[serde(default)]
    pub payment_method: Option<PaymentMethod>,
    /// Payment method sub-type used for this attempt.
    #[serde(default)]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Raw connector error code, when the attempt failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, when the attempt failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Delopay-unified decline code (from the gateway status map).
    #[serde(default)]
    pub unified_code: Option<String>,
    /// Delopay-unified, human-readable decline message.
    #[serde(default)]
    pub unified_message: Option<String>,
    /// When the attempt was created (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// When the attempt was last modified (RFC 3339).
    #[serde(default)]
    pub modified_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One event on a payment's status timeline: the creation of, or a status
/// transition on, the payment intent or one of its attempts / refunds /
/// disputes.
///
/// [`entity_type`](Self::entity_type) is a plain `String` rather than an enum
/// so a new timeline event kind does not fail the whole response. The values
/// sent today are `"payment"`, `"attempt"`, `"refund"`, `"dispute"`, `"risk"`
/// and `"checkout"`. The last two are timeline events with **no underlying
/// status change**: `status` holds the event name rather than a payment state,
/// and `entity_id` names what it is about (the processor's risk-signal id, or
/// the native-pane method key).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentStatusHistoryEvent {
    /// What the event is about: `"payment"`, `"attempt"`, `"refund"`,
    /// `"dispute"`, `"risk"` or `"checkout"`.
    pub entity_type: String,
    /// RFC 3339 timestamp of the event.
    pub timestamp: String,

    /// Id of the attempt / refund / dispute the event belongs to. Absent for
    /// intent-level events.
    #[serde(default)]
    pub entity_id: Option<String>,
    /// The attempt this event is associated with, where known.
    #[serde(default)]
    pub attempt_id: Option<String>,
    /// The status before this event. Absent on creation and derived events.
    #[serde(default)]
    pub previous_status: Option<String>,
    /// The status after this event. Absent only on a derived creation event,
    /// where the initial status was not recorded.
    #[serde(default)]
    pub status: Option<String>,
    /// Connector involved in the event, where known.
    #[serde(default)]
    pub connector: Option<String>,
    /// Raw connector error code recorded with the event.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message recorded with the event.
    #[serde(default)]
    pub error_message: Option<String>,
    /// `true` when this event records the creation of the entity.
    #[serde(default)]
    pub is_creation: bool,
    /// `true` when this event was reconstructed from current records (payments
    /// predating the persisted status log) — its timestamp is approximate and
    /// intermediate transitions may be missing.
    #[serde(default)]
    pub derived: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The status timeline of a payment, returned by
/// [`Payments::list_status_history`](crate::resources::payments::Payments::list_status_history).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentStatusHistoryResponse {
    /// The payment this timeline belongs to.
    pub payment_id: String,
    /// `true` when every event comes from the persisted status-transition log;
    /// `false` when any event had to be reconstructed from current records.
    #[serde(default)]
    pub complete: bool,
    /// The number of events returned.
    #[serde(default)]
    pub count: i64,
    /// All recorded events, oldest first.
    #[serde(default = "Vec::new")]
    pub events: Vec<PaymentStatusHistoryEvent>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Outcome of soft-deleting a payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentsDeleteResponse {
    /// The payment that was deleted.
    pub payment_id: String,
    /// The merchant it belonged to.
    pub merchant_id: String,
    /// Always `true` on success — the endpoint errors otherwise.
    pub deleted: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Which payment statuses the calling merchant is allowed to delete.
///
/// Read this before offering a delete action: the set is merchant policy, not
/// a constant, and deleting outside it fails a precondition rather than
/// silently doing nothing.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentsDeletePolicyResponse {
    /// The deletable statuses.
    #[serde(default = "Vec::new")]
    pub statuses: Vec<IntentStatus>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One client/device observation captured while the buyer interacted with a
/// payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentClientContextEntry {
    /// Where it was captured: `checkout_open`, `confirm`, `redirect_return`,
    /// `client_signals`, …
    pub source: String,
    /// Browser-assigned device identifier.
    #[serde(default)]
    pub device_id: Option<String>,
    /// Partitioned (CHIPS) twin of [`device_id`](Self::device_id), scoped to
    /// the embedding site.
    #[serde(default)]
    pub partitioned_device_id: Option<String>,
    /// Observed IP address.
    #[serde(default)]
    pub ip_address: Option<String>,
    /// Country the IP resolved to.
    #[serde(default)]
    pub ip_country: Option<String>,
    /// Reported user agent.
    #[serde(default)]
    pub user_agent: Option<String>,
    /// Reported `Accept-Language`.
    #[serde(default)]
    pub accept_language: Option<String>,
    /// Best-effort hardware-model guess derived server-side. Display and
    /// analytics only — **never** make a decision on it.
    #[serde(default)]
    pub device_model: Option<String>,
    /// Capture-point-specific extras: client hints, screen size, referrer.
    ///
    /// The wire name is `extra`; renamed here because `extra` is this
    /// crate's catch-all for *unmodeled* fields, and one struct cannot mean
    /// both by that name.
    #[serde(rename = "extra", default)]
    pub extra_data: Option<Value>,
    /// ISO 8601 capture timestamp.
    pub created_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every client/device observation recorded for one payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentClientContextListResponse {
    /// The payment the observations belong to.
    pub payment_id: String,
    /// How many observations were returned.
    #[serde(default)]
    pub count: i64,
    /// The observations, oldest first.
    #[serde(default = "Vec::new")]
    pub data: Vec<PaymentClientContextEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    const WITH_SECRET: &str = r#"{
        "payment_id": "pay_1", "merchant_id": "mer_1", "status": "requires_confirmation",
        "amount": 1999, "currency": "EUR", "client_secret": "pay_1_secret_abc123"
    }"#;

    /// Kills a `Debug` that prints `&self.client_secret`, and a derived one.
    #[test]
    fn payment_response_debug_redacts_the_client_secret() {
        let res: PaymentResponse = serde_json::from_str(WITH_SECRET).unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("pay_1_secret_abc123"));
        assert!(printed.contains("client_secret: Some(\"[redacted]\")"));
        // Non-secret fields must still be readable, or the redaction has cost
        // more than it bought.
        assert!(printed.contains("pay_1"));
        assert!(printed.contains("1999"));
    }

    /// Kills a `Debug` that hard-codes `Some("[redacted]")` regardless of the
    /// field, which would hide whether a secret was ever issued.
    #[test]
    fn payment_response_debug_shows_none_when_no_client_secret() {
        let res: PaymentResponse = serde_json::from_str(
            r#"{"payment_id":"pay_1","merchant_id":"mer_1","status":"succeeded",
                "amount":1999,"currency":"EUR"}"#,
        )
        .unwrap();
        assert!(format!("{res:?}").contains("client_secret: None"));
    }

    /// A partially reconstructed timeline must stay readable, and a `risk` /
    /// `checkout` event — which carries an event name in `status` and no
    /// transition — must not be rejected. Mutation: typing `entity_type` as a
    /// closed enum makes the last two events fail to parse.
    #[test]
    fn status_history_parses_derived_and_non_status_events() {
        let history: PaymentStatusHistoryResponse = serde_json::from_str(
            r#"{
                "payment_id": "pay_1",
                "complete": false,
                "count": 3,
                "events": [
                    {
                        "entity_type": "payment",
                        "timestamp": "2026-08-01T10:00:00Z",
                        "status": "requires_confirmation",
                        "is_creation": true,
                        "derived": true
                    },
                    {
                        "entity_type": "attempt",
                        "entity_id": "pay_1_1",
                        "attempt_id": "pay_1_1",
                        "previous_status": "pending",
                        "status": "charged",
                        "connector": "stripe",
                        "timestamp": "2026-08-01T10:00:05Z",
                        "is_creation": false,
                        "derived": false
                    },
                    {
                        "entity_type": "checkout",
                        "entity_id": "apple_pay",
                        "status": "native_pane_selected",
                        "timestamp": "2026-08-01T10:00:03Z",
                        "is_creation": false,
                        "derived": false
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(history.payment_id, "pay_1");
        assert!(!history.complete);
        assert_eq!(history.count, 3);
        assert!(history.events[0].derived);
        assert!(history.events[0].is_creation);
        assert_eq!(history.events[0].previous_status, None);
        assert_eq!(history.events[1].connector.as_deref(), Some("stripe"));
        assert_eq!(history.events[2].entity_type, "checkout");
        assert_eq!(
            history.events[2].status.as_deref(),
            Some("native_pane_selected")
        );
    }

    /// A timeline with no events must deserialize to an empty list rather than
    /// failing. Mutation: drop `#[serde(default = "Vec::new")]`.
    #[test]
    fn status_history_defaults_to_no_events() {
        let history: PaymentStatusHistoryResponse =
            serde_json::from_str(r#"{"payment_id":"pay_1"}"#).unwrap();
        assert!(history.events.is_empty());
        assert!(!history.complete);
    }
}