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
//! HTTP integration tests against a local mock server (no real network / creds).
//! Exercises the client core: auth header, JSON body, idempotency, retries, and
//! error mapping.
#![cfg(feature = "client")]

use delopay::{
    Delopay, DelopayError, PaymentCreateRequest, PaymentListParams, RefundCreateRequest,
};
use serde_json::json;
use wiremock::matchers::{body_json, body_partial_json, header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn client(server: &MockServer) -> Delopay {
    // `.no_proxy()` is required, not cosmetic: the SDK honours `HTTP_PROXY` /
    // `HTTPS_PROXY` from the environment, and a developer machine in a
    // corporate network usually has them set without a loopback `NO_PROXY`.
    // Without this, every test here tries to CONNECT to the mock server via
    // that proxy and fails. Proxy behaviour has its own suite in
    // `tests/http_proxy.rs`, which configures a proxy explicitly.
    Delopay::builder("snd_test")
        .base_url(server.uri())
        .no_proxy()
        .build()
}

#[tokio::test]
async fn create_sends_auth_header_and_parses_response() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/payments"))
        .and(header("api-key", "snd_test"))
        .and(header("content-type", "application/json"))
        .and(body_partial_json(
            json!({"amount": 1999, "currency": "EUR"}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payment_id": "pay_1", "merchant_id": "mer_1",
            "status": "requires_payment_method", "amount": 1999, "currency": "EUR",
            "client_secret": "secret_x"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let p = client(&server)
        .payments()
        .create(&PaymentCreateRequest::new(1999, "EUR"))
        .await
        .unwrap();

    assert_eq!(p.payment_id, "pay_1");
    assert_eq!(p.merchant_id, "mer_1");
    assert_eq!(p.client_secret.as_deref(), Some("secret_x"));
}

#[tokio::test]
async fn create_idempotent_sends_idempotency_key_header() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/payments"))
        .and(header("idempotency-key", "order_9"))
        .and(body_partial_json(json!({"amount": 1, "currency": "EUR"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payment_id": "pay_1", "merchant_id": "m", "status": "x", "amount": 1, "currency": "EUR"
        })))
        .expect(1)
        .mount(&server)
        .await;

    client(&server)
        .payments()
        .create_idempotent(&PaymentCreateRequest::new(1, "EUR"), "order_9")
        .await
        .unwrap();
}

#[tokio::test]
async fn maps_401_to_authentication_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/payments/pay_x"))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": { "type": "authentication_error", "code": "AUTH_01", "message": "invalid api key" }
        })))
        .mount(&server)
        .await;

    let err = client(&server)
        .payments()
        .retrieve("pay_x")
        .await
        .unwrap_err();
    match err {
        DelopayError::Authentication(e) => assert_eq!(e.code, "AUTH_01"),
        other => panic!("expected authentication error, got {other:?}"),
    }
}

#[tokio::test]
async fn parses_error_envelope_with_request_id() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/payments"))
        .and(body_partial_json(json!({"amount": 1, "currency": "EUR"})))
        .respond_with(
            ResponseTemplate::new(400)
                .insert_header("x-request-id", "req_123")
                .set_body_json(json!({
                    "error": { "type": "invalid_request", "code": "IR_01", "message": "amount too small" }
                })),
        )
        .mount(&server)
        .await;

    let err = client(&server)
        .payments()
        .create(&PaymentCreateRequest::new(1, "EUR"))
        .await
        .unwrap_err();
    match err {
        DelopayError::Api(e) => {
            assert_eq!(e.status, 400);
            assert_eq!(e.code, "IR_01");
            assert_eq!(e.error_type, "invalid_request");
            assert_eq!(e.request_id.as_deref(), Some("req_123"));
        }
        other => panic!("expected api error, got {other:?}"),
    }
}

#[tokio::test]
async fn retries_idempotent_get_on_429_then_succeeds() {
    let server = MockServer::start().await;
    // First call returns 429 (mounted first = higher precedence, served
    // exactly once). wiremock matches mounted mocks in mount order and picks
    // the first satisfiable one, so this must be mounted before the 200
    // fallback or it would never be hit. `.expect(1)` makes that assumption
    // self-enforcing: if this mock is never served, the test fails loudly
    // instead of silently passing via the fallback.
    Mock::given(method("GET"))
        .and(path("/payments/pay_1"))
        .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
        .up_to_n_times(1)
        .expect(1)
        .mount(&server)
        .await;
    // Fallback 200, served on the retry (mounted second = lower precedence).
    Mock::given(method("GET"))
        .and(path("/payments/pay_1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payment_id": "pay_1", "merchant_id": "m", "status": "succeeded",
            "amount": 500, "currency": "EUR"
        })))
        .mount(&server)
        .await;

    let p = client(&server).payments().retrieve("pay_1").await.unwrap();
    assert_eq!(p.status, "succeeded");
}

