delopay 0.20.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! The `payment_methods` 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::Address;
use crate::core::models::payment_method::{
    CustomerPaymentMethodsListResponse, PaymentMethodListResponse,
    PaymentMethodPresentationResponse, PaymentMethodResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Save a new payment method (card, bank account, wallet, …).
    pub async fn create(
        &self,
        params: &PaymentMethodCreateRequest,
    ) -> Result<PaymentMethodResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/payment-methods", Some(&body), &[], None)
            .await
    }

    /// Retrieve a saved payment method by ID.
    pub async fn retrieve(&self, method_id: &str) -> Result<PaymentMethodResponse> {
        let path = format!("/payment-methods/{}", encode_segment(method_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a saved payment method (e.g. refresh card expiry).
    pub async fn update(
        &self,
        method_id: &str,
        params: &PaymentMethodUpdateRequest,
    ) -> Result<PaymentMethodResponse> {
        params.validate()?;
        let path = format!("/payment-methods/{}/update", encode_segment(method_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a saved payment method.
    pub async fn delete(&self, method_id: &str) -> Result<Value> {
        let path = format!("/payment-methods/{}", encode_segment(method_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// List the payment methods available **for a payment** — the discovery
    /// endpoint a custom checkout renders its tiles from.
    ///
    /// Callable with a publishable key plus the payment's `client_secret`, so
    /// it runs from the browser. The returned set is already filtered by
    /// country, order value and the merchant's availability rules, and each
    /// entry carries
    /// [`display`](crate::core::models::payment_method::ResponsePaymentMethodTypes::display)
    /// (name + icon slug) and
    /// [`amount_limits`](crate::core::models::payment_method::ResponsePaymentMethodTypes::amount_limits)
    /// so neither has to be maintained alongside.
    ///
    /// This is **not** the customer's saved methods — see
    /// [`list_for_customer`](Self::list_for_customer).
    pub async fn list(
        &self,
        params: Option<&PaymentMethodListParams>,
    ) -> Result<PaymentMethodListResponse> {
        let query = params
            .map(PaymentMethodListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/payment-methods", None, &query, None)
            .await
    }

    /// List the saved payment methods for a customer, optionally filtered by
    /// what the current checkout accepts (countries, currencies, amount, …).
    pub async fn list_for_customer(
        &self,
        customer_id: &str,
        params: Option<&CustomerPaymentMethodsListParams>,
    ) -> Result<CustomerPaymentMethodsListResponse> {
        let path = format!("/customers/{}/payment-methods", encode_segment(customer_id));
        let query = params
            .map(CustomerPaymentMethodsListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Set a customer's default saved payment method.
    pub async fn set_default(
        &self,
        customer_id: &str,
        method_id: &str,
    ) -> Result<PaymentMethodResponse> {
        let path = format!(
            "/customers/{}/payment-methods/{}/default",
            encode_segment(customer_id),
            encode_segment(method_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// The shop's payment buttons as the hosted checkout draws them: order,
    /// labels in the shop's or caller's language, artwork, and what selecting
    /// each one does. For drawing payment buttons on your own site without a
    /// local table of provider names and icons.
    ///
    /// With a secret key, name the shop (`profile_id`) and optionally the
    /// environment and a buyer context; the answer may be reused for
    /// `cache.max_age_seconds`. With a publishable key, pass the payment's
    /// `client_secret`; that answer is never reused.
    ///
    /// A displayed entry is not a promise: the payment is confirmed against
    /// the current configuration.
    ///
    /// `GET /account/payment-methods/presentation`
    pub async fn presentation(
        &self,
        params: &PaymentMethodPresentationParams,
    ) -> Result<PaymentMethodPresentationResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/account/payment-methods/presentation",
                None,
                &params.to_query(),
                None,
            )
            .await
    }
}

/// Query parameters for [`PaymentMethods::presentation`].
///
/// `Debug` redacts `client_secret`.
#[derive(Clone, Default)]
pub struct PaymentMethodPresentationParams {
    /// The payment's client secret, for a publishable-key caller.
    pub client_secret: Option<String>,
    /// The shop, for a secret-key caller.
    pub profile_id: Option<String>,
    /// `"live"` (the default) or `"test"`. Secret key only.
    pub environment: Option<String>,
    /// The buyer's country (ISO 3166-1 alpha-2).
    pub country: Option<String>,
    /// ISO 4217 currency. Secret key only, together with `amount`.
    pub currency: Option<String>,
    /// Amount in minor units. Secret key only, together with `currency`.
    pub amount: Option<i64>,
    /// The contract the caller understands. Refused (422) when not served.
    pub contract_version: Option<u32>,
    /// Language of `label` and `sublabel`, as a BCP 47 tag.
    pub locale: Option<String>,
}

impl PaymentMethodPresentationParams {
    /// No parameters set.
    pub fn new() -> Self {
        Self::default()
    }

    /// The shop to answer for (secret key).
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// The payment to answer for (publishable key).
    #[must_use]
    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client_secret = Some(client_secret.into());
        self
    }

    /// `"live"` or `"test"`.
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }

    /// The buyer's country.
    #[must_use]
    pub fn country(mut self, country: impl Into<String>) -> Self {
        self.country = Some(country.into());
        self
    }

    /// The amount and its currency, in minor units.
    #[must_use]
    pub fn amount(mut self, amount: i64, currency: impl Into<String>) -> Self {
        self.amount = Some(amount);
        self.currency = Some(currency.into());
        self
    }

    /// The contract version the caller understands.
    #[must_use]
    pub fn contract_version(mut self, contract_version: u32) -> Self {
        self.contract_version = Some(contract_version);
        self
    }

    /// The language of the labels.
    #[must_use]
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.client_secret {
            q.push(("client_secret", v.clone()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = &self.environment {
            q.push(("environment", v.clone()));
        }
        if let Some(v) = &self.country {
            q.push(("country", v.clone()));
        }
        if let Some(v) = &self.currency {
            q.push(("currency", v.clone()));
        }
        if let Some(v) = self.amount {
            q.push(("amount", v.to_string()));
        }
        if let Some(v) = self.contract_version {
            q.push(("contract_version", v.to_string()));
        }
        if let Some(v) = &self.locale {
            q.push(("locale", v.clone()));
        }
        q
    }
}

impl std::fmt::Debug for PaymentMethodPresentationParams {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PaymentMethodPresentationParams")
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "<redacted>"),
            )
            .field("profile_id", &self.profile_id)
            .field("environment", &self.environment)
            .field("country", &self.country)
            .field("currency", &self.currency)
            .field("amount", &self.amount)
            .field("contract_version", &self.contract_version)
            .field("locale", &self.locale)
            .finish()
    }
}

/// Parameters for [`PaymentMethods::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentMethodCreateRequest {
    /// Payment method family, e.g. `"card"`.
    pub payment_method: String,
    /// Payment method sub-type, e.g. `"credit"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Issuer name, when relevant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_issuer: Option<String>,
    /// Card details (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card: Option<Value>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Customer to attach the method to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Card network, e.g. `"Visa"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_network: Option<String>,
    /// Bank transfer details (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bank_transfer: Option<Value>,
    /// Wallet details (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallet: Option<Value>,
    /// Client secret, for client-side creation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<String>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Any additional create fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `PaymentMethodCreateRequest`'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 PAYMENT_METHOD_CREATE_REQUEST_NAMED: &[&str] = &[
    "payment_method",
    "payment_method_type",
    "payment_method_issuer",
    "card",
    "metadata",
    "customer_id",
    "card_network",
    "bank_transfer",
    "wallet",
    "client_secret",
    "billing",
];

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

impl PaymentMethodCreateRequest {
    /// A new request for a method of the given family (e.g. `"card"`).
    pub fn new(payment_method: impl Into<String>) -> Self {
        Self {
            payment_method: payment_method.into(),
            ..Default::default()
        }
    }
}

/// Card fields updatable via [`PaymentMethods::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CardUpdate {
    /// New expiry month, e.g. `"09"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_exp_month: Option<String>,
    /// New expiry year, e.g. `"2030"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_exp_year: Option<String>,
    /// New cardholder name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_holder_name: Option<String>,
}

/// Parameters for [`PaymentMethods::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentMethodUpdateRequest {
    /// Card fields to update.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card: Option<CardUpdate>,
    /// Wallet details to update (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallet: Option<Value>,
    /// Client secret, for client-side updates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<String>,
    /// Any additional update fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `PaymentMethodUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const PAYMENT_METHOD_UPDATE_REQUEST_NAMED: &[&str] = &["card", "wallet", "client_secret"];

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

/// Filter parameters for [`PaymentMethods::list`].
#[derive(Debug, Clone, Default)]
pub struct PaymentMethodListParams {
    /// Client secret of the payment being checked out.
    pub client_secret: Option<String>,
    /// ISO 3166-1 alpha-2 country hint driving geo-aware availability. The
    /// highest-precedence country signal (explicit hint > billing > IP-geo), so
    /// the returned set reflects what a customer in that country would see.
    pub country: Option<String>,
    /// Order value in minor units. Filters out methods the connector does not
    /// accept at that amount and applies the merchant's own order-value rules —
    /// and drives the `amount_limits` each returned method carries.
    pub amount: Option<i64>,
    /// Only methods usable for recurring payments.
    pub recurring_enabled: Option<bool>,
    /// Only methods that support installments.
    pub installment_payment_enabled: Option<bool>,
    /// Maximum number of methods to return.
    pub limit: Option<i64>,
    /// Only card methods supporting all of these networks (repeated query key).
    pub card_networks: Option<Vec<String>>,
}

impl PaymentMethodListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.client_secret {
            q.push(("client_secret", v.clone()));
        }
        if let Some(v) = &self.country {
            q.push(("country", v.clone()));
        }
        if let Some(v) = self.amount {
            q.push(("amount", v.to_string()));
        }
        if let Some(v) = self.recurring_enabled {
            q.push(("recurring_enabled", v.to_string()));
        }
        if let Some(v) = self.installment_payment_enabled {
            q.push(("installment_payment_enabled", v.to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(values) = &self.card_networks {
            for v in values {
                q.push(("card_networks", v.clone()));
            }
        }
        q
    }
}

/// Filter parameters for [`PaymentMethods::list_for_customer`].
#[derive(Debug, Clone, Default)]
pub struct CustomerPaymentMethodsListParams {
    /// Client secret of the payment being checked out.
    pub client_secret: Option<String>,
    /// Only methods usable in these countries (repeated query key).
    pub accepted_countries: Option<Vec<String>>,
    /// Only methods usable in these currencies (repeated query key).
    pub accepted_currencies: Option<Vec<String>>,
    /// Amount the checkout will charge, in minor units.
    pub amount: Option<i64>,
    /// Only methods that support recurring charges.
    pub recurring_enabled: Option<bool>,
    /// Only methods that support installment payments.
    pub installment_payment_enabled: Option<bool>,
    /// Maximum number of methods to return.
    pub limit: Option<i64>,
    /// Only these card networks (repeated query key).
    pub card_networks: Option<Vec<String>>,
}

impl CustomerPaymentMethodsListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.client_secret {
            q.push(("client_secret", v.clone()));
        }
        // Array filters are emitted as repeated keys (`?k=a&k=b`), matching
        // the TS SDK's URLSearchParams behavior — not comma-joined.
        for v in self.accepted_countries.iter().flatten() {
            q.push(("accepted_countries", v.clone()));
        }
        for v in self.accepted_currencies.iter().flatten() {
            q.push(("accepted_currencies", v.clone()));
        }
        if let Some(v) = self.amount {
            q.push(("amount", v.to_string()));
        }
        if let Some(v) = self.recurring_enabled {
            q.push(("recurring_enabled", v.to_string()));
        }
        if let Some(v) = self.installment_payment_enabled {
            q.push(("installment_payment_enabled", v.to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        for v in self.card_networks.iter().flatten() {
            q.push(("card_networks", v.clone()));
        }
        q
    }
}

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

    const PM_JSON: &str = r#"{
        "merchant_id": "mer_1", "payment_method_id": "pm_1",
        "payment_method": "card"
    }"#;

    const PRESENTATION_JSON: &str = r#"{
        "contract_version": 1,
        "revision": "rev_1",
        "scope": "shop",
        "environment": "live",
        "locale": "de",
        "context": {"country": "DE", "currency": "EUR", "amount": 4999},
        "status": "ready",
        "layout_source": "stored",
        "cache": {"max_age_seconds": 300, "stale_if_error_seconds": 86400},
        "entries": [{
            "id": "ent_card",
            "kind": "card",
            "tier": "normal",
            "label": "Karte",
            "sublabel": "Visa, Mastercard",
            "label_source": "default",
            "sublabel_source": "merchant",
            "category": "card",
            "icon": {"type": "builtin", "key": "card"},
            "fallback_icon": "card",
            "payment_method": "card",
            "requires_device_support": false,
            "further_choice": "none",
            "children_detail": "known",
            "children": [{
                "id": "card_network:visa",
                "kind": "card_network",
                "label": "Visa",
                "icon": {"type": "svg", "data_uri": "data:image/svg+xml;base64,PHN2Zy8+", "sha256": "ab12", "source": "default"},
                "source": "account_configuration",
                "selection": "display_only"
            }],
            "children_status": "available",
            "children_stale": false,
            "children_narrowed": true,
            "action": {"type": "hosted_checkout"},
            "entry_surprise": 1
        }],
        "surprise_field": "kept"
    }"#;

    #[tokio::test]
    async fn presentation_gets_the_presentation_path_with_every_set_parameter() {
        let (client, mock) = client_with(vec![Step::ok(PRESENTATION_JSON)]);
        let params = PaymentMethodPresentationParams::new()
            .profile_id("pro_1")
            .environment("test")
            .country("DE")
            .amount(4999, "EUR")
            .contract_version(1)
            .locale("de");
        let out = client
            .payment_methods()
            .presentation(&params)
            .await
            .unwrap();
        assert_eq!(out.contract_version, 1);
        assert_eq!(out.context.amount, Some(4999));
        assert_eq!(out.cache.max_age_seconds, 300);
        let entry = &out.entries[0];
        assert_eq!(entry.kind, "card");
        assert_eq!(entry.sublabel.as_deref(), Some("Visa, Mastercard"));
        assert_eq!(entry.icon.as_ref().unwrap().kind, "builtin");
        assert_eq!(entry.icon.as_ref().unwrap().key.as_deref(), Some("card"));
        let child_icon = entry.children[0].icon.as_ref().unwrap();
        assert_eq!(child_icon.kind, "svg");
        assert_eq!(child_icon.sha256.as_deref(), Some("ab12"));
        assert_eq!(entry.action.as_ref().unwrap().kind, "hosted_checkout");
        assert!(entry.children_narrowed);
        assert!(entry.members.is_none());
        assert_eq!(entry.extra["entry_surprise"], 1);
        assert_eq!(out.extra["surprise_field"], "kept");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/payment-methods/presentation?profile_id=pro_1\
             &environment=test&country=DE&currency=EUR&amount=4999&contract_version=1&locale=de"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn presentation_for_a_payment_sends_only_the_client_secret() {
        let (client, mock) = client_with(vec![Step::ok(PRESENTATION_JSON)]);
        client
            .payment_methods()
            .presentation(&PaymentMethodPresentationParams::new().client_secret("pay_1_secret_x"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/account/payment-methods/presentation?client_secret=pay_1_secret_x"
        );
    }

    /// A derived `Debug` would print the client secret.
    #[test]
    fn presentation_params_debug_redacts_the_client_secret() {
        let params = PaymentMethodPresentationParams::new().client_secret("pay_1_secret_x");
        let printed = format!("{params:?}");
        assert!(!printed.contains("pay_1_secret_x"), "{printed}");
        assert!(printed.contains("<redacted>"));
    }

    /// Every optional field populated so serialization emits the full key set.
    fn full_create_request() -> PaymentMethodCreateRequest {
        PaymentMethodCreateRequest {
            payment_method: "card".to_string(),
            payment_method_type: Some("credit".to_string()),
            payment_method_issuer: Some("Big Bank".to_string()),
            card: Some(json!({"card_number": "4242424242424242"})),
            metadata: Some(json!({"k": "v"})),
            customer_id: Some("cus_1".to_string()),
            card_network: Some("Visa".to_string()),
            bank_transfer: Some(json!({"iban": "DE00"})),
            wallet: Some(json!({"type": "apple_pay"})),
            client_secret: Some("cs_1".to_string()),
            billing: Some(Address::default()),
            extra: serde_json::Map::new(),
        }
    }

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

    /// Every optional field populated so serialization emits the full key set.
    fn full_update_request() -> PaymentMethodUpdateRequest {
        PaymentMethodUpdateRequest {
            card: Some(CardUpdate {
                card_exp_month: Some("09".to_string()),
                card_exp_year: Some("2030".to_string()),
                card_holder_name: Some("Ada".to_string()),
            }),
            wallet: Some(json!({"type": "apple_pay"})),
            client_secret: Some("cs_1".to_string()),
            extra: serde_json::Map::new(),
        }
    }

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

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = PaymentMethodCreateRequest::new("card");
        req.extra.insert("customer_id".to_string(), json!("cus_2"));
        assert!(matches!(
            req.validate().unwrap_err(),
            crate::core::error::DelopayError::InvalidRequest(_)
        ));
    }

    #[tokio::test]
    async fn create_posts_to_payment_methods() {
        let (client, mock) = client_with(vec![Step::ok(PM_JSON)]);
        let req = PaymentMethodCreateRequest::new("card");
        client.payment_methods().create(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payment-methods");
        assert_eq!(seen[0].body_json()["payment_method"], "card");
    }

    #[tokio::test]
    async fn update_posts_to_the_update_path() {
        let (client, mock) = client_with(vec![Step::ok(PM_JSON)]);
        let req = full_update_request();
        client.payment_methods().update("pm_1", &req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payment-methods/pm_1/update");
        assert_eq!(seen[0].body_json()["card"]["card_exp_year"], "2030");
    }

    #[tokio::test]
    async fn list_for_customer_serializes_repeated_array_params() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"customer_payment_methods":[],"is_guest_customer":true}"#,
        )]);
        let params = CustomerPaymentMethodsListParams {
            accepted_currencies: Some(vec!["EUR".to_string(), "USD".to_string()]),
            amount: Some(5000),
            ..Default::default()
        };
        client
            .payment_methods()
            .list_for_customer("cus_1", Some(&params))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/cus_1/payment-methods\
             ?accepted_currencies=EUR&accepted_currencies=USD&amount=5000",
            "array filters must be repeated keys, not comma-joined"
        );
    }

    #[tokio::test]
    async fn list_filters_by_client_secret_and_country() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"payment_methods":[]}"#)]);
        let params = PaymentMethodListParams {
            client_secret: Some("cs_1".to_string()),
            country: Some("DE".to_string()),
            ..Default::default()
        };
        client.payment_methods().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-methods?client_secret=cs_1&country=DE"
        );
    }

    /// `amount` is the filter that matters most — it drives both the
    /// availability rules and the `amount_limits` each method comes back with.
    /// `card_networks` must go out as repeated keys, like every other array
    /// filter on this endpoint.
    #[tokio::test]
    async fn list_sends_the_order_value_and_capability_filters() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"payment_methods":[]}"#)]);
        let params = PaymentMethodListParams {
            amount: Some(25_000),
            recurring_enabled: Some(true),
            installment_payment_enabled: Some(false),
            limit: Some(20),
            card_networks: Some(vec!["Visa".to_string(), "Mastercard".to_string()]),
            ..Default::default()
        };
        client.payment_methods().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-methods\
             ?amount=25000&recurring_enabled=true&installment_payment_enabled=false\
             &limit=20&card_networks=Visa&card_networks=Mastercard"
        );
    }
}