delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! The `identity_verifications` resource: identity verification (KYC, KYB,
//! AML screening, age, proof of address) through a connected identity
//! verification provider account, and that account's transaction screening
//! and device intelligence.
//!
//! A test verification runs on the account's test credentials only, a live
//! one on its live credentials only. Reading needs permission to read
//! customers; starting a verification needs permission to edit them.

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::identity_verification::{
    AmlEventListResponse, DeviceIntelligenceSettingResponse, DeviceSignalResponse,
    IdentityVerificationFlowsResponse, IdentityVerificationListResponse,
    IdentityVerificationResponse, OperationScreeningResponse, PaymentScreeningResponse,
    PaymentScreeningSettingResponse, SubjectVerificationResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

/// The `{"enabled": …}` body of the switch endpoints.
#[derive(Serialize)]
struct EnabledBody {
    enabled: bool,
}

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

    /// Start a verification of a person or a business. The provider-side
    /// workflow decides the checks. With a `return_url`, the provider's
    /// session is created at once and its page returned in
    /// `verification_url`. With a `payment_id` and no `return_url`, the
    /// payment's checkout starts it. `POST /identity-verifications`
    pub async fn create(
        &self,
        params: &IdentityVerificationCreateRequest,
    ) -> Result<IdentityVerificationResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/identity-verifications",
                Some(&body),
                None,
            )
            .await
    }

    /// The merchant's verifications, newest first. A caller limited to one
    /// shop sees that shop's only. `GET /identity-verifications`
    pub async fn list(
        &self,
        params: Option<&IdentityVerificationListParams>,
    ) -> Result<IdentityVerificationListResponse> {
        let query = params
            .map(IdentityVerificationListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/identity-verifications",
                None,
                &query,
                None,
            )
            .await
    }

    /// One verification. With `force_sync`, a verification the provider can
    /// still change (pending or in review, or a subject under ongoing AML
    /// monitoring) is read from the provider first.
    /// `GET /identity-verifications/{verification_id}`
    pub async fn retrieve(
        &self,
        verification_id: &str,
        force_sync: bool,
    ) -> Result<IdentityVerificationResponse> {
        let query: Vec<(&str, String)> = if force_sync {
            vec![("force_sync", "true".to_string())]
        } else {
            Vec::new()
        };
        self.inner
            .request(
                HttpMethod::Get,
                &verification_path(verification_id),
                None,
                &query,
                None,
            )
            .await
    }

    /// A subject's latest verification in one environment (live unless
    /// `test_mode` is `Some(true)`), with its checks, and the subject's
    /// verification under ongoing AML monitoring.
    /// `GET /identity-verifications/subjects/{subject_reference}`
    pub async fn subject(
        &self,
        subject_reference: &str,
        test_mode: Option<bool>,
    ) -> Result<SubjectVerificationResponse> {
        let path = format!(
            "/identity-verifications/subjects/{}",
            encode_segment(subject_reference)
        );
        self.inner
            .request(
                HttpMethod::Get,
                &path,
                None,
                &test_mode_query(test_mode),
                None,
            )
            .await
    }

    /// The provider-side workflows an account can run in one environment,
    /// read from the provider. Pass a `flow_id` as `provider_flow_id` to
    /// [`create`](Self::create).
    /// `GET /identity-verifications/accounts/{merchant_connector_id}/flows`
    pub async fn flows(
        &self,
        merchant_connector_id: &str,
        test_mode: Option<bool>,
    ) -> Result<IdentityVerificationFlowsResponse> {
        let path = format!("{}/flows", account_path(merchant_connector_id));
        self.inner
            .request(
                HttpMethod::Get,
                &path,
                None,
                &test_mode_query(test_mode),
                None,
            )
            .await
    }

    /// Switch ongoing AML monitoring of a verification's subject. Only a
    /// verified person or business can be enrolled; monitoring can be
    /// switched off at any time. Needs permission to edit customers.
    /// `POST /identity-verifications/{verification_id}/aml-monitoring`
    pub async fn set_aml_monitoring(
        &self,
        verification_id: &str,
        enabled: bool,
    ) -> Result<IdentityVerificationResponse> {
        let path = format!("{}/aml-monitoring", verification_path(verification_id));
        let body = to_json_vec(&EnabledBody { enabled })?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }

    /// Every change of the subject's AML result the provider reported while
    /// the subject was monitored, newest first, at most 100.
    /// `GET /identity-verifications/{verification_id}/aml-events`
    pub async fn aml_events(&self, verification_id: &str) -> Result<AmlEventListResponse> {
        let path = format!("{}/aml-events", verification_path(verification_id));
        self.get(&path).await
    }

    /// A payment's screening by the transaction monitoring of the shop's
    /// screening account. Recorded only: it never holds or refuses the
    /// payment. Answers 404 when the payment has no screening.
    /// `GET /identity-verifications/payment-screenings/{payment_id}`
    pub async fn payment_screening(&self, payment_id: &str) -> Result<PaymentScreeningResponse> {
        self.get(&operation_path("payment-screenings", payment_id))
            .await
    }

    /// Whether an account screens its shop's payments.
    /// `GET /identity-verifications/accounts/{merchant_connector_id}/payment-screening`
    pub async fn payment_screening_setting(
        &self,
        merchant_connector_id: &str,
    ) -> Result<PaymentScreeningSettingResponse> {
        let path = format!("{}/payment-screening", account_path(merchant_connector_id));
        self.get(&path).await
    }

    /// Switch screening of the account's shop's payments. Switched on, every
    /// payment of the shop that succeeds from then on is screened shortly
    /// after. A shop has at most one screening account.
    /// `PUT /identity-verifications/accounts/{merchant_connector_id}/payment-screening`
    pub async fn update_payment_screening_setting(
        &self,
        merchant_connector_id: &str,
        enabled: bool,
    ) -> Result<PaymentScreeningSettingResponse> {
        let path = format!("{}/payment-screening", account_path(merchant_connector_id));
        self.put_enabled(&path, enabled).await
    }

    /// A refund's screening, for a provider that screens refunds. Recorded
    /// only: it never holds or reverses the refund. Answers 404 when the
    /// refund has no screening.
    /// `GET /identity-verifications/refund-screenings/{refund_id}`
    pub async fn refund_screening(&self, refund_id: &str) -> Result<OperationScreeningResponse> {
        self.get(&operation_path("refund-screenings", refund_id))
            .await
    }

    /// A payout's screening, for a provider that screens payouts. Recorded
    /// only: it never holds or reverses the payout. Answers 404 when the
    /// payout has no screening.
    /// `GET /identity-verifications/payout-screenings/{payout_id}`
    pub async fn payout_screening(&self, payout_id: &str) -> Result<OperationScreeningResponse> {
        self.get(&operation_path("payout-screenings", payout_id))
            .await
    }

    /// Whether an account assesses its shop's checkout devices.
    /// `GET /identity-verifications/accounts/{merchant_connector_id}/device-intelligence`
    pub async fn device_intelligence_setting(
        &self,
        merchant_connector_id: &str,
    ) -> Result<DeviceIntelligenceSettingResponse> {
        let path = format!(
            "{}/device-intelligence",
            account_path(merchant_connector_id)
        );
        self.get(&path).await
    }

    /// Switch device intelligence of the account's shop. Switched on, every
    /// checkout of the shop assesses the buyer's device and records the
    /// provider's signal on the payment; it never holds or refuses a payment.
    /// A shop has at most one device intelligence account.
    /// `PUT /identity-verifications/accounts/{merchant_connector_id}/device-intelligence`
    pub async fn update_device_intelligence_setting(
        &self,
        merchant_connector_id: &str,
        enabled: bool,
    ) -> Result<DeviceIntelligenceSettingResponse> {
        let path = format!(
            "{}/device-intelligence",
            account_path(merchant_connector_id)
        );
        self.put_enabled(&path, enabled).await
    }

    /// A payment's device signal from its checkout's device assessment.
    /// Recorded only. Answers 404 when the payment's checkout was not
    /// assessed. `GET /identity-verifications/device-signals/{payment_id}`
    pub async fn device_signal(&self, payment_id: &str) -> Result<DeviceSignalResponse> {
        self.get(&operation_path("device-signals", payment_id))
            .await
    }

    async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.inner
            .request(HttpMethod::Get, path, None, &[], None)
            .await
    }

    async fn put_enabled<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        enabled: bool,
    ) -> Result<T> {
        let body = to_json_vec(&EnabledBody { enabled })?;
        self.inner
            .request_body_keyed(HttpMethod::Put, path, Some(&body), None)
            .await
    }
}

