delopay 0.3.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
//! The `connectors` resource: merchant connector accounts, the per-shop
//! bindings between a merchant account and an upstream payment processor.

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::connector::{
    ConnectorResponse, ConnectorWebhookListResponse, ConnectorWebhookRegisterResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Create a connector under a merchant account.
    /// `POST /account/{account_id}/connectors`
    pub async fn create(
        &self,
        account_id: &str,
        params: &ConnectorCreateRequest,
    ) -> Result<ConnectorResponse> {
        params.validate()?;
        let path = format!("/account/{}/connectors", encode_segment(account_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Retrieve one connector.
    /// `GET /account/{account_id}/connectors/{connector_id}`
    pub async fn retrieve(
        &self,
        account_id: &str,
        connector_id: &str,
    ) -> Result<ConnectorResponse> {
        let path = format!(
            "/account/{}/connectors/{}",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List a merchant account's connectors.
    /// `GET /account/{account_id}/connectors`
    pub async fn list(&self, account_id: &str) -> Result<Vec<ConnectorResponse>> {
        let path = format!("/account/{}/connectors", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a connector.
    /// `POST /account/{account_id}/connectors/{connector_id}`
    pub async fn update(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &ConnectorUpdateRequest,
    ) -> Result<ConnectorResponse> {
        params.validate()?;
        let path = format!(
            "/account/{}/connectors/{}",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a connector.
    /// `DELETE /account/{account_id}/connectors/{connector_id}`
    pub async fn delete(&self, account_id: &str, connector_id: &str) -> Result<ConnectorResponse> {
        let path = format!(
            "/account/{}/connectors/{}",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// Clone a connector into another shop (business profile) of the same
    /// merchant. `POST /account/{account_id}/connectors/{connector_id}/clone`
    ///
    /// Credentials are copied server-side, re-encrypted under the same merchant
    /// key — the caller never handles them (list/retrieve mask credentials, so a
    /// client-side copy is impossible). Returns the newly created connector in
    /// the target shop.
    ///
    /// Named `clone_connector`, not `clone`: an inherent `clone` taking three
    /// arguments would shadow [`Clone::clone`] and make `connectors.clone()`
    /// fail to compile.
    pub async fn clone_connector(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &ConnectorCloneRequest,
    ) -> Result<ConnectorResponse> {
        let path = format!(
            "/account/{}/connectors/{}/clone",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Verify connector credentials. `POST /account/connectors/verify`
    ///
    /// Open body shape — see the API reference.
    pub async fn verify(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/account/connectors/verify",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Register a webhook for a connector.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}`
    ///
    /// Pass `None` to send no body, which the server treats as
    /// `{ "event_type": "all_events" }`; pass
    /// [`ConnectorWebhookRegisterRequest::specific_event`] to scope the
    /// registration to a single event.
    pub async fn register_webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: Option<&ConnectorWebhookRegisterRequest>,
    ) -> Result<ConnectorWebhookRegisterResponse> {
        let path = format!(
            "/account/{}/connectors/webhooks/{}",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        match params {
            // The TypeScript SDK omits the body entirely when no params are
            // given; the server's default only applies to a bodyless call.
            None => {
                self.inner
                    .request(HttpMethod::Post, &path, None, &[], None)
                    .await
            }
            Some(p) => {
                let body = to_json_vec(p)?;
                self.inner
                    .request(HttpMethod::Post, &path, Some(&body), &[], None)
                    .await
            }
        }
    }

    /// Get the webhooks registered for a connector.
    /// `GET /account/{merchant_id}/connectors/webhooks/{connector_id}`
    pub async fn webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
    ) -> Result<ConnectorWebhookListResponse> {
        let path = format!(
            "/account/{}/connectors/webhooks/{}",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List the payment methods the platform supports.
    /// `GET /account/payment-methods`
    pub async fn list_payment_methods(&self) -> Result<Vec<Value>> {
        self.inner
            .request(HttpMethod::Get, "/account/payment-methods", None, &[], None)
            .await
    }
}

/// Parameters for [`Connectors::create`].
///
/// `Debug` is hand-written: `connector_account_details`,
/// `connector_webhook_details` and `additional_merchant_data` carry live
/// gateway credentials (API keys, signing secrets, acquirer merchant data), so
/// a derived `Debug` would leak them into logs. They print as
/// `Some("[redacted]")`.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorCreateRequest {
    /// Connector category, e.g. `"payment_processor"` or `"payout_processor"`.
    pub connector_type: String,
    /// Snake-case connector identifier, e.g. `"stripe"`, `"adyen"`.
    pub connector_name: String,
    /// Human-readable label, unique within the merchant account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_label: Option<String>,
    /// Shop (business profile) the connector belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Gateway credentials (open shape — see the API reference). **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_account_details: Option<Value>,
    /// Payment methods to enable on this connector (open shapes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled on creation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Secret** (holds the shared
    /// verification secret).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_webhook_details: Option<Value>,
    /// Additional merchant data required by some connectors. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_merchant_data: Option<Value>,
    /// Connector status, e.g. `"active"` or `"inactive"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

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

/// `Some("[redacted]")` when the credential field is set, `None` when it is
/// not — enough to debug "did I set this?" without printing the secret.
fn redact(v: Option<&Value>) -> Option<&'static str> {
    v.map(|_| REDACTED)
}

impl std::fmt::Debug for ConnectorCreateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorCreateRequest")
            .field("connector_type", &self.connector_type)
            .field("connector_name", &self.connector_name)
            .field("connector_label", &self.connector_label)
            .field("profile_id", &self.profile_id)
            .field(
                "connector_account_details",
                &redact(self.connector_account_details.as_ref()),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &redact(self.connector_webhook_details.as_ref()),
            )
            .field(
                "additional_merchant_data",
                &redact(self.additional_merchant_data.as_ref()),
            )
            .field("status", &self.status)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `ConnectorCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_CREATE_REQUEST_NAMED: &[&str] = &[
    "connector_type",
    "connector_name",
    "connector_label",
    "profile_id",
    "connector_account_details",
    "payment_methods_enabled",
    "metadata",
    "test_mode",
    "disabled",
    "connector_webhook_details",
    "additional_merchant_data",
    "status",
];

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

impl ConnectorCreateRequest {
    /// A request creating a connector of the given category and name, e.g.
    /// `ConnectorCreateRequest::new("payment_processor", "stripe")`.
    pub fn new(connector_type: impl Into<String>, connector_name: impl Into<String>) -> Self {
        Self {
            connector_type: connector_type.into(),
            connector_name: connector_name.into(),
            ..Default::default()
        }
    }

    /// Set the shop (business profile) the connector belongs to.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Set the connector's label.
    #[must_use]
    pub fn connector_label(mut self, label: impl Into<String>) -> Self {
        self.connector_label = Some(label.into());
        self
    }

    /// Set the gateway credentials.
    #[must_use]
    pub fn connector_account_details(mut self, details: Value) -> Self {
        self.connector_account_details = Some(details);
        self
    }

    /// Set whether the connector runs in the gateway's test environment.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }
}

/// Parameters for [`Connectors::update`].
///
/// `Debug` is hand-written for the same reason as
/// [`ConnectorCreateRequest`]: the credential-bearing fields are redacted.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorUpdateRequest {
    /// Connector category, e.g. `"payment_processor"`. Required by the API.
    pub connector_type: String,
    /// Connector status, e.g. `"active"` or `"inactive"`. Required by the API.
    pub status: String,
    /// Human-readable label, unique within the merchant account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_label: Option<String>,
    /// Gateway credentials (open shape — see the API reference). **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_account_details: Option<Value>,
    /// Payment methods enabled on this connector (open shapes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_webhook_details: Option<Value>,
    /// Additional merchant data required by some connectors. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_merchant_data: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ConnectorUpdateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorUpdateRequest")
            .field("connector_type", &self.connector_type)
            .field("status", &self.status)
            .field("connector_label", &self.connector_label)
            .field(
                "connector_account_details",
                &redact(self.connector_account_details.as_ref()),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &redact(self.connector_webhook_details.as_ref()),
            )
            .field(
                "additional_merchant_data",
                &redact(self.additional_merchant_data.as_ref()),
            )
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `ConnectorUpdateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_UPDATE_REQUEST_NAMED: &[&str] = &[
    "connector_type",
    "status",
    "connector_label",
    "connector_account_details",
    "payment_methods_enabled",
    "metadata",
    "test_mode",
    "disabled",
    "connector_webhook_details",
    "additional_merchant_data",
];

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

impl ConnectorUpdateRequest {
    /// A request setting the connector's category and status, e.g.
    /// `ConnectorUpdateRequest::new("payment_processor", "active")`.
    pub fn new(connector_type: impl Into<String>, status: impl Into<String>) -> Self {
        Self {
            connector_type: connector_type.into(),
            status: status.into(),
            ..Default::default()
        }
    }

    /// Set the gateway credentials.
    #[must_use]
    pub fn connector_account_details(mut self, details: Value) -> Self {
        self.connector_account_details = Some(details);
        self
    }

    /// Set whether the connector is disabled.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = Some(disabled);
        self
    }
}

/// Parameters for [`Connectors::clone_connector`].
///
/// Carries no credentials — the copy happens server-side — so `Debug` is
/// derived.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorCloneRequest {
    /// Target shop (business profile) to clone the connector into. Must belong
    /// to the same merchant; it cannot be the source connector's own shop.
    pub profile_id: String,
    /// Label for the clone. Omit to let the server derive one from the source
    /// connector's label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_label: Option<String>,
}

impl ConnectorCloneRequest {
    /// A request cloning into the given shop (business profile).
    pub fn new(profile_id: impl Into<String>) -> Self {
        Self {
            profile_id: profile_id.into(),
            connector_label: None,
        }
    }

    /// Set the clone's label.
    #[must_use]
    pub fn connector_label(mut self, label: impl Into<String>) -> Self {
        self.connector_label = Some(label.into());
        self
    }
}

/// Parameters for [`Connectors::register_webhook`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorWebhookRegisterRequest {
    /// Event scope: the string `"all_events"`, or
    /// `{"specific_event": "…"}`. Omit to let the server default to all
    /// events.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<Value>,
    /// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
    /// `"live"` server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    /// Endpoint URL to register (plain `/webhooks/…` or obfuscated
    /// `/webhooks_base/…` form). When omitted the server derives the canonical
    /// plain form. Must route back to the connector account — the path has to
    /// end with the `mca_…` id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
}

impl ConnectorWebhookRegisterRequest {
    /// Register for every event the connector emits.
    pub fn all_events() -> Self {
        Self {
            event_type: Some(Value::String("all_events".to_string())),
            ..Default::default()
        }
    }

    /// Register for one named event only.
    pub fn specific_event(event: impl Into<String>) -> Self {
        Self {
            event_type: Some(serde_json::json!({ "specific_event": event.into() })),
            ..Default::default()
        }
    }

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

    /// Register a specific endpoint URL instead of the server-derived one.
    #[must_use]
    pub fn webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }
}

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

    const CONNECTOR_JSON: &str = r#"{
        "merchant_connector_id": "mca_1",
        "connector_type": "payment_processor",
        "connector_name": "stripe",
        "profile_id": "pro_1",
        "status": "active"
    }"#;

    fn full_create_request() -> ConnectorCreateRequest {
        ConnectorCreateRequest {
            connector_type: "payment_processor".to_string(),
            connector_name: "stripe".to_string(),
            connector_label: Some("stripe_uk".to_string()),
            profile_id: Some("pro_1".to_string()),
            connector_account_details: Some(json!({"api_key": "sk_live_supersecret"})),
            payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
            metadata: Some(json!({"team": "payments"})),
            test_mode: Some(false),
            disabled: Some(false),
            connector_webhook_details: Some(json!({"merchant_secret": "whsec_topsecret"})),
            additional_merchant_data: Some(json!({"acquirer": "acq_1"})),
            status: Some("active".to_string()),
            extra: serde_json::Map::new(),
        }
    }

    fn full_update_request() -> ConnectorUpdateRequest {
        ConnectorUpdateRequest {
            connector_type: "payment_processor".to_string(),
            status: "active".to_string(),
            connector_label: Some("stripe_uk".to_string()),
            connector_account_details: Some(json!({"api_key": "sk_live_supersecret"})),
            payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
            metadata: Some(json!({"team": "payments"})),
            test_mode: Some(false),
            disabled: Some(false),
            connector_webhook_details: Some(json!({"merchant_secret": "whsec_topsecret"})),
            additional_merchant_data: Some(json!({"acquirer": "acq_1"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard: catches a new field added to `ConnectorCreateRequest`
    /// without a matching update to `CONNECTOR_CREATE_REQUEST_NAMED`.
    #[test]
    fn connector_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_create_request()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CONNECTOR_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "CONNECTOR_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

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

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = ConnectorCreateRequest::new("payment_processor", "stripe");
        req.extra.insert("profile_id".to_string(), json!("pro_2"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("profile_id")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[test]
    fn update_validate_rejects_colliding_extra_key() {
        let mut req = ConnectorUpdateRequest::new("payment_processor", "active");
        req.extra.insert("status".to_string(), json!("inactive"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    /// The credential fields must never reach a log line. A mutation replacing
    /// `redact(...)` with the field itself makes this red.
    #[test]
    fn debug_redacts_connector_credentials() {
        let rendered = format!("{:?}", full_create_request());
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(!rendered.contains("acq_1"), "{rendered}");
        assert!(rendered.contains("connector_account_details: Some(\"[redacted]\")"));
        // Non-secret fields still print, or the impl would be useless.
        assert!(rendered.contains("stripe"), "{rendered}");

        let rendered = format!("{:?}", full_update_request());
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(!rendered.contains("acq_1"), "{rendered}");
        assert!(rendered.contains("connector_account_details: Some(\"[redacted]\")"));
    }

    /// An unset credential field must be distinguishable from a set one.
    #[test]
    fn debug_shows_none_for_unset_credentials() {
        let rendered = format!(
            "{:?}",
            ConnectorCreateRequest::new("payment_processor", "stripe")
        );
        assert!(
            rendered.contains("connector_account_details: None"),
            "{rendered}"
        );
    }

    #[tokio::test]
    async fn create_posts_to_the_account_connectors_path() {
        let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
        let req = ConnectorCreateRequest::new("payment_processor", "stripe")
            .profile_id("pro_1")
            .connector_account_details(json!({"api_key": "sk_test"}));
        let created = client.connectors().create("mer/1", &req).await.unwrap();
        assert_eq!(created.merchant_connector_id, "mca_1");
        assert_eq!(created.connector_name.as_deref(), Some("stripe"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/account/mer%2F1/connectors");
        let body = seen[0].body_json();
        assert_eq!(body["connector_name"], "stripe");
        assert_eq!(body["connector_account_details"]["api_key"], "sk_test");
    }

    #[tokio::test]
    async fn retrieve_list_and_delete_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(CONNECTOR_JSON),
            Step::ok("[]"),
            Step::ok(CONNECTOR_JSON),
        ]);
        let connectors = client.connectors();
        let retrieved = connectors.retrieve("mer_1", "mca/1").await.unwrap();
        assert_eq!(retrieved.status.as_deref(), Some("active"));
        assert!(connectors.list("mer_1").await.unwrap().is_empty());
        connectors.delete("mer_1", "mca_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/account/mer_1/connectors/mca%2F1")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/account/mer_1/connectors")
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("DELETE", "https://api.test/account/mer_1/connectors/mca_1")
        );
    }

    #[tokio::test]
    async fn update_posts_the_status_to_the_connector_path() {
        let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
        let req = ConnectorUpdateRequest::new("payment_processor", "inactive").disabled(true);
        client
            .connectors()
            .update("mer_1", "mca_1", &req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["status"], "inactive");
        assert_eq!(body["disabled"], true);
    }

    #[tokio::test]
    async fn clone_connector_posts_the_target_profile() {
        let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
        let req = ConnectorCloneRequest::new("pro_2").connector_label("stripe_de");
        client
            .connectors()
            .clone_connector("mer_1", "mca_1", &req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/clone"
        );
        let body = seen[0].body_json();
        assert_eq!(body["profile_id"], "pro_2");
        assert_eq!(body["connector_label"], "stripe_de");
    }

    #[tokio::test]
    async fn verify_posts_the_open_body() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"status":"ok"}"#)]);
        client
            .connectors()
            .verify(&json!({"connector_name": "stripe"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/account/connectors/verify");
        assert_eq!(seen[0].body_json()["connector_name"], "stripe");
    }

    #[tokio::test]
    async fn register_webhook_omits_the_body_when_no_params() {
        // The server only applies its `all_events` default to a bodyless call,
        // so a mutation sending `{}` here must fail.
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"webhook_registration_status":"success"}"#,
        )]);
        let registered = client
            .connectors()
            .register_webhook("mer_1", "mca_1", None)
            .await
            .unwrap();
        assert_eq!(registered.webhook_registration_status, "success");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1"
        );
        assert!(seen[0].body.is_none(), "expected no request body");
    }

    #[tokio::test]
    async fn register_webhook_sends_a_specific_event_scope() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"webhook_registration_status":"success"}"#,
        )]);
        let req = ConnectorWebhookRegisterRequest::specific_event("payment_intent.succeeded")
            .environment("sandbox");
        client
            .connectors()
            .register_webhook("mer_1", "mca_1", Some(&req))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert_eq!(
            body["event_type"]["specific_event"],
            "payment_intent.succeeded"
        );
        assert_eq!(body["environment"], "sandbox");
    }

    #[tokio::test]
    async fn webhook_and_payment_methods_get_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"connector":"stripe","webhooks":[{"connector_webhook_id":"we_1"}]}"#),
            Step::ok("[]"),
        ]);
        let connectors = client.connectors();
        let listed = connectors.webhook("mer_1", "mca_1").await.unwrap();
        assert_eq!(listed.connector, "stripe");
        assert_eq!(listed.webhooks.len(), 1);
        assert_eq!(listed.webhooks[0].connector_webhook_id, "we_1");
        connectors.list_payment_methods().await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/account/mer_1/connectors/webhooks/mca_1"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/account/payment-methods")
        );
    }
}