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
//! The `whop_resolution_cases` resource: Whop Resolution Center cases, a
//! buyer's claim before any chargeback.
//!
//! Cases are read and answered live through one Whop connector account and
//! environment, named on every call by `merchant_connector_id` and
//! `test_mode`. Every operation honours the caller's connector-account grants
//! and shop scope.

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::whop_case::{
    WhopResolutionCase, WhopResolutionCaseActionResponse, WhopResolutionCaseEventList,
    WhopResolutionCaseList,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// One page of cases, newest first. `GET /disputes/whop/cases`
    pub async fn list(
        &self,
        params: &WhopResolutionCaseListParams,
    ) -> Result<WhopResolutionCaseList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/disputes/whop/cases",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// One case as Whop reports it now. `GET /disputes/whop/cases/{case_id}`
    pub async fn retrieve(
        &self,
        case_id: &str,
        locator: &WhopResolutionCaseLocator,
    ) -> Result<WhopResolutionCase> {
        self.inner
            .request(
                HttpMethod::Get,
                &case_path(case_id),
                None,
                &locator.to_query(),
                None,
            )
            .await
    }

    /// A case's timeline, newest first.
    /// `GET /disputes/whop/cases/{case_id}/events`
    pub async fn events(
        &self,
        case_id: &str,
        params: &WhopResolutionCaseEventsParams,
    ) -> Result<WhopResolutionCaseEventList> {
        let path = format!("{}/events", case_path(case_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &params.to_query(), None)
            .await
    }

    /// Accept, deny, reply to or request information on a case. `accept`
    /// refunds the payment in full at Whop.
    ///
    /// Not retried after a network error or `5xx`. An `unknown` outcome, or a
    /// lost answer, is retried by calling again with the same `request_id`:
    /// Whop answers a retry of the same action with the original result.
    ///
    /// `POST /disputes/whop/cases/{case_id}/actions`
    pub async fn act(
        &self,
        case_id: &str,
        params: &WhopResolutionCaseActionRequest,
    ) -> Result<WhopResolutionCaseActionResponse> {
        params.validate()?;
        let path = format!("{}/actions", case_path(case_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }
}

/// `/disputes/whop/cases/{case_id}`, percent-encoded.
fn case_path(case_id: &str) -> String {
    format!("/disputes/whop/cases/{}", encode_segment(case_id))
}

fn push_locator(
    q: &mut Vec<(&'static str, String)>,
    merchant_connector_id: &str,
    test_mode: Option<bool>,
) {
    q.push(("merchant_connector_id", merchant_connector_id.to_string()));
    if let Some(v) = test_mode {
        q.push(("test_mode", v.to_string()));
    }
}

/// A Whop case's status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WhopResolutionCaseStatus {
    /// Waiting for the merchant.
    AwaitingMerchant,
    /// Waiting for the buyer.
    AwaitingCustomer,
    /// Under review by Whop.
    UnderReview,
    /// Closed.
    Closed,
}

impl WhopResolutionCaseStatus {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AwaitingMerchant => "awaiting_merchant",
            Self::AwaitingCustomer => "awaiting_customer",
            Self::UnderReview => "under_review",
            Self::Closed => "closed",
        }
    }
}

/// The Whop connector account and environment a case is read through.
#[derive(Debug, Clone, Default)]
pub struct WhopResolutionCaseLocator {
    /// The Whop connector account. Required.
    pub merchant_connector_id: String,
    /// `true` reads through the sandbox credentials. Defaults to live.
    pub test_mode: Option<bool>,
}

impl WhopResolutionCaseLocator {
    /// Read through `merchant_connector_id`'s live credentials.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            test_mode: None,
        }
    }

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

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        push_locator(&mut q, &self.merchant_connector_id, self.test_mode);
        q
    }
}

/// Filters for [`WhopResolutionCases::list`].
#[derive(Debug, Clone, Default)]
pub struct WhopResolutionCaseListParams {
    /// The Whop connector account. Required.
    pub merchant_connector_id: String,
    /// `true` reads through the sandbox credentials. Defaults to live.
    pub test_mode: Option<bool>,
    /// Only cases of this shop's payments.
    pub profile_id: Option<String>,
    /// Only cases in this status.
    pub status: Option<WhopResolutionCaseStatus>,
    /// Page size.
    pub limit: Option<u32>,
    /// The `next_cursor` of the previous page.
    pub cursor: Option<String>,
}