/// `/identity-verifications/{verification_id}`, percent-encoded.
fn verification_path(verification_id: &str) -> String {
    format!(
        "/identity-verifications/{}",
        encode_segment(verification_id)
    )
}

/// `/identity-verifications/accounts/{merchant_connector_id}`, percent-encoded.
fn account_path(merchant_connector_id: &str) -> String {
    format!(
        "/identity-verifications/accounts/{}",
        encode_segment(merchant_connector_id)
    )
}

/// `/identity-verifications/{kind}/{id}`, with `id` percent-encoded.
fn operation_path(kind: &str, id: &str) -> String {
    format!("/identity-verifications/{kind}/{}", encode_segment(id))
}

fn test_mode_query(test_mode: Option<bool>) -> Vec<(&'static str, String)> {
    test_mode
        .map(|v| vec![("test_mode", v.to_string())])
        .unwrap_or_default()
}

/// Filters for [`IdentityVerifications::list`].
#[derive(Debug, Clone, Default)]
pub struct IdentityVerificationListParams {
    /// Only verifications of this subject.
    pub subject_reference: Option<String>,
    /// Only verifications asked for by this payment.
    pub payment_id: Option<String>,
    /// `true` for test verifications only, `false` for live only.
    pub test_mode: Option<bool>,
    /// Page size.
    pub limit: Option<u32>,
    /// Verifications to skip.
    pub offset: Option<u32>,
}

