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
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Buyer-side clients for a single hosted-checkout payment.
//!
//! These are the calls a checkout page makes on the shopper's behalf. They
//! authenticate with the two browser-safe credentials — the payment's
//! [`ClientSecret`] and the merchant's [`PublishableKey`] — and there is no
//! way to hand either client a [`crate::credentials::SecretKey`]: the
//! constructors do not accept one, so putting a secret key on a checkout page
//! is a compile error rather than an incident.
//!
//! Two types, because the two credentials unlock different routes:
//!
//! - [`PaymentLinkSession`] needs only the client secret. It covers the
//!   `/payment-link/{merchant}/{payment}/*` side channel — rail catalogs, the
//!   vault handshake, checkout telemetry — which authenticates with
//!   `Authorization: Bearer <client_secret>`.
//! - [`CheckoutSession`] adds the publishable key and, with it, the
//!   `/payments/*` and `/payment-methods` routes that actually read and
//!   confirm the payment. It exposes every [`PaymentLinkSession`] call too,
//!   so a page holding both credentials only needs this one.
//!
//! Splitting them is what removes the runtime "missing credential" error the
//! other SDKs have to raise: a call you cannot authenticate does not exist on
//! the type you built.
//!
//! # Credential isolation
//!
//! Each route carries **exactly one** credential. The bearer routes go
//! through a client with no API key at all — not one whose key is merely
//! unused — so a `/payment-link/*` request cannot pick up the publishable key
//! by accident, and the client secret never travels as an `api-key`.
//!
//! ```no_run
//! # use delopay::{CheckoutSession, PublishableKey};
//! # async fn run() -> delopay::Result<()> {
//! let session = CheckoutSession::new(
//!     "mer_123",
//!     "pay_456",
//!     PublishableKey::new("pk_snd_abc")?,
//!     "pay_456_secret_xyz",
//! );
//! let catalog = session.paysepro_methods("de").await?;
//! let payment = session.retrieve_payment().await?;
//! # let _ = (catalog, payment);
//! # Ok(())
//! # }
//! ```

use std::sync::Arc;

use serde::Serialize;

use crate::core::credentials::{ClientSecret, PublishableKey};
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::checkout::{
    EpayoutsMethodsResponse, PayseproMethodsResponse, RecordCheckoutEventResponse,
    VaultCollectSessionResponse, VaultPaymentMethodResponse,
};
use crate::core::models::payment::PaymentResponse;
use crate::core::models::payment_method::PaymentMethodListResponse;
use crate::http::client::{ClientParts, DelopayBuilder, Inner};
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::payments::{PaymentConfirmRequest, PaymentUpdateRequest};

/// Options shared by both buyer-side clients: which environment to talk to,
/// and the usual transport knobs.
#[derive(Debug, Clone, Default)]
pub struct CheckoutSessionOptions {
    /// Override the API base URL, e.g. `/api` behind a same-origin proxy.
    pub base_url: Option<String>,
    /// Use the sandbox environment. Ignored when `base_url` is set.
    pub sandbox: bool,
    /// Per-request timeout.
    pub timeout: Option<std::time::Duration>,
    /// Maximum automatic retries for retriable requests.
    pub max_retries: Option<u32>,
}

impl CheckoutSessionOptions {
    /// Production defaults.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Talk to the sandbox environment.
    #[must_use]
    pub fn sandbox(mut self, sandbox: bool) -> Self {
        self.sandbox = sandbox;
        self
    }

