delopay 0.4.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! The connector (merchant connector account) models.
//!
//! `Debug` on [`ConnectorResponse`] and [`ConnectorWebhookRegisterResponse`] is
//! hand-written: the API echoes back credential-shaped fields
//! (`connector_account_details`, `connector_webhook_details`, and the
//! connector-minted `webhook_secret`), and a derived `Debug` would put them in
//! a log line.

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

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

/// A merchant connector account as returned by the API.
///
/// Only [`merchant_connector_id`](ConnectorResponse::merchant_connector_id) is
/// required: the delete endpoint answers with a trimmed object carrying just
/// the ids, so everything else is optional rather than a hard deserialization
/// failure.
///
/// Unmodeled fields are preserved in [`extra`](ConnectorResponse::extra).
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorResponse {
    /// Unique connector account ID, e.g. `"mca_…"`.
    pub merchant_connector_id: String,

    /// Connector category, e.g. `"payment_processor"`, `"payout_processor"`.
    #[serde(default)]
    pub connector_type: Option<String>,
    /// Snake-case connector identifier, e.g. `"stripe"`, `"adyen"`.
    #[serde(default)]
    pub connector_name: Option<String>,
    /// Shop (business profile) the connector belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account that owns the connector.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Connector status, e.g. `"active"` or `"inactive"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Human-readable label, unique within the merchant account.
    #[serde(default)]
    pub connector_label: Option<String>,
    /// Gateway credentials, masked by the API. **Treated as secret**: redacted
    /// by [`Debug`].
    #[serde(default)]
    pub connector_account_details: Option<Value>,
    /// Payment methods enabled on this connector (open shapes).
    #[serde(default)]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled.
    #[serde(default)]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Treated as secret**: redacted
    /// by [`Debug`].
    #[serde(default)]
    pub connector_webhook_details: Option<Value>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// Whether the connector was deleted, on the delete endpoint's response.
    #[serde(default)]
    pub deleted: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ConnectorResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorResponse")
            .field("merchant_connector_id", &self.merchant_connector_id)
            .field("connector_type", &self.connector_type)
            .field("connector_name", &self.connector_name)
            .field("profile_id", &self.profile_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("connector_label", &self.connector_label)
            .field(
                "connector_account_details",
                &self.connector_account_details.as_ref().map(|_| REDACTED),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &self.connector_webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("created_at", &self.created_at)
            .field("deleted", &self.deleted)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Result of registering a webhook endpoint with a connector.
///
/// `webhook_secret` is the signing secret the connector minted for the new
/// endpoint (e.g. Stripe's `whsec_…`). It is already persisted server-side into
/// the connector's webhook verification details; [`Debug`] redacts it.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookRegisterResponse {
    /// Whether the registration succeeded: `"success"` or `"failure"`.
    pub webhook_registration_status: String,

    /// Event scope registered: the string `"all_events"`, or
    /// `{"specific_event": "…"}`.
    #[serde(default)]
    pub event_type: Option<Value>,
    /// Credential set registered against: `"live"` or `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// The connector's identifier for the registered endpoint.
    #[serde(default)]
    pub connector_webhook_id: Option<String>,
    /// Signing secret the connector minted for the endpoint. **Secret**:
    /// redacted by [`Debug`].
    #[serde(default)]
    pub webhook_secret: Option<String>,
    /// Error code, when the registration failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, when the registration failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ConnectorWebhookRegisterResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorWebhookRegisterResponse")
            .field(
                "webhook_registration_status",
                &self.webhook_registration_status,
            )
            .field("event_type", &self.event_type)
            .field("environment", &self.environment)
            .field("connector_webhook_id", &self.connector_webhook_id)
            .field(
                "webhook_secret",
                &self.webhook_secret.as_ref().map(|_| REDACTED),
            )
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("extra", &self.extra)
            .finish()
    }
}

/// One webhook endpoint registered with a connector.
///
/// Carries no secret: the signing secret is only ever returned at registration
/// time, so `Debug` is derived.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookEntry {
    /// The connector's identifier for this endpoint.
    pub connector_webhook_id: String,

    /// Event scope: the string `"all_events"`, or
    /// `{"specific_event": "…"}`.
    #[serde(default)]
    pub event_type: Option<Value>,
    /// Credential set the endpoint belongs to. Absent for registrations stored
    /// before environments were tracked (those are all live).
    #[serde(default)]
    pub environment: Option<String>,
    /// Callback URL the endpoint is registered to. Present when the list is
    /// sourced live from the connector (e.g. Stripe); absent for entries
    /// reconstructed from stored registration metadata only.
    #[serde(default)]
    pub webhook_url: Option<String>,
    /// Endpoint status as the connector reports it, e.g. `"enabled"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Events the endpoint is subscribed to at the connector.
    #[serde(default)]
    pub enabled_events: Option<Vec<String>>,
    /// Events Delopay handles that this endpoint is **not** subscribed to. A
    /// PSP freezes an endpoint's event list at registration time, so an
    /// endpoint registered before an event type was added keeps missing it —
    /// nothing errors, the events simply never arrive.
    ///
    /// `Some([])` means the subscription is current. A non-empty list means
    /// those events are being silently dropped; call
    /// [`Connectors::sync_webhook_events`](crate::resources::connectors::Connectors::sync_webhook_events)
    /// to repair it. `None` means the subscription could not be inspected
    /// (non-Stripe connectors, or a list reconstructed from stored metadata) —
    /// which is not the same as "checked and healthy".
    #[serde(default)]
    pub missing_events: Option<Vec<String>>,
    /// Unix timestamp (seconds) the endpoint was created at the connector.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The webhook endpoints registered for one connector.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookListResponse {
    /// Snake-case connector identifier the endpoints belong to.
    pub connector: String,
    /// The registered endpoints.
    #[serde(default = "Vec::new")]
    pub webhooks: Vec<ConnectorWebhookEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One endpoint's outcome from
/// [`Connectors::sync_webhook_events`](crate::resources::connectors::Connectors::sync_webhook_events).
///
/// Carries no secret: syncing preserves the existing endpoint and its signing
/// secret rather than minting a new one, so `Debug` is derived.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookSyncResult {
    /// The connector's identifier for the endpoint.
    pub connector_webhook_id: String,

    /// Credential set the endpoint belongs to: `"live"` or `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// Callback URL the endpoint is registered to.
    #[serde(default)]
    pub webhook_url: Option<String>,
    /// Endpoint status as the connector reports it, e.g. `"enabled"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Whether the subscription was actually rewritten. `false` with an empty
    /// [`added_events`](Self::added_events) means it was already current.
    #[serde(default)]
    pub updated: bool,
    /// Events that were missing and have now been subscribed.
    #[serde(default = "Vec::new")]
    pub added_events: Vec<String>,
    /// Set when this endpoint could not be updated; the others are unaffected.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of bringing a connector's webhook subscriptions up to date.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookSyncResponse {
    /// Snake-case connector identifier the endpoints belong to.
    pub connector: String,
    /// The full event set Delopay expects to be subscribed to.
    #[serde(default = "Vec::new")]
    pub expected_events: Vec<String>,
    /// One entry per endpoint registered at this connector account, across
    /// every credential set whose endpoints could be listed. A failure on one
    /// endpoint never aborts the rest.
    #[serde(default = "Vec::new")]
    pub endpoints: Vec<ConnectorWebhookSyncResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Outcome of registering one URL as a Stripe payment method domain.
///
/// The status strings the API sends today are `"registered"`,
/// `"already_registered"`, `"invalid_url"` and `"failed"`; kept as a `String`
/// so a new one does not fail the whole response.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StripePaymentMethodDomainResult {
    /// The URL exactly as sent.
    pub url: String,

    /// Host actually registered with Stripe; absent when the URL failed to
    /// parse.
    #[serde(default)]
    pub domain: Option<String>,
    /// `"registered"`, `"already_registered"`, `"invalid_url"` or `"failed"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Stripe's `apple_pay.status` for the domain (`"active"`, `"inactive"`),
    /// when reported.
    #[serde(default)]
    pub apple_pay_status: Option<String>,
    /// Human-readable failure or duplicate detail. Never contains credentials.
    #[serde(default)]
    pub message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The per-URL outcomes of registering Stripe payment method domains.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StripePaymentMethodDomainsRegisterResponse {
    /// Credential set the domains were registered against: `"live"` or
    /// `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// One row per URL sent, in the order they were sent. Duplicates by
    /// resolved host are collapsed server-side but still get their own row.
    #[serde(default = "Vec::new")]
    pub results: Vec<StripePaymentMethodDomainResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    /// Credentials the API echoes back must not reach a log line. Mutation:
    /// print `&self.connector_account_details` instead of the redacted map —
    /// the first assertion goes red.
    #[test]
    fn connector_response_debug_redacts_credentials() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{
                "merchant_connector_id": "mca_1",
                "connector_name": "stripe",
                "connector_account_details": {"api_key": "sk_live_supersecret"},
                "connector_webhook_details": {"merchant_secret": "whsec_topsecret"}
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(
            rendered.contains("connector_account_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(
            rendered.contains("connector_webhook_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        // Non-secret fields still print, or the impl would be useless.
        assert!(rendered.contains("stripe"), "{rendered}");
        assert!(rendered.contains("mca_1"), "{rendered}");
    }

    /// An absent credential must be distinguishable from a present one.
    /// Mutation: `map(|_| REDACTED)` -> `map_or(Some(REDACTED), ...)`-style
    /// unconditional redaction makes this red.
    #[test]
    fn connector_response_debug_shows_none_for_absent_credentials() {
        let parsed: ConnectorResponse =
            serde_json::from_str(r#"{"merchant_connector_id":"mca_1"}"#).unwrap();
        let rendered = format!("{parsed:?}");
        assert!(
            rendered.contains("connector_account_details: None"),
            "{rendered}"
        );
    }

    /// Unknown fields land in `extra`, and known ones do not. Mutation:
    /// dropping `#[serde(flatten)]` from `extra` makes the lookup return
    /// `None`.
    #[test]
    fn connector_response_keeps_unknown_fields() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{"merchant_connector_id":"mca_1","status":"active","brand_new_field":42}"#,
        )
        .unwrap();
        assert_eq!(parsed.status.as_deref(), Some("active"));
        assert_eq!(parsed.extra.get("brand_new_field"), Some(&Value::from(42)));
        assert!(!parsed.extra.contains_key("status"));
    }

    /// The register response's minted signing secret must not print. Mutation:
    /// print `&self.webhook_secret` directly.
    #[test]
    fn register_response_debug_redacts_the_webhook_secret() {
        let parsed: ConnectorWebhookRegisterResponse = serde_json::from_str(
            r#"{
                "webhook_registration_status": "success",
                "event_type": "all_events",
                "environment": "sandbox",
                "connector_webhook_id": "we_1",
                "webhook_secret": "whsec_minted",
                "error_code": null,
                "error_message": null
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("whsec_minted"), "{rendered}");
        assert!(
            rendered.contains("webhook_secret: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(rendered.contains("we_1"), "{rendered}");
        assert_eq!(parsed.webhook_registration_status, "success");
        assert_eq!(parsed.environment.as_deref(), Some("sandbox"));
        assert_eq!(parsed.error_code, None);
    }

    /// A specific-event scope stays a structured value, and the list endpoint's
    /// entries deserialize. Mutation: typing `event_type` as `Option<String>`
    /// makes the object form fail to parse.
    #[test]
    fn webhook_list_parses_entries_and_structured_event_types() {
        let parsed: ConnectorWebhookListResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "webhooks": [
                    {
                        "connector_webhook_id": "we_1",
                        "event_type": {"specific_event": "payment_intent.succeeded"},
                        "enabled_events": ["payment_intent.succeeded"],
                        "created_at": 1700000000
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.connector, "stripe");
        assert_eq!(parsed.webhooks.len(), 1);
        let entry = &parsed.webhooks[0];
        assert_eq!(entry.connector_webhook_id, "we_1");
        assert_eq!(
            entry.event_type.as_ref().unwrap()["specific_event"],
            "payment_intent.succeeded"
        );
        assert_eq!(entry.created_at, Some(1_700_000_000));
        assert_eq!(entry.environment, None);
    }

    /// A response with no `webhooks` key must yield an empty list rather than
    /// failing. Mutation: drop `#[serde(default = "Vec::new")]`.
    #[test]
    fn webhook_list_defaults_to_no_webhooks() {
        let parsed: ConnectorWebhookListResponse =
            serde_json::from_str(r#"{"connector":"adyen"}"#).unwrap();
        assert!(parsed.webhooks.is_empty());
    }

    /// "Subscription is current" and "subscription was never inspected" are
    /// different answers and must stay distinguishable. Mutation: give
    /// `missing_events` a `#[serde(default = "Vec::new")]` and the absent case
    /// collapses into the empty one.
    #[test]
    fn webhook_entry_distinguishes_empty_from_absent_missing_events() {
        let parsed: ConnectorWebhookListResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "webhooks": [
                    {"connector_webhook_id": "we_current", "missing_events": []},
                    {"connector_webhook_id": "we_stale", "missing_events": ["refund.succeeded"]},
                    {"connector_webhook_id": "we_unknown"}
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.webhooks[0].missing_events.as_deref(), Some(&[][..]));
        assert_eq!(
            parsed.webhooks[1].missing_events.as_deref(),
            Some(&["refund.succeeded".to_string()][..])
        );
        assert_eq!(parsed.webhooks[2].missing_events, None);
    }

    /// A per-endpoint failure must parse alongside the endpoints that
    /// succeeded — the sync never aborts on one bad endpoint, so the response
    /// carries both shapes at once.
    #[test]
    fn webhook_sync_parses_mixed_endpoint_outcomes() {
        let parsed: ConnectorWebhookSyncResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "expected_events": ["payment_intent.succeeded", "refund.succeeded"],
                "endpoints": [
                    {
                        "connector_webhook_id": "we_1",
                        "environment": "live",
                        "webhook_url": "https://api.delopay.net/webhooks/mer_1/mca_1",
                        "status": "enabled",
                        "updated": true,
                        "added_events": ["refund.succeeded"]
                    },
                    {
                        "connector_webhook_id": "we_2",
                        "updated": false,
                        "added_events": [],
                        "error_message": "endpoint is disabled at Stripe"
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.expected_events.len(), 2);
        assert!(parsed.endpoints[0].updated);
        assert_eq!(parsed.endpoints[0].added_events, ["refund.succeeded"]);
        assert_eq!(parsed.endpoints[0].error_message, None);
        assert!(!parsed.endpoints[1].updated);
        assert!(parsed.endpoints[1].added_events.is_empty());
        assert_eq!(
            parsed.endpoints[1].error_message.as_deref(),
            Some("endpoint is disabled at Stripe")
        );
    }

    /// A URL that failed to parse has no `domain`, and that must survive
    /// deserialization rather than fail the whole response.
    #[test]
    fn stripe_domain_registration_parses_per_url_outcomes() {
        let parsed: StripePaymentMethodDomainsRegisterResponse = serde_json::from_str(
            r#"{
                "environment": "live",
                "results": [
                    {
                        "url": "https://checkout.delopay.net",
                        "domain": "checkout.delopay.net",
                        "status": "registered",
                        "apple_pay_status": "active"
                    },
                    {"url": "not a url", "status": "invalid_url", "message": "could not parse host"}
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.environment.as_deref(), Some("live"));
        assert_eq!(
            parsed.results[0].domain.as_deref(),
            Some("checkout.delopay.net")
        );
        assert_eq!(
            parsed.results[0].apple_pay_status.as_deref(),
            Some("active")
        );
        assert_eq!(parsed.results[1].domain, None);
        assert_eq!(parsed.results[1].status.as_deref(), Some("invalid_url"));
    }
}