impl WhopResolutionCaseListParams {
    /// The first page of `merchant_connector_id`'s live cases.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            ..Default::default()
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        push_locator(&mut q, &self.merchant_connector_id, self.test_mode);
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = self.status {
            q.push(("status", v.as_str().to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = &self.cursor {
            q.push(("cursor", v.clone()));
        }
        q
    }
}

/// Parameters for [`WhopResolutionCases::events`].
#[derive(Debug, Clone, Default)]
pub struct WhopResolutionCaseEventsParams {
    /// The Whop connector account. Required.
    pub merchant_connector_id: String,
    /// `true` reads through the sandbox credentials. Defaults to live.
    pub test_mode: Option<bool>,
    /// Page size.
    pub limit: Option<u32>,
    /// The `next_cursor` of the previous page.
    pub cursor: Option<String>,
}

impl WhopResolutionCaseEventsParams {
    /// The first page of a case's events, read through
    /// `merchant_connector_id`'s live credentials.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            ..Default::default()
        }
    }

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

/// An action on a Whop case.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WhopResolutionCaseAction {
    /// Accept the claim, refunding the payment in full at Whop.
    Accept,
    /// Deny the claim. Needs a `message`.
    Deny,
    /// Reply to the buyer. Needs a `message`.
    Reply,
    /// Ask the buyer for more information.
    RequestInfo,
}

/// Parameters for [`WhopResolutionCases::act`].
#[derive(Debug, Clone, Serialize)]
pub struct WhopResolutionCaseActionRequest {
    /// The Whop connector account.
    pub merchant_connector_id: String,
    /// `true` acts through the sandbox credentials. Defaults to live.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// The action.
    pub action: WhopResolutionCaseAction,
    /// A client-generated id, reused for a retry of this exact action.
    pub request_id: String,
    /// Shown to the buyer. Required for `deny` and `reply`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// `accept` only: also end the buyer's Whop membership.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terminate_membership: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl WhopResolutionCaseActionRequest {
    /// Take `action` through `merchant_connector_id`'s live credentials, under
    /// `request_id`.
    pub fn new(
        merchant_connector_id: impl Into<String>,
        action: WhopResolutionCaseAction,
        request_id: impl Into<String>,
    ) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            test_mode: None,
            action,
            request_id: request_id.into(),
            message: None,
            terminate_membership: None,
            extra: serde_json::Map::new(),
        }
    }

    /// Act through the sandbox (`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 the message shown to the buyer.
    #[must_use]
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// With `accept`, also end the buyer's Whop membership.
    #[must_use]
    pub fn terminate_membership(mut self, terminate: bool) -> Self {
        self.terminate_membership = Some(terminate);
        self
    }
}

/// Names of `WhopResolutionCaseActionRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED: &[&str] = &[
    "merchant_connector_id",
    "test_mode",
    "action",
    "request_id",
    "message",
    "terminate_membership",
];

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

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

    const CASE_JSON: &str = r#"{
        "case_id": "rc_1", "merchant_connector_id": "mca_1", "test_mode": true,
        "profile_id": "pro_1", "payment_id": "pay_1", "attempt_id": null,
        "connector_payment_id": "pay_whop_1", "status": "awaiting_merchant",
        "reason": "product_not_received", "outcome": null, "refund": null,
        "escalated": false, "customer_appealed": false, "amount": "10.00",
        "currency": "USD", "response_due_at": "2026-01-05T00:00:00Z",
        "created_at": "2026-01-01T00:00:00Z", "updated_at": null,
        "product_id": null, "plan_id": null, "payment_method_type": "card",
        "card_brand": "visa", "card_last4": "4242", "buyer_name": "Jane Buyer",
        "buyer_username": "janeb", "buyer_email": "jane@example.com",
        "available_actions": ["accept", "deny", "reply"], "case_surprise": 1
    }"#;

    #[tokio::test]
    async fn list_sends_the_account_and_filters() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"cases":[{CASE_JSON}],"next_cursor":"c2","x":1}}"#
        ))]);
        let params = WhopResolutionCaseListParams {
            test_mode: Some(true),
            status: Some(WhopResolutionCaseStatus::AwaitingMerchant),
            limit: Some(10),
            cursor: Some("c1".to_string()),
            ..WhopResolutionCaseListParams::new("mca_1")
        };
        let page = client.whop_resolution_cases().list(&params).await.unwrap();
        assert_eq!(page.cases[0].case_id, "rc_1");
        assert_eq!(page.cases[0].extra["case_surprise"], 1);
        assert_eq!(page.next_cursor.as_deref(), Some("c2"));
        assert_eq!(page.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/whop/cases?merchant_connector_id=mca_1&test_mode=true\
             &status=awaiting_merchant&limit=10&cursor=c1"
        );
    }

    #[tokio::test]
    async fn retrieve_encodes_the_case_id_and_redacts_the_buyer() {
        let (client, mock) = client_with(vec![Step::ok(CASE_JSON)]);
        let case = client
            .whop_resolution_cases()
            .retrieve("rc/1", &WhopResolutionCaseLocator::new("mca_1"))
            .await
            .unwrap();
        assert_eq!(case.buyer_email.as_deref(), Some("jane@example.com"));
        assert_eq!(case.available_actions, ["accept", "deny", "reply"]);
        let printed = format!("{case:?}");
        assert!(!printed.contains("jane@example.com"));
        assert!(!printed.contains("Jane Buyer"));
        assert!(!printed.contains("janeb"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/whop/cases/rc%2F1?merchant_connector_id=mca_1"
        );
    }

    #[tokio::test]
    async fn events_gets_the_events_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"events":[{"event_id":"ev_1","action":"reply","reporter_type":"customer",
                "details":"where is it?","viewable_by_customer":true,"created_at":null,
                "attachments":[{"id":"att_1","filename":"receipt.png","content_type":"image/png","url":null}],
                "x":1}],"next_cursor":null}"#,
        )]);
        let params = WhopResolutionCaseEventsParams {
            test_mode: Some(false),
            limit: Some(5),
            ..WhopResolutionCaseEventsParams::new("mca_1")
        };
        let out = client
            .whop_resolution_cases()
            .events("rc_1", &params)
            .await
            .unwrap();
        assert_eq!(out.events[0].attachments[0].id, "att_1");
        assert_eq!(out.events[0].extra["x"], 1);
        assert!(out.next_cursor.is_none());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/whop/cases/rc_1/events?merchant_connector_id=mca_1\
             &test_mode=false&limit=5"
        );
    }

    #[tokio::test]
    async fn act_posts_the_action() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"request_id":"req_1","action":"deny","outcome":"submitted","case":{CASE_JSON},"x":1}}"#
        ))]);
        let req =
            WhopResolutionCaseActionRequest::new("mca_1", WhopResolutionCaseAction::Deny, "req_1")
                .test_mode(true)
                .message("delivered on time");
        let out = client
            .whop_resolution_cases()
            .act("rc_1", &req)
            .await
            .unwrap();
        assert_eq!(out.outcome, "submitted");
        assert_eq!(out.case.case_id, "rc_1");
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/whop/cases/rc_1/actions"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "merchant_connector_id": "mca_1",
                "test_mode": true,
                "action": "deny",
                "request_id": "req_1",
                "message": "delivered on time"
            })
        );
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn act_is_not_retried_on_5xx() {
        let (client, mock) = client_with_retries(
            vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
            2,
        );
        let req = WhopResolutionCaseActionRequest::new(
            "mca_1",
            WhopResolutionCaseAction::Accept,
            "req_1",
        );
        client
            .whop_resolution_cases()
            .act("rc_1", &req)
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 1);
    }

    /// Drift guard for `WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED`.
    #[test]
    fn whop_resolution_case_action_request_named_fields_are_complete() {
        let req = WhopResolutionCaseActionRequest::new(
            "mca_1",
            WhopResolutionCaseAction::Accept,
            "req_1",
        )
        .test_mode(true)
        .message("m")
        .terminate_membership(true);
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED.contains(&key.as_str()),
                "WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn act_validate_rejects_colliding_extra_key() {
        let mut req =
            WhopResolutionCaseActionRequest::new("mca_1", WhopResolutionCaseAction::Reply, "r");
        req.extra.insert("action".to_string(), json!("accept"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("action")),
            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..1)
            .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
            .whop_resolution_cases()
            .act(
                "rc_1",
                &WhopResolutionCaseActionRequest::new(
                    "mca_1",
                    WhopResolutionCaseAction::Accept,
                    "req_1",
                ),
            )
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 1);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }
}