    /// Send requests to this base URL instead of the environment default.
    #[must_use]
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Per-request timeout.
    #[must_use]
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Maximum automatic retries.
    #[must_use]
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    /// The transport and shared configuration these options describe.
    ///
    /// Built once and reused by both `Inner`s of a [`CheckoutSession`], so
    /// the two credentials share one connection pool.
    fn into_parts(self) -> ClientParts {
        // The builder wants a secret key; this one is deliberately empty and
        // is never installed on an `Inner` — the buyer-side clients supply
        // their own credential per half. Everything else (proxy resolution,
        // timeouts, base URL defaulting) is the builder's, not re-implemented.
        let mut builder = DelopayBuilder::for_checkout_session();
        if let Some(base_url) = self.base_url {
            builder = builder.base_url(base_url);
        }
        builder = builder.sandbox(self.sandbox);
        if let Some(timeout) = self.timeout {
            builder = builder.timeout(timeout);
        }
        if let Some(max_retries) = self.max_retries {
            builder = builder.max_retries(max_retries);
        }
        builder.into_parts()
    }
}

/// The client-secret half of a checkout: the `/payment-link/*` side channel.
///
/// Holds no API key at all — every call authenticates with
/// `Authorization: Bearer <client_secret>`.
#[derive(Debug, Clone)]
pub struct PaymentLinkSession {
    inner: Arc<Inner>,
    link_base: String,
    client_secret: ClientSecret,
}

impl PaymentLinkSession {
    /// A session for one payment, authenticated by its client secret.
    pub fn new(
        merchant_id: &str,
        payment_id: &str,
        client_secret: impl Into<ClientSecret>,
    ) -> Self {
        Self::with_options(
            merchant_id,
            payment_id,
            client_secret,
            CheckoutSessionOptions::new(),
        )
    }

    /// [`new`](Self::new) with non-default transport options.
    pub fn with_options(
        merchant_id: &str,
        payment_id: &str,
        client_secret: impl Into<ClientSecret>,
        options: CheckoutSessionOptions,
    ) -> Self {
        Self::from_parts(
            &options.into_parts(),
            merchant_id,
            payment_id,
            client_secret.into(),
        )
    }

    fn from_parts(
        parts: &ClientParts,
        merchant_id: &str,
        payment_id: &str,
        client_secret: ClientSecret,
    ) -> Self {
        Self {
            // Empty key: this half must never present an `api-key`.
            inner: Arc::new(parts.inner_with_key(String::new())),
            link_base: format!(
                "/payment-link/{}/{}",
                encode_segment(merchant_id),
                encode_segment(payment_id)
            ),
            client_secret,
        }
    }

    /// The `Authorization: Bearer <client_secret>` header these routes take.
    fn bearer(&self) -> String {
        format!("Bearer {}", self.client_secret.as_str())
    }

    async fn send<T: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
    ) -> Result<T> {
        let authorization = self.bearer();
        self.inner
            .request_with_headers(
                method,
                path,
                body,
                query,
                None,
                &[("authorization", authorization.as_str())],
            )
            .await
    }

    /// The Paysepro rail catalog for the buyer's country.
    ///
    /// `country` is a lowercase ISO 3166-1 alpha-2 code.
    ///
    /// `GET /payment-link/{merchant_id}/{payment_id}/paysepro/methods`
    pub async fn paysepro_methods(&self, country: &str) -> Result<PayseproMethodsResponse> {
        let path = format!("{}/paysepro/methods", self.link_base);
        self.send(HttpMethod::Get, &path, None, &[("cc", country.to_string())])
            .await
    }

    /// The e-Payouts rail catalog for the buyer's country, plus every country
    /// the catalog can mint a method for.
    ///
    /// `GET /payment-link/{merchant_id}/{payment_id}/epayouts/methods`
    pub async fn epayouts_methods(&self, country: &str) -> Result<EpayoutsMethodsResponse> {
        let path = format!("{}/epayouts/methods", self.link_base);
        self.send(HttpMethod::Get, &path, None, &[("cc", country.to_string())])
            .await
    }

    /// Record a buyer-side checkout event on the payment's status timeline.
    ///
    /// Telemetry, so this **cannot fail the checkout**: a transport or server
    /// error resolves to `None` rather than an error, because a dropped
    /// analytics event must never become an error the buyer sees. `None` also
    /// covers a deduplicated event — the two are not distinguished, on
    /// purpose, since neither is actionable.
    ///
    /// `POST /payment-link/{merchant_id}/{payment_id}/checkout-events`
    pub async fn record_event(
        &self,
        event: &str,
        method: &str,
    ) -> Option<RecordCheckoutEventResponse> {
        let body = to_json_vec(&RecordCheckoutEventRequest { event, method }).ok()?;
        let path = format!("{}/checkout-events", self.link_base);
        self.send(HttpMethod::Post, &path, Some(&body), &[])
            .await
            .ok()
    }

    /// A short-lived VGS Collect session for browser-side card capture.
    ///
    /// A 404 — or a 400 carrying the "shop has no vault" code — means the
    /// shop has no vault configured. Any **other** error must not be read
    /// that way: falling back to an unprotected card pane because the vault
    /// refused is exactly what this endpoint's error contract exists to stop.
    ///
    /// `GET /payment-link/{merchant_id}/{payment_id}/vault/collect-session`
    pub async fn vault_collect_session(&self) -> Result<VaultCollectSessionResponse> {
        let path = format!("{}/vault/collect-session", self.link_base);
        self.send(HttpMethod::Get, &path, None, &[]).await
    }

    /// Register an aliased card as a payment method and mint the one-shot
    /// `payment_token` the confirm call spends.
    ///
    /// `POST /payment-link/{merchant_id}/{payment_id}/vault/payment-method`
    pub async fn register_vault_payment_method(
        &self,
        params: &VaultPaymentMethodRequest,
    ) -> Result<VaultPaymentMethodResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/vault/payment-method", self.link_base);
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }
}

