delopay 0.2.1

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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
//! 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::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 payment methods, filtered by client secret and/or country.
    pub async fn list(
        &self,
        params: Option<&PaymentMethodListParams>,
    ) -> Result<Vec<PaymentMethodResponse>> {
        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<Vec<PaymentMethodResponse>> {
        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
    }

    /// Migrate a payment method from another processor (open request shape).
    pub async fn migrate(&self, params: &Value) -> Result<PaymentMethodResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/migrate",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Migrate payment methods in bulk (open request/response shapes).
    pub async fn migrate_batch(&self, params: &[Value]) -> Result<Value> {
        let body = to_json_vec(&params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/migrate-batch",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Update payment methods in bulk (open request/response shapes).
    pub async fn update_batch(&self, params: &[Value]) -> Result<Value> {
        let body = to_json_vec(&params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/update-batch",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Retrieve payment methods in bulk. Query keys are open — see the API
    /// reference.
    pub async fn batch_retrieve(
        &self,
        query: &[(&str, String)],
    ) -> Result<Vec<PaymentMethodResponse>> {
        self.inner
            .request(HttpMethod::Get, "/payment-methods/batch", None, query, None)
            .await
    }

    /// Tokenize a card (open request/response shapes).
    pub async fn tokenize_card(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/tokenize-card",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Tokenize cards in bulk (open request/response shapes).
    pub async fn tokenize_card_batch(&self, params: &[Value]) -> Result<Value> {
        let body = to_json_vec(&params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/tokenize-card-batch",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Start a collect-link flow that lets a customer submit payment details
    /// themselves (open request/response shapes).
    pub async fn collect(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/collect",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Save (persist) a payment method captured during a payment.
    pub async fn save(
        &self,
        method_id: &str,
        params: Option<&Value>,
    ) -> Result<PaymentMethodResponse> {
        let path = format!("/payment-methods/{}/save", encode_segment(method_id));
        let body: Option<Vec<u8>> = match params {
            Some(p) => Some(to_json_vec(p)?),
            None => None,
        };
        self.inner
            .request(HttpMethod::Post, &path, body.as_deref(), &[], None)
            .await
    }

    /// Create a payment-method auth link token (open request/response shapes).
    pub async fn create_auth_link(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/auth/link",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Exchange a payment-method auth token (open request/response shapes).
    pub async fn exchange_auth_token(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-methods/auth/exchange",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Tokenize a card using an existing payment method (open shapes).
    pub async fn tokenize_card_for_method(&self, method_id: &str, params: &Value) -> Result<Value> {
        let path = format!(
            "/payment-methods/{}/tokenize-card",
            encode_segment(method_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }
}

/// 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.
    pub country: Option<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()));
        }
        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"
    }"#;

    /// 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("[]")]);
        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("[]")]);
        let params = PaymentMethodListParams {
            client_secret: Some("cs_1".to_string()),
            country: Some("DE".to_string()),
        };
        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"
        );
    }

    #[tokio::test]
    async fn advanced_operations_hit_their_documented_paths() {
        let steps = vec![
            Step::ok(PM_JSON),
            Step::ok(r#"{"migrated":1}"#),
            Step::ok(r#"{"updated":1}"#),
            Step::ok("[]"),
            Step::ok(r#"{"token":"t"}"#),
            Step::ok(r#"{"tokens":[]}"#),
            Step::ok(r#"{"link":"l"}"#),
            Step::ok(PM_JSON),
            Step::ok(r#"{"link_token":"lt"}"#),
            Step::ok(r#"{"access_token":"at"}"#),
            Step::ok(r#"{"token":"t"}"#),
        ];
        let (client, mock) = client_with(steps);
        let pm = client.payment_methods();
        let body = json!({"k": "v"});
        let batch = [json!({"k": "v"})];

        pm.migrate(&body).await.unwrap();
        pm.migrate_batch(&batch).await.unwrap();
        pm.update_batch(&batch).await.unwrap();
        pm.batch_retrieve(&[("limit", "10".to_string())])
            .await
            .unwrap();
        pm.tokenize_card(&body).await.unwrap();
        pm.tokenize_card_batch(&batch).await.unwrap();
        pm.collect(&body).await.unwrap();
        pm.save("pm_1", None).await.unwrap();
        pm.create_auth_link(&body).await.unwrap();
        pm.exchange_auth_token(&body).await.unwrap();
        pm.tokenize_card_for_method("pm_1", &body).await.unwrap();

        let expected = [
            ("POST", "https://api.test/payment-methods/migrate"),
            ("POST", "https://api.test/payment-methods/migrate-batch"),
            ("POST", "https://api.test/payment-methods/update-batch"),
            ("GET", "https://api.test/payment-methods/batch?limit=10"),
            ("POST", "https://api.test/payment-methods/tokenize-card"),
            (
                "POST",
                "https://api.test/payment-methods/tokenize-card-batch",
            ),
            ("POST", "https://api.test/payment-methods/collect"),
            ("POST", "https://api.test/payment-methods/pm_1/save"),
            ("POST", "https://api.test/payment-methods/auth/link"),
            ("POST", "https://api.test/payment-methods/auth/exchange"),
            (
                "POST",
                "https://api.test/payment-methods/pm_1/tokenize-card",
            ),
        ];
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), expected.len());
        for (i, (method, url)) in expected.iter().enumerate() {
            assert_eq!(seen[i].method, *method, "wrong verb at call {i}");
            assert_eq!(seen[i].url, *url, "wrong URL at call {i}");
        }
    }

    #[tokio::test]
    async fn batch_bodies_serialize_as_json_arrays() {
        // `migrate_batch` and friends take a slice; the wire body must be a
        // JSON array, not an object wrapping one.
        let (client, mock) = client_with(vec![Step::ok(r#"{"ok":true}"#)]);
        let batch = [json!({"a": 1}), json!({"a": 2})];
        client
            .payment_methods()
            .migrate_batch(&batch)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert!(body.is_array(), "body must be a bare JSON array: {body}");
        assert_eq!(body[1]["a"], 2);
    }
}