#[tokio::test]
async fn list_sends_query_and_parses_envelope() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/payments/list"))
        .and(query_param("limit", "10"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [{
                "payment_id": "pay_1", "merchant_id": "m", "status": "succeeded",
                "amount": 1, "currency": "EUR"
            }],
            "total_count": 1
        })))
        .mount(&server)
        .await;

    let params = PaymentListParams {
        limit: Some(10),
        ..Default::default()
    };
    let list = client(&server)
        .payments()
        .list(Some(&params))
        .await
        .unwrap();
    assert_eq!(list.data.len(), 1);
    assert_eq!(list.data[0].payment_id, "pay_1");
    assert_eq!(list.total_count, Some(1));
}

#[tokio::test]
async fn refund_create_hits_refunds_endpoint() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/refunds"))
        .and(body_partial_json(
            json!({"payment_id": "pay_1", "amount": 500}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "refund_id": "ref_1", "payment_id": "pay_1", "amount": 500,
            "currency": "EUR", "status": "pending", "connector": "stripe"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let r = client(&server)
        .refunds()
        .create(&RefundCreateRequest::new("pay_1").amount(500))
        .await
        .unwrap();
    assert_eq!(r.refund_id, "ref_1");
    assert_eq!(r.status, "pending");
}

/// Regression test for the `struct -> serde_json::Value -> bytes` ->
/// `struct -> bytes` change: a `BTreeMap` intermediate used to merge/dedup
/// keys silently; direct serialization does not. `body_json` requires the
/// wire body to match *exactly*, so this fails just as loudly if a field
/// that should be omitted by `skip_serializing_if` (e.g. `confirm`,
/// `description`, ...) leaks onto the wire as `null` or otherwise.
#[tokio::test]
async fn create_sends_exact_body_with_only_set_fields_present() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/payments"))
        .and(body_json(json!({
            "amount": 1999,
            "currency": "EUR",
            "payment_link": true
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payment_id": "pay_1", "merchant_id": "m", "status": "x",
            "amount": 1999, "currency": "EUR"
        })))
        .expect(1)
        .mount(&server)
        .await;

    client(&server)
        .payments()
        .create(&PaymentCreateRequest::new(1999, "EUR").payment_link(true))
        .await
        .unwrap();
}

/// An `extra` key that collides with a named field must be rejected by
/// `validate()` before serialization, so no request ever reaches the wire.
/// No mock is mounted for `/payments` here — if the SDK went ahead and
/// serialized/sent the request anyway, the unmatched call would surface as
/// a transport/API error instead of `InvalidRequest`, so the assertion
/// below also proves the short-circuit happened.
#[tokio::test]
async fn create_with_colliding_extra_key_is_rejected_before_any_request_is_sent() {
    let server = MockServer::start().await;

    let mut params = PaymentCreateRequest::new(1999, "EUR");
    params.extra.insert("amount".to_string(), json!(999));

    let err = client(&server)
        .payments()
        .create(&params)
        .await
        .unwrap_err();
    assert!(
        matches!(err, DelopayError::InvalidRequest(_)),
        "expected InvalidRequest, got {err:?}"
    );
}

// ---------------------------------------------------------------------------
// Merchant-surface expansion (payment links, subscriptions, disputes, payouts)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn payment_link_retrieve_decodes_the_typed_response() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/payment-link/plink_1"))
        .and(header("api-key", "snd_test"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payment_link_id": "plink_1",
            "merchant_id": "mer_1",
            "link_to_pay": "https://checkout.test/pay/plink_1",
            "amount": 1999,
            "created_at": "2026-09-01T00:00:00Z",
            "expiry": "2026-09-03T00:00:00Z",
            "description": "Order 1001",
            "status": "active",
            "currency": "EUR",
            "secure_link": "https://checkout.test/s/abc"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let link = client(&server)
        .payment_links()
        .retrieve("plink_1")
        .await
        .unwrap();
    assert_eq!(link.payment_link_id, "plink_1");
    assert_eq!(link.merchant_id, "mer_1");
    assert_eq!(link.link_to_pay, "https://checkout.test/pay/plink_1");
    assert_eq!(link.status, "active");
    assert_eq!(
        link.secure_link.as_deref(),
        Some("https://checkout.test/s/abc")
    );
}

#[tokio::test]
async fn subscription_create_and_confirm_sends_profile_header_and_decodes_redirect() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/subscriptions"))
        .and(header("x-profile-id", "pro_1"))
        .and(body_partial_json(json!({
            "item_price_id": "price_1",
            "customer_id": "cus_1",
            "payment_details": {"payment_method": "card"}
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": "sub_1", "status": "pending",
            "redirect_url": "https://paypal.test/approve"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = delopay::CreateAndConfirmSubscriptionRequest {
        item_price_id: Some("price_1".to_string()),
        customer_id: "cus_1".to_string(),
        payment_details: delopay::SubscriptionPaymentDetails {
            payment_method: Some("card".to_string()),
            ..Default::default()
        },
        ..Default::default()
    };
    let sub = client(&server)
        .subscriptions()
        .with_profile_id("pro_1")
        .create_and_confirm(&req)
        .await
        .unwrap();
    assert_eq!(sub.id, "sub_1");
    assert_eq!(
        sub.redirect_url.as_deref(),
        Some("https://paypal.test/approve")
    );
}

#[tokio::test]
async fn dispute_attach_evidence_is_a_put_with_a_json_body() {
    let server = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/disputes/evidence"))
        .and(body_json(json!({
            "receipt": "file_receipt",
            "dispute_id": "dp_1"
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "dispute_id": "dp_1", "payment_id": "pay_1", "attempt_id": "att_1",
            "amount": "500", "currency": "EUR", "dispute_stage": "dispute",
            "dispute_status": "dispute_challenged", "connector": "stripe",
            "connector_status": "under_review", "connector_dispute_id": "du_1",
            "is_already_refunded": false
        })))
        .expect(1)
        .mount(&server)
        .await;

    let mut req = delopay::DisputeEvidenceRequest {
        receipt: Some("file_receipt".to_string()),
        ..Default::default()
    };
    req.extra.insert("dispute_id".to_string(), json!("dp_1"));
    let dispute = client(&server)
        .disputes()
        .attach_evidence(&req)
        .await
        .unwrap();
    assert_eq!(dispute.dispute_status, "dispute_challenged");
}

#[tokio::test]
async fn payout_update_is_a_put_to_the_payout_path() {
    let server = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/payouts/po_1"))
        .and(body_partial_json(json!({"amount": 900})))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payout_id": "po_1", "merchant_id": "mer_1", "amount": 900,
            "currency": "EUR", "status": "requires_confirmation"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = delopay::PayoutUpdateRequest {
        amount: Some(900),
        ..Default::default()
    };
    let payout = client(&server)
        .payouts()
        .update("po_1", &req)
        .await
        .unwrap();
    assert_eq!(payout.amount, 900);
}

#[tokio::test]
async fn payment_attempts_list_decodes_the_envelope() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/payments/pay_1/attempts"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "size": 2,
            "data": [
                {"attempt_id": "att_1", "status": "failure",
                 "connector": "stripe", "unified_message": "Insufficient funds"},
                {"attempt_id": "att_2", "status": "charged", "connector": "adyen"}
            ]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let attempts = client(&server)
        .payments()
        .list_attempts("pay_1")
        .await
        .unwrap();
    assert_eq!(attempts.size, Some(2));
    assert_eq!(
        attempts.data[0].unified_message.as_deref(),
        Some("Insufficient funds")
    );
    assert_eq!(attempts.data[1].connector.as_deref(), Some("adyen"));
}

#[tokio::test]
async fn ephemeral_key_create_round_trips() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/ephemeral-keys"))
        .and(body_json(json!({"customer_id": "cus_1"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "customer_id": "cus_1", "created_at": 1700000000i64,
            "expires": 1700003600i64, "secret": "epk_secret"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let key = client(&server)
        .ephemeral_keys()
        .create("cus_1")
        .await
        .unwrap();
    assert_eq!(key.secret, "epk_secret");
}

/// A router predating the pane-catalogue endpoint answers 404, and the SDK
/// hands that back as an error rather than substituting
/// `STRIPE_FALLBACK_PANE_CATALOG` for it.
///
/// That is the contract, not an oversight: degrading is a policy the caller
/// owns. A client that silently answered a 404 with Stripe's list would tell a
/// merchant on another connector that Stripe's methods are available, and the
/// caller could no longer tell "this router has no catalogue" from "this
/// router says Stripe". The doc on `Connectors::panes_catalog` therefore tells
/// the caller to degrade; it does not do it for them.
///
/// This test exists so that a future change adding auto-degradation is a
/// deliberate one — it will fail here first.
#[tokio::test]
async fn panes_catalog_propagates_404_rather_than_degrading_for_the_caller() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/account/mer_1/connectors/native-panes/catalog"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": {"type": "invalid_request", "code": "HE_02",
                      "message": "Unrecognized request URL"}
        })))
        .expect(1)
        .mount(&server)
        .await;

    let err = client(&server)
        .connectors()
        .panes_catalog("mer_1")
        .await
        .expect_err("a 404 must reach the caller, who decides whether to degrade");

    match err {
        DelopayError::Api(api) => assert_eq!(api.status, 404),
        other => panic!("expected an API error carrying the status, got {other:?}"),
    }

    // And the constant the caller degrades *to* is reachable without a client,
    // so the fallback path does not itself depend on the endpoint answering.
    assert!(
        !delopay::panes::STRIPE_FALLBACK_PANE_CATALOG
            .methods
            .is_empty()
    );
}