/// Buyer-side client for a single hosted-checkout payment, holding both
/// browser-safe credentials — the merchant's [`PublishableKey`] and the
/// payment's [`ClientSecret`].
///
/// Adds the publishable-key routes — read, update and confirm the payment,
/// list its payment methods — on top of every [`PaymentLinkSession`] call.
///
/// A [`crate::SecretKey`] cannot reach a checkout page through this type: the
/// constructors do not accept one, so the mistake is a compile error rather
/// than an incident.
///
/// Each route carries **exactly one** credential. The `/payment-link/*` half
/// runs on a client with no API key at all — not one whose key is merely
/// unused — so those requests cannot pick up the publishable key by
/// accident, and the client secret never travels as an `api-key`. Both
/// halves share one connection pool.
///
/// ```no_run
/// # use delopay::{CheckoutSession, PublishableKey};
/// # async fn run() -> delopay::Result<()> {
/// let session = CheckoutSession::new(
///     "mer_123",
///     "pay_456",
///     PublishableKey::new("pk_snd_abc")?,
///     "pay_456_secret_xyz",
/// );
/// let catalog = session.paysepro_methods("de").await?;
/// let payment = session.retrieve_payment().await?;
/// # let _ = (catalog, payment);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct CheckoutSession {
    link: PaymentLinkSession,
    /// Authenticates with the publishable key in the `api-key` header.
    pk_inner: Arc<Inner>,
    payment_path: String,
    client_secret: ClientSecret,
}

impl CheckoutSession {
    /// A session for one payment, holding the merchant's publishable key and
    /// the payment's client secret.
    ///
    /// Both come from the checkout payload (`pub_key` and `client_secret`).
    pub fn new(
        merchant_id: &str,
        payment_id: &str,
        publishable_key: PublishableKey,
        client_secret: impl Into<ClientSecret>,
    ) -> Self {
        Self::with_options(
            merchant_id,
            payment_id,
            publishable_key,
            client_secret,
            CheckoutSessionOptions::new(),
        )
    }