impl IdentityVerificationListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.subject_reference {
            q.push(("subject_reference", v.clone()));
        }
        if let Some(v) = &self.payment_id {
            q.push(("payment_id", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// The kind of verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum VerificationKind {
    /// A person (KYC).
    Person,
    /// A business (KYB).
    Business,
    /// An AML screening.
    AmlScreening,
    /// An age check.
    Age,
    /// A proof of address.
    ProofOfAddress,
    /// Ownership of a payment method.
    PaymentMethodOwnership,
}

/// Parameters for [`IdentityVerifications::create`].
#[derive(Debug, Clone, Serialize)]
pub struct IdentityVerificationCreateRequest {
    /// The identity verification provider account to run it on.
    pub merchant_connector_id: String,
    /// The kind of verification.
    pub kind: VerificationKind,
    /// The provider-side workflow, as [`IdentityVerifications::flows`] lists
    /// it.
    pub provider_flow_id: String,
    /// Your own id for the person or business, up to 255 characters.
    pub subject_reference: String,
    /// The payment that asked for the verification; its checkout then shows
    /// the verification step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id: Option<String>,
    /// `true` runs on the account's test credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Where the provider sends the subject when they finish. Required
    /// without `payment_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// The subject's language, for example `de` or `pt-BR`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl IdentityVerificationCreateRequest {
    /// Run `provider_flow_id` on `merchant_connector_id` for
    /// `subject_reference`.
    pub fn new(
        merchant_connector_id: impl Into<String>,
        kind: VerificationKind,
        provider_flow_id: impl Into<String>,
        subject_reference: impl Into<String>,
    ) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            kind,
            provider_flow_id: provider_flow_id.into(),
            subject_reference: subject_reference.into(),
            payment_id: None,
            test_mode: None,
            return_url: None,
            locale: None,
            extra: serde_json::Map::new(),
        }
    }

    /// Tie the verification to a payment.
    #[must_use]
    pub fn payment_id(mut self, payment_id: impl Into<String>) -> Self {
        self.payment_id = Some(payment_id.into());
        self
    }

    /// Run on the test (`true`) or live (`false`) credentials.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }

    /// Set where the provider sends the subject when they finish.
    #[must_use]
    pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
        self.return_url = Some(return_url.into());
        self
    }

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

