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;
#[derive(Debug, Clone)]
pub struct IdentityVerifications {
inner: Arc<Inner>,
}
#[derive(Serialize)]
struct EnabledBody {
enabled: bool,
}
impl IdentityVerifications {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
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
}
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
}
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
}
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
}
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
}
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
}
pub async fn aml_events(&self, verification_id: &str) -> Result<AmlEventListResponse> {
let path = format!("{}/aml-events", verification_path(verification_id));
self.get(&path).await
}
pub async fn payment_screening(&self, payment_id: &str) -> Result<PaymentScreeningResponse> {
self.get(&operation_path("payment-screenings", payment_id))
.await
}
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
}
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
}
pub async fn refund_screening(&self, refund_id: &str) -> Result<OperationScreeningResponse> {
self.get(&operation_path("refund-screenings", refund_id))
.await
}
pub async fn payout_screening(&self, payout_id: &str) -> Result<OperationScreeningResponse> {
self.get(&operation_path("payout-screenings", payout_id))
.await
}
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
}
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
}
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
}
}
fn verification_path(verification_id: &str) -> String {
format!(
"/identity-verifications/{}",
encode_segment(verification_id)
)
}
fn account_path(merchant_connector_id: &str) -> String {
format!(
"/identity-verifications/accounts/{}",
encode_segment(merchant_connector_id)
)
}
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()
}
#[derive(Debug, Clone, Default)]
pub struct IdentityVerificationListParams {
pub subject_reference: Option<String>,
pub payment_id: Option<String>,
pub test_mode: Option<bool>,
pub limit: Option<u32>,
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
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum VerificationKind {
Person,
Business,
AmlScreening,
Age,
ProofOfAddress,
PaymentMethodOwnership,
}
#[derive(Debug, Clone, Serialize)]
pub struct IdentityVerificationCreateRequest {
pub merchant_connector_id: String,
pub kind: VerificationKind,
pub provider_flow_id: String,
pub subject_reference: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_mode: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl IdentityVerificationCreateRequest {
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(),
}
}
#[must_use]
pub fn payment_id(mut self, payment_id: impl Into<String>) -> Self {
self.payment_id = Some(payment_id.into());
self
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
#[must_use]
pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
self.return_url = Some(return_url.into());
self
}
#[must_use]
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = Some(locale.into());
self
}
}
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(¶ms))
.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"
);
}
#[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:?}"),
}
}
#[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
);
}
}
}