    /// [`new`](Self::new) with non-default transport options.
    pub fn with_options(
        merchant_id: &str,
        payment_id: &str,
        publishable_key: PublishableKey,
        client_secret: impl Into<ClientSecret>,
        options: CheckoutSessionOptions,
    ) -> Self {
        let parts = options.into_parts();
        let client_secret = client_secret.into();
        Self {
            link: PaymentLinkSession::from_parts(
                &parts,
                merchant_id,
                payment_id,
                client_secret.clone(),
            ),
            pk_inner: Arc::new(parts.inner_with_key(publishable_key.into_string())),
            payment_path: format!("/payments/{}", encode_segment(payment_id)),
            client_secret,
        }
    }

    /// The client-secret half, for the `/payment-link/*` calls. Every one of
    /// them is also available directly on this type.
    #[must_use]
    pub fn payment_link(&self) -> &PaymentLinkSession {
        &self.link
    }

    /// The payment's current state — status polling for redirect and popup
    /// rails.
    ///
    /// `GET /payments/{payment_id}`
    pub async fn retrieve_payment(&self) -> Result<PaymentResponse> {
        self.pk_inner
            .request(
                HttpMethod::Get,
                &self.payment_path,
                None,
                &[("client_secret", self.client_secret.as_str().to_string())],
                None,
            )
            .await
    }

    /// Update the payment before confirmation — persisting custom-field
    /// answers as `metadata`, for instance, on rails that never reach
    /// `/confirm`.
    ///
    /// The client secret is attached to the body automatically.
    ///
    /// `POST /payments/{payment_id}`
    pub async fn update_payment(&self, params: &PaymentUpdateRequest) -> Result<PaymentResponse> {
        let body = self.body_with_client_secret(params)?;
        self.pk_inner
            .request(HttpMethod::Post, &self.payment_path, Some(&body), &[], None)
            .await
    }

    /// Confirm the payment.
    ///
    /// The client secret is attached to the body automatically. Pass an
    /// idempotency key through [`confirm_payment_idempotent`] to make a retry
    /// safe — a bare confirm is deliberately **not** retried on a network
    /// error, since the server may already have charged the card.
    ///
    /// `POST /payments/{payment_id}/confirm`
    ///
    /// [`confirm_payment_idempotent`]: Self::confirm_payment_idempotent
    pub async fn confirm_payment(&self, params: &PaymentConfirmRequest) -> Result<PaymentResponse> {
        self.confirm_with_key(params, None).await
    }

    /// [`confirm_payment`](Self::confirm_payment) carrying an
    /// `Idempotency-Key`, so a retry cannot double-charge.
    pub async fn confirm_payment_idempotent(
        &self,
        params: &PaymentConfirmRequest,
        idempotency_key: &str,
    ) -> Result<PaymentResponse> {
        self.confirm_with_key(params, Some(idempotency_key)).await
    }

    async fn confirm_with_key(
        &self,
        params: &PaymentConfirmRequest,
        idempotency_key: Option<&str>,
    ) -> Result<PaymentResponse> {
        let body = self.body_with_client_secret(params)?;
        let path = format!("{}/confirm", self.payment_path);
        self.pk_inner
            .request(HttpMethod::Post, &path, Some(&body), &[], idempotency_key)
            .await
    }

    /// The payment methods available for this payment.
    ///
    /// `country` is the highest-precedence geo hint, ahead of the billing
    /// address and IP geolocation.
    ///
    /// `GET /payment-methods`
    pub async fn list_payment_methods(
        &self,
        country: Option<&str>,
    ) -> Result<PaymentMethodListResponse> {
        let mut query = vec![("client_secret", self.client_secret.as_str().to_string())];
        if let Some(country) = country {
            query.push(("country", country.to_string()));
        }
        self.pk_inner
            .request(HttpMethod::Get, "/payment-methods", None, &query, None)
            .await
    }

