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
//! The `authentication` resource: standalone 3-D Secure authentication.
//!
//! Lets you run a 3DS authentication on its own — separately from a payment —
//! then feed the outcome into whatever charge flow you use. The authentication
//! lifecycle calls return [`AuthenticationResponse`]; the redirect / token /
//! eligibility-check endpoints stay open shapes ([`serde_json::Value`]),
//! because the API reference documents them rather than us.

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::authentication::AuthenticationResponse;
use crate::core::models::common::Currency;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Start a 3DS authentication.
    pub async fn create(
        &self,
        params: &AuthenticationCreateRequest,
    ) -> Result<AuthenticationResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/authentication", Some(&body), &[], None)
            .await
    }

    /// Check whether the card is eligible for 3DS.
    pub async fn check_eligibility(
        &self,
        authentication_id: &str,
    ) -> Result<AuthenticationResponse> {
        let path = format!(
            "/authentication/{}/eligibility",
            encode_segment(authentication_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Run the authentication itself (open request shape — see the API
    /// reference).
    pub async fn authenticate(
        &self,
        authentication_id: &str,
        params: &Value,
    ) -> Result<AuthenticationResponse> {
        let path = format!(
            "/authentication/{}/authenticate",
            encode_segment(authentication_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Sync an authentication's status with the 3DS server.
    pub async fn sync(
        &self,
        merchant_id: &str,
        authentication_id: &str,
        params: Option<&Value>,
    ) -> Result<AuthenticationResponse> {
        let path = format!(
            "/authentication/{}/{}/sync",
            encode_segment(merchant_id),
            encode_segment(authentication_id)
        );
        let body: Option<Vec<u8>> = match params {
            Some(p) => Some(to_json_vec(p)?),
            None => None,
        };
        self.inner
            .request(HttpMethod::Post, &path, body.as_deref(), &[], None)
            .await
    }

    /// Handle the browser redirect back from the 3DS challenge (open
    /// request/response shapes).
    pub async fn redirect(
        &self,
        merchant_id: &str,
        authentication_id: &str,
        params: &Value,
    ) -> Result<Value> {
        let path = format!(
            "/authentication/{}/{}/redirect",
            encode_segment(merchant_id),
            encode_segment(authentication_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Mint a token listing the authentication methods enabled for this
    /// authentication (open request/response shapes).
    pub async fn enabled_authn_methods_token(
        &self,
        authentication_id: &str,
        params: &Value,
    ) -> Result<Value> {
        let path = format!(
            "/authentication/{}/enabled-authn-methods-token",
            encode_segment(authentication_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Submit an eligibility check (open request/response shapes).
    pub async fn eligibility_check(
        &self,
        authentication_id: &str,
        params: &Value,
    ) -> Result<Value> {
        let path = format!(
            "/authentication/{}/eligibility-check",
            encode_segment(authentication_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }
}

/// Parameters for [`Authentication::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct AuthenticationCreateRequest {
    /// Amount to authenticate, in the currency's minor units.
    pub amount: i64,
    /// Three-letter currency code, e.g. `"USD"`.
    pub currency: Currency,
    /// Provide your own authentication ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication_id: Option<String>,
    /// Shop (business profile) to authenticate under.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Customer details (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer: Option<Value>,
    /// 3DS connector to authenticate through.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication_connector: Option<String>,
    /// URL the customer is returned to after the challenge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Force a 3DS challenge rather than allowing a frictionless flow.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub force_3ds_challenge: Option<bool>,
    /// PSD2 SCA exemption to claim.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub psd2_sca_exemption_type: Option<String>,
    /// Acquirer configuration to authenticate against.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_acquirer_id: Option<String>,
    /// Payment method data (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_data: Option<Value>,
    /// Any additional create fields not modeled above, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `AuthenticationCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const AUTHENTICATION_CREATE_REQUEST_NAMED: &[&str] = &[
    "amount",
    "currency",
    "authentication_id",
    "profile_id",
    "customer",
    "authentication_connector",
    "return_url",
    "force_3ds_challenge",
    "psd2_sca_exemption_type",
    "profile_acquirer_id",
    "payment_method_data",
];

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

impl AuthenticationCreateRequest {
    /// A request authenticating `amount` minor units of `currency`.
    pub fn new(amount: i64, currency: impl Into<Currency>) -> Self {
        Self {
            amount,
            currency: currency.into(),
            ..Default::default()
        }
    }

    /// Set the URL the customer is returned to after the challenge.
    #[must_use]
    pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
        self.return_url = Some(return_url.into());
        self
    }

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

    /// Force a 3DS challenge rather than allowing a frictionless flow.
    #[must_use]
    pub fn force_3ds_challenge(mut self, force: bool) -> Self {
        self.force_3ds_challenge = Some(force);
        self
    }
}

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

    const AUTH_JSON: &str = r#"{
        "authentication_id": "auth_1", "merchant_id": "merch_1",
        "status": "started", "amount": 1000, "currency": "USD",
        "client_secret": "auth_1_secret", "three_ds_server_id": "srv_9"
    }"#;

    #[tokio::test]
    async fn create_posts_to_the_authentication_root() {
        let (client, mock) = client_with(vec![Step::ok(AUTH_JSON)]);
        let out = client
            .authentication()
            .create(
                &AuthenticationCreateRequest::new(1000, "USD")
                    .return_url("https://example.com/return")
                    .force_3ds_challenge(true),
            )
            .await
            .unwrap();
        // Typed: these would not compile against a `Value`, and a model whose
        // field names drifted from the wire would fail to deserialize here.
        assert_eq!(out.authentication_id, "auth_1");
        assert_eq!(out.status, "started");
        assert_eq!(out.amount, 1000);
        assert_eq!(out.client_secret.as_deref(), Some("auth_1_secret"));
        // Unmodeled fields survive rather than being dropped.
        assert_eq!(out.extra["three_ds_server_id"], "srv_9");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/authentication");
        let body = seen[0].body_json();
        assert_eq!(body["amount"], 1000);
        assert_eq!(body["currency"], "USD");
        assert_eq!(body["return_url"], "https://example.com/return");
        assert_eq!(body["force_3ds_challenge"], true);
    }

    #[tokio::test]
    async fn check_eligibility_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(AUTH_JSON)]);
        client
            .authentication()
            .check_eligibility("auth/1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/authentication/auth%2F1/eligibility"
        );
        assert!(seen[0].body.is_none(), "eligibility takes no request body");
    }

    #[tokio::test]
    async fn authenticate_posts_its_open_body() {
        let (client, mock) = client_with(vec![Step::ok(AUTH_JSON)]);
        client
            .authentication()
            .authenticate("auth/1", &json!({"device_channel": "BRW"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/authentication/auth%2F1/authenticate"
        );
        assert_eq!(seen[0].body_json()["device_channel"], "BRW");
    }

    #[tokio::test]
    async fn sync_is_merchant_scoped_and_body_is_optional() {
        let (client, mock) = client_with(vec![Step::ok(AUTH_JSON), Step::ok(AUTH_JSON)]);
        let auth = client.authentication();
        auth.sync("merch/1", "auth_1", Some(&json!({"force": true})))
            .await
            .unwrap();
        auth.sync("merch/1", "auth_1", None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/authentication/merch%2F1/auth_1/sync"
        );
        assert_eq!(seen[0].body_json()["force"], true);
        assert!(seen[1].body.is_none(), "`None` params must send no body");
    }

    #[tokio::test]
    async fn redirect_is_merchant_scoped() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        client
            .authentication()
            .redirect("merch/1", "auth_1", &json!({"cres": "abc"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/authentication/merch%2F1/auth_1/redirect"
        );
        assert_eq!(seen[0].body_json()["cres"], "abc");
    }

    #[tokio::test]
    async fn token_and_eligibility_check_hit_their_paths() {
        let (client, mock) = client_with(vec![Step::ok("{}"), Step::ok("{}")]);
        let auth = client.authentication();
        auth.enabled_authn_methods_token("auth/1", &json!({"client_secret": "cs_1"}))
            .await
            .unwrap();
        auth.eligibility_check("auth/1", &json!({"card_number": "4242"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/authentication/auth%2F1/enabled-authn-methods-token"
        );
        assert_eq!(seen[0].body_json()["client_secret"], "cs_1");
        assert_eq!(seen[1].method, "POST");
        assert_eq!(
            seen[1].url,
            "https://api.test/authentication/auth%2F1/eligibility-check"
        );
        assert_eq!(seen[1].body_json()["card_number"], "4242");
    }

    /// Drift guard for `AUTHENTICATION_CREATE_REQUEST_NAMED`.
    #[test]
    fn authentication_create_request_named_fields_are_complete() {
        let req = AuthenticationCreateRequest {
            amount: 1000,
            currency: "USD".to_string(),
            authentication_id: Some("auth_1".to_string()),
            profile_id: Some("pro_1".to_string()),
            customer: Some(json!({"id": "cus_1"})),
            authentication_connector: Some("threedsecureio".to_string()),
            return_url: Some("https://example.com/return".to_string()),
            force_3ds_challenge: Some(true),
            psd2_sca_exemption_type: Some("low_value".to_string()),
            profile_acquirer_id: Some("acq_1".to_string()),
            payment_method_data: Some(json!({"card": {}})),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                AUTHENTICATION_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "AUTHENTICATION_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = AuthenticationCreateRequest::new(1000, "USD");
        req.extra.insert("currency".to_string(), json!("EUR"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("currency")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }
}