/// Names of `IdentityVerificationCreateRequest`'s fields as they appear on
/// the wire (`extra` excluded).
const IDENTITY_VERIFICATION_CREATE_REQUEST_NAMED: &[&str] = &[
    "merchant_connector_id",
    "kind",
    "provider_flow_id",
    "subject_reference",
    "payment_id",
    "test_mode",
    "return_url",
    "locale",
];

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

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

    const VERIFICATION_JSON: &str = r#"{
        "verification_id": "iv_1", "profile_id": "pro_1", "merchant_connector_id": "mca_1",
        "connector": "didit", "kind": "person", "subject_reference": "user-42",
        "payment_id": null, "test_mode": true, "provider_flow_id": "flow_1",
        "provider_reference": "sess_1", "outcome": "verified",
        "checks": [{"check": "document", "outcome": "passed"}],
        "verification_url": "https://verify.example/s/1",
        "provider_cost": {"amount": 65, "currency": "EUR", "basis": "reported"},
        "aml_monitoring": {"enabled": false, "monitored_by_provider": null,
            "changed_at": null, "status": null, "hits": null,
            "status_changed_at": null, "yearly_cost": null},
        "created_at": "2026-01-01T00:00:00Z", "modified_at": "2026-01-01T00:00:00Z",
        "completed_at": "2026-01-01T00:05:00Z", "iv_surprise": 1
    }"#;

    const SCREENING_FIELDS: &str = r#""profile_id": "pro_1", "merchant_connector_id": "mca_2",
        "connector": "sumsub", "test_mode": false, "outcome": "approved",
        "not_screened_reason": null, "risk_score": 12, "provider_reference": "scr_1",
        "provider_cost": null, "created_at": "2026-01-01T00:00:00Z",
        "screened_at": "2026-01-01T00:01:00Z", "x": 1"#;

    const SETTING_JSON: &str = r#"{"merchant_connector_id":"mca_2","profile_id":"pro_1",
        "enabled":true,"enabled_at":"2026-01-01T00:00:00Z","x":1}"#;

    #[tokio::test]
    async fn create_posts_the_verification() {
        let (client, mock) = client_with(vec![Step::ok(VERIFICATION_JSON)]);
        let req = IdentityVerificationCreateRequest::new(
            "mca_1",
            VerificationKind::Person,
            "flow_1",
            "user-42",
        )
        .test_mode(true)
        .return_url("https://shop.example/done")
        .locale("de");
        let out = client.identity_verifications().create(&req).await.unwrap();
        assert_eq!(out.outcome, "verified");
        assert_eq!(out.provider_cost.unwrap().amount, 65);
        assert_eq!(out.extra["iv_surprise"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/identity-verifications");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "merchant_connector_id": "mca_1",
                "kind": "person",
                "provider_flow_id": "flow_1",
                "subject_reference": "user-42",
                "test_mode": true,
                "return_url": "https://shop.example/done",
                "locale": "de"
            })
        );
    }

    #[tokio::test]
    async fn list_sends_the_filters() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"count":1,"total_count":3,"data":[{VERIFICATION_JSON}]}}"#
        ))]);
        let params = IdentityVerificationListParams {
            subject_reference: Some("user-42".to_string()),
            test_mode: Some(true),
            limit: Some(1),
            offset: Some(2),
            ..Default::default()
        };
        let out = client
            .identity_verifications()
            .list(Some(&params))
            .await
            .unwrap();
        assert_eq!(out.total_count, 3);
        assert_eq!(out.data[0].checks[0].check, "document");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications?subject_reference=user-42&test_mode=true\
             &limit=1&offset=2"
        );
    }

    #[tokio::test]
    async fn retrieve_sends_force_sync_only_when_asked() {
        let (client, mock) = client_with(vec![
            Step::ok(VERIFICATION_JSON),
            Step::ok(VERIFICATION_JSON),
        ]);
        client
            .identity_verifications()
            .retrieve("iv/1", true)
            .await
            .unwrap();
        client
            .identity_verifications()
            .retrieve("iv_1", false)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/iv%2F1?force_sync=true"
        );
        assert_eq!(seen[1].url, "https://api.test/identity-verifications/iv_1");
    }

    #[tokio::test]
    async fn subject_gets_the_encoded_subject() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"subject_reference":"user/42","verification":{"verification_id":"iv_1",
                "kind":"person","outcome":"verified","checks":[],"test_mode":true,
                "created_at":"2026-01-01T00:00:00Z","completed_at":null},
                "aml_monitoring":null,"x":1}"#,
        )]);
        let out = client
            .identity_verifications()
            .subject("user/42", Some(true))
            .await
            .unwrap();
        assert_eq!(out.verification.unwrap().verification_id, "iv_1");
        assert!(out.aml_monitoring.is_none());
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/subjects/user%2F42?test_mode=true"
        );
    }

    #[tokio::test]
    async fn flows_gets_the_account_flows() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","test_mode":false,
                "flows":[{"flow_id":"flow_1","name":"KYC","kind":"person","x":1}]}"#,
        )]);
        let out = client
            .identity_verifications()
            .flows("mca_1", None)
            .await
            .unwrap();
        assert_eq!(out.flows[0].kind.as_deref(), Some("person"));
        assert_eq!(out.flows[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/accounts/mca_1/flows"
        );
    }

    #[tokio::test]
    async fn set_aml_monitoring_posts_the_switch() {
        let (client, mock) = client_with(vec![Step::ok(VERIFICATION_JSON)]);
        client
            .identity_verifications()
            .set_aml_monitoring("iv_1", true)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/iv_1/aml-monitoring"
        );
        assert_eq!(seen[0].body_json(), json!({"enabled": true}));
    }

    #[tokio::test]
    async fn aml_events_gets_the_events() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"verification_id":"iv_1","data":[{"event_id":"ae_1","previous_status":"clear",
                "status":"hit","previous_hits":0,"hits":2,"previous_outcome":"verified",
                "outcome":"needs_review","created_at":"2026-01-01T00:00:00Z","x":1}]}"#,
        )]);
        let out = client
            .identity_verifications()
            .aml_events("iv_1")
            .await
            .unwrap();
        assert_eq!(out.data[0].hits, Some(2));
        assert_eq!(out.data[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/iv_1/aml-events"
        );
    }

    #[tokio::test]
    async fn payment_screening_gets_the_payment() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"payment_id": "pay_1", {SCREENING_FIELDS}}}"#
        ))]);
        let out = client
            .identity_verifications()
            .payment_screening("pay/1")
            .await
            .unwrap();
        assert_eq!(out.risk_score, Some(12));
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/payment-screenings/pay%2F1"
        );
    }

    #[tokio::test]
    async fn payment_screening_setting_gets_the_account_setting() {
        let (client, mock) = client_with(vec![Step::ok(SETTING_JSON)]);
        let out = client
            .identity_verifications()
            .payment_screening_setting("mca_2")
            .await
            .unwrap();
        assert!(out.enabled);
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/accounts/mca_2/payment-screening"
        );
    }

    #[tokio::test]
    async fn update_payment_screening_setting_puts_the_switch() {
        let (client, mock) = client_with(vec![Step::ok(SETTING_JSON)]);
        client
            .identity_verifications()
            .update_payment_screening_setting("mca_2", false)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/accounts/mca_2/payment-screening"
        );
        assert_eq!(seen[0].body_json(), json!({"enabled": false}));
    }

    #[tokio::test]
    async fn refund_screening_gets_the_refund() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"operation": "refund", "operation_id": "ref_1", "payment_id": "pay_1", {SCREENING_FIELDS}}}"#
        ))]);
        let out = client
            .identity_verifications()
            .refund_screening("ref_1")
            .await
            .unwrap();
        assert_eq!(out.operation, "refund");
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/refund-screenings/ref_1"
        );
    }

    #[tokio::test]
    async fn payout_screening_gets_the_payout() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"operation": "payout", "operation_id": "po_1", "payment_id": null, {SCREENING_FIELDS}}}"#
        ))]);
        let out = client
            .identity_verifications()
            .payout_screening("po_1")
            .await
            .unwrap();
        assert_eq!(out.operation_id, "po_1");
        assert!(out.payment_id.is_none());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/payout-screenings/po_1"
        );
    }

    #[tokio::test]
    async fn device_intelligence_setting_gets_the_account_setting() {
        let (client, mock) = client_with(vec![Step::ok(SETTING_JSON)]);
        let out = client
            .identity_verifications()
            .device_intelligence_setting("mca_2")
            .await
            .unwrap();
        assert_eq!(out.enabled_at.as_deref(), Some("2026-01-01T00:00:00Z"));
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/accounts/mca_2/device-intelligence"
        );
    }

    #[tokio::test]
    async fn update_device_intelligence_setting_puts_the_switch() {
        let (client, mock) = client_with(vec![Step::ok(SETTING_JSON)]);
        client
            .identity_verifications()
            .update_device_intelligence_setting("mca/2", true)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/accounts/mca%2F2/device-intelligence"
        );
        assert_eq!(seen[0].body_json(), json!({"enabled": true}));
    }

    #[tokio::test]
    async fn device_signal_gets_the_payment_signal() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"payment_id":"pay_1","profile_id":"pro_1","merchant_connector_id":"mca_2",
                "connector":"fingerprint","test_mode":false,"outcome":"recorded",
                "not_recorded_reason":null,"risk_score":80,"ip_country":"NL",
                "risk_labels":["vpn","incognito"],"provider_details":{"bot":false},
                "created_at":"2026-01-01T00:00:00Z","recorded_at":"2026-01-01T00:00:01Z","x":1}"#,
        )]);
        let out = client
            .identity_verifications()
            .device_signal("pay_1")
            .await
            .unwrap();
        assert_eq!(out.risk_labels, ["vpn", "incognito"]);
        assert_eq!(out.provider_details["bot"], false);
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/identity-verifications/device-signals/pay_1"
        );
    }

    /// Drift guard for `IDENTITY_VERIFICATION_CREATE_REQUEST_NAMED`.
    #[test]
    fn identity_verification_create_request_named_fields_are_complete() {
        let req = IdentityVerificationCreateRequest::new(
            "mca_1",
            VerificationKind::Business,
            "flow_1",
            "s",
        )
        .payment_id("pay_1")
        .test_mode(true)
        .return_url("https://shop.example/done")
        .locale("de");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                IDENTITY_VERIFICATION_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "IDENTITY_VERIFICATION_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req =
            IdentityVerificationCreateRequest::new("mca_1", VerificationKind::Age, "flow_1", "s");
        req.extra.insert("kind".to_string(), json!("person"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("kind")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// Every write here ignores the client-wide idempotency key: none sends
    /// it, and none is replayed after a `503`. Switching a call site back to
    /// `request(.., None)` makes it send the key and retry.
    #[tokio::test]
    async fn writes_ignore_the_client_wide_idempotency_key() {
        let steps = (0..4)
            .map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
            .collect();
        let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
        let client = client.with_idempotency_key("client-key");
        client
            .identity_verifications()
            .create(&IdentityVerificationCreateRequest::new(
                "mca_1",
                VerificationKind::Person,
                "flow_1",
                "s",
            ))
            .await
            .unwrap_err();
        client
            .identity_verifications()
            .set_aml_monitoring("iv_1", true)
            .await
            .unwrap_err();
        client
            .identity_verifications()
            .update_payment_screening_setting("mca_1", true)
            .await
            .unwrap_err();
        client
            .identity_verifications()
            .update_device_intelligence_setting("mca_1", true)
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 4);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }
}