    /// Validate `params`, serialize it, and merge the session's client secret
    /// into the resulting JSON object.
    ///
    /// The [`ValidateRequest`] bound is the point of putting the check here
    /// rather than at each call site: it is the same guard the secret-key
    /// paths run before serializing, and having it in one place means a
    /// future checkout route cannot forget it. Without it, an `extra` key
    /// colliding with a named field ships a JSON object with a literal
    /// duplicate key, which the server may resolve either way.
    ///
    /// The merge is done on the serialized value rather than by adding a
    /// field to the request structs: those are shared with the secret-key
    /// surface, where a client secret has no business being.
    ///
    /// The session's secret **overwrites** a `client_secret` the caller set
    /// on the request. A session is bound to one payment, so a second secret
    /// in the body is either the same value or a mistake, and sending the
    /// caller's would authenticate against a payment this session is not for.
    fn body_with_client_secret<T: Serialize + ValidateRequest>(
        &self,
        params: &T,
    ) -> Result<Vec<u8>> {
        params.validate()?;
        let mut value = serde_json::to_value(params)
            .map_err(|e| crate::core::error::DelopayError::Decode(e.to_string()))?;
        match value.as_object_mut() {
            Some(map) => {
                map.insert(
                    "client_secret".to_string(),
                    serde_json::Value::String(self.client_secret.as_str().to_string()),
                );
            }
            // Unreachable for the request structs this is called with, which
            // are all structs; erroring beats silently sending a body the
            // server would reject as unauthenticated.
            None => {
                return Err(crate::core::error::DelopayError::InvalidRequest(
                    "checkout request body must serialize to a JSON object".to_string(),
                ));
            }
        }
        to_json_vec(&value)
    }

    // --- `/payment-link/*` calls, delegated to the client-secret half ---

    /// See [`PaymentLinkSession::paysepro_methods`].
    pub async fn paysepro_methods(&self, country: &str) -> Result<PayseproMethodsResponse> {
        self.link.paysepro_methods(country).await
    }

    /// See [`PaymentLinkSession::epayouts_methods`].
    pub async fn epayouts_methods(&self, country: &str) -> Result<EpayoutsMethodsResponse> {
        self.link.epayouts_methods(country).await
    }

    /// See [`PaymentLinkSession::record_event`].
    pub async fn record_event(
        &self,
        event: &str,
        method: &str,
    ) -> Option<RecordCheckoutEventResponse> {
        self.link.record_event(event, method).await
    }

    /// See [`PaymentLinkSession::vault_collect_session`].
    pub async fn vault_collect_session(&self) -> Result<VaultCollectSessionResponse> {
        self.link.vault_collect_session().await
    }

    /// See [`PaymentLinkSession::register_vault_payment_method`].
    pub async fn register_vault_payment_method(
        &self,
        params: &VaultPaymentMethodRequest,
    ) -> Result<VaultPaymentMethodResponse> {
        self.link.register_vault_payment_method(params).await
    }
}

/// Body of [`PaymentLinkSession::record_event`].
#[derive(Debug, Serialize)]
struct RecordCheckoutEventRequest<'a> {
    event: &'a str,
    method: &'a str,
}

/// Body for [`PaymentLinkSession::register_vault_payment_method`].
///
/// The expiry travels in the clear by necessity: VGS never hands raw values
/// back, so only the card *number* exists as an alias.
#[derive(Debug, Clone, Serialize)]
pub struct VaultPaymentMethodRequest {
    /// The card-number alias from `createAliases` (must be card-shaped).
    pub card_number_alias: String,
    /// Expiry month, two digits.
    pub card_exp_month: String,
    /// Expiry year.
    pub card_exp_year: String,
    /// Name on the card.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_holder_name: Option<String>,
    /// Buyer-chosen nickname for the saved card.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nick_name: Option<String>,
    /// Card network, when the page already knows it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_network: Option<String>,
}

impl VaultPaymentMethodRequest {
    /// The three fields the vault always needs.
    #[must_use]
    pub fn new(
        card_number_alias: impl Into<String>,
        card_exp_month: impl Into<String>,
        card_exp_year: impl Into<String>,
    ) -> Self {
        Self {
            card_number_alias: card_number_alias.into(),
            card_exp_month: card_exp_month.into(),
            card_exp_year: card_exp_year.into(),
            card_holder_name: None,
            nick_name: None,
            card_network: None,
        }
    }

    /// Set the name on the card.
    #[must_use]
    pub fn card_holder_name(mut self, name: impl Into<String>) -> Self {
        self.card_holder_name = Some(name.into());
        self
    }

    /// Set the buyer-chosen nickname.
    #[must_use]
    pub fn nick_name(mut self, nick_name: impl Into<String>) -> Self {
        self.nick_name = Some(nick_name.into());
        self
    }

    /// Set the card network.
    #[must_use]
    pub fn card_network(mut self, card_network: impl Into<String>) -> Self {
        self.card_network = Some(card_network.into());
        self
    }
}

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

    const PAYMENT_JSON: &str = r#"{
        "payment_id": "pay_456", "merchant_id": "mer_123", "status": "requires_confirmation",
        "amount": 1999, "currency": "EUR"
    }"#;

    /// A `CheckoutSession` over a scripted mock, plus the mock. Mirrors
    /// `mock::client_with`, but builds the two `Inner`s the session needs
    /// over *one* transport, so header assertions see every call.
    fn session_with(steps: Vec<Step>) -> (CheckoutSession, Arc<MockTransport>) {
        let mock = Arc::new(MockTransport::new(steps));
        let parts = ClientParts::for_test(mock.clone(), "https://api.test");
        let client_secret = ClientSecret::new("pay_456_secret_xyz");
        let session = CheckoutSession {
            link: PaymentLinkSession::from_parts(
                &parts,
                "mer_123",
                "pay_456",
                client_secret.clone(),
            ),
            pk_inner: Arc::new(parts.inner_with_key("pk_snd_abc".to_string())),
            payment_path: "/payments/pay_456".to_string(),
            client_secret,
        };
        (session, mock)
    }

    #[tokio::test]
    async fn link_routes_send_a_bearer_and_no_api_key() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"country":"de","currency":"EUR","methods":[]}"#,
        )]);
        session.paysepro_methods("de").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer_123/pay_456/paysepro/methods?cc=de"
        );
        assert_eq!(
            seen[0].header("authorization"),
            Some("Bearer pay_456_secret_xyz")
        );
        // The isolation guarantee: this route must not also present the
        // publishable key. An `Inner` that sent an empty `api-key` header
        // would fail here too.
        assert_eq!(seen[0].header("api-key"), None);
    }

    #[tokio::test]
    async fn publishable_key_routes_send_the_key_and_no_bearer() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        session.retrieve_payment().await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payments/pay_456?client_secret=pay_456_secret_xyz"
        );
        assert_eq!(seen[0].header("api-key"), Some("pk_snd_abc"));
        // The client secret rides as a parameter here, never as a bearer —
        // and never as the api-key.
        assert_eq!(seen[0].header("authorization"), None);
    }

    #[tokio::test]
    async fn confirm_merges_the_client_secret_into_the_body() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        let params = PaymentConfirmRequest {
            payment_method: Some("card".to_string()),
            ..Default::default()
        };
        session.confirm_payment(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payments/pay_456/confirm");
        let body = seen[0].body_json();
        assert_eq!(body["client_secret"], "pay_456_secret_xyz");
        // The caller's own fields survive the merge.
        assert_eq!(body["payment_method"], "card");
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn the_idempotent_confirm_sends_a_key() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        let params = PaymentConfirmRequest {
            payment_method: Some("card".to_string()),
            ..Default::default()
        };
        session
            .confirm_payment_idempotent(&params, "confirm-pay_456")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("idempotency-key"), Some("confirm-pay_456"));
    }

    #[tokio::test]
    async fn update_payment_carries_the_client_secret_too() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        // `metadata` is a named field, so it goes in the field — putting it
        // in `extra` is exactly what the collision guard now rejects, and
        // there is a test below for that.
        let params = PaymentUpdateRequest {
            metadata: Some(serde_json::json!({"gift": "yes"})),
            ..Default::default()
        };
        session.update_payment(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payments/pay_456");
        let body = seen[0].body_json();
        assert_eq!(body["client_secret"], "pay_456_secret_xyz");
        assert_eq!(body["metadata"]["gift"], "yes");
    }

    #[tokio::test]
    async fn the_checkout_paths_run_the_extra_key_collision_guard() {
        // A colliding `extra` key would otherwise serialize a JSON object
        // with a literal duplicate key, which the server may resolve either
        // way. The secret-key paths reject it; these must too.
        let (session, mock) = session_with(vec![]);

        let mut confirm = PaymentConfirmRequest::default();
        confirm
            .extra
            .insert("payment_method".to_string(), serde_json::json!("card"));
        match session.confirm_payment(&confirm).await.unwrap_err() {
            crate::DelopayError::InvalidRequest(msg) => {
                assert!(msg.contains("payment_method"), "{msg}");
            }
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut update = PaymentUpdateRequest::default();
        update
            .extra
            .insert("amount".to_string(), serde_json::json!(1));
        match session.update_payment(&update).await.unwrap_err() {
            crate::DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount"), "{msg}"),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        // Both rejected before the wire, so the empty script is never hit.
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn list_payment_methods_sends_the_secret_and_an_optional_country() {
        let (session, mock) = session_with(vec![
            Step::ok(r#"{"payment_methods":[]}"#),
            Step::ok(r#"{"payment_methods":[]}"#),
        ]);
        session.list_payment_methods(None).await.unwrap();
        session.list_payment_methods(Some("de")).await.unwrap();

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

    #[tokio::test]
    async fn record_event_swallows_a_server_error() {
        let (session, mock) = session_with(vec![Step::status(500, "boom")]);
        // Telemetry must not surface as an error the checkout has to handle.
        assert!(
            session
                .record_event("native_pane_selected", "apple_pay")
                .await
                .is_none()
        );
        // It was genuinely attempted — a version that returned `None` without
        // sending anything would pass a weaker assertion.
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn record_event_returns_the_receipt_on_success() {
        let (session, mock) = session_with(vec![Step::ok(r#"{"recorded":true}"#)]);
        let receipt = session
            .record_event("native_pane_tab_opened", "klarna")
            .await
            .unwrap();
        assert!(receipt.recorded);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer_123/pay_456/checkout-events"
        );
        let body = seen[0].body_json();
        assert_eq!(body["event"], "native_pane_tab_opened");
        assert_eq!(body["method"], "klarna");
    }

    #[tokio::test]
    async fn the_vault_handshake_posts_only_the_set_fields() {
        let (session, mock) = session_with(vec![
            Step::ok(
                r#"{"vault_id":"tnt_1","environment":"sandbox","access_token":"tok",
                    "expires_in":900}"#,
            ),
            Step::ok(r#"{"last4":"4242","payment_token":"pt_1"}"#),
        ]);
        session.vault_collect_session().await.unwrap();
        session
            .register_vault_payment_method(&VaultPaymentMethodRequest::new("alias_1", "12", "2030"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer_123/pay_456/vault/collect-session"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/payment-link/mer_123/pay_456/vault/payment-method"
        );
        let body = seen[1].body_json();
        assert_eq!(body["card_number_alias"], "alias_1");
        assert!(body.get("nick_name").is_none());
    }

    #[tokio::test]
    async fn the_link_base_percent_encodes_both_ids() {
        let mock = Arc::new(MockTransport::new(vec![Step::ok(
            r#"{"country":"de","currency":"EUR","methods":[],"supported_countries":[]}"#,
        )]));
        let parts = ClientParts::for_test(mock.clone(), "https://api.test");
        let link =
            PaymentLinkSession::from_parts(&parts, "mer/1", "pay/2", ClientSecret::new("cs"));
        link.epayouts_methods("de").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer%2F1/pay%2F2/epayouts/methods?cc=de"
        );
    }
}