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
//! The `events` resource — webhook delivery events and their retry history.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::event::{
    EventDetailResponse, EventListResponse, EventManualTriggerResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// List events for a merchant.
    ///
    /// The envelope is `{ "events": [...], "total_count": n }`, not the
    /// `data`-keyed one the rest of the API uses — read
    /// [`events`](EventListResponse::events).
    pub async fn list(
        &self,
        merchant_id: &str,
        params: Option<&EventListParams>,
    ) -> Result<EventListResponse> {
        let path = format!("/events/{}", encode_segment(merchant_id));
        let bytes = match params {
            Some(p) => to_json_vec(p)?,
            None => to_json_vec(&Value::Object(Default::default()))?,
        };
        self.inner
            .request(HttpMethod::Post, &path, Some(&bytes), &[], None)
            .await
    }

    /// Fire an outgoing webhook event by hand.
    ///
    /// `POST /events/{merchant_id}/trigger`
    ///
    /// The payload is built from the object's current record and its status is
    /// then **overwritten** to agree with the `event_type` given — for the case
    /// where DeloPay's record is right and the merchant's shop never heard about
    /// it. The object's own state is neither checked nor changed, so this can
    /// also assert a state DeloPay's records contradict:
    /// [`object_status`](EventManualTriggerResponse::object_status) and
    /// [`status_overridden`](EventManualTriggerResponse::status_overridden) say
    /// which happened.
    ///
    /// Needs the `WebhookEventTrigger` permission, which is separate from the
    /// one authorizing [`retry_delivery`](Self::retry_delivery), and is
    /// **JWT-only**: authenticate the client with
    /// [`Delopay::with_jwt`](crate::Delopay::with_jwt), since an API key names
    /// no one and this route records who fired the event.
    pub async fn trigger(
        &self,
        merchant_id: &str,
        params: &EventManualTriggerRequest,
    ) -> Result<EventManualTriggerResponse> {
        let path = format!("/events/{}/trigger", encode_segment(merchant_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Fire an outgoing webhook event by hand, scoped to the shop the
    /// credential is bound to (`POST /events/profile/trigger`) — the shop twin
    /// of [`trigger`](Self::trigger).
    pub async fn trigger_by_profile(
        &self,
        params: &EventManualTriggerRequest,
    ) -> Result<EventManualTriggerResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/events/profile/trigger",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// List the delivery attempts made for a webhook event, newest first:
    /// each attempt with its event fields plus the request sent and the
    /// response received.
    ///
    /// `GET /events/{merchant_id}/{event_id}/attempts`
    pub async fn list_delivery_attempts(
        &self,
        merchant_id: &str,
        event_id: &str,
    ) -> Result<Vec<EventDetailResponse>> {
        let path = format!(
            "/events/{}/{}/attempts",
            encode_segment(merchant_id),
            encode_segment(event_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List events scoped to the shop (business profile) the credential
    /// belongs to — the same endpoint as [`list`](Self::list), narrowed.
    pub async fn list_by_profile(
        &self,
        params: Option<&EventListParams>,
    ) -> Result<EventListResponse> {
        let bytes = match params {
            Some(p) => to_json_vec(p)?,
            None => to_json_vec(&Value::Object(Default::default()))?,
        };
        self.inner
            .request(
                HttpMethod::Post,
                "/events/profile/list",
                Some(&bytes),
                &[],
                None,
            )
            .await
    }

    /// Retry delivery of a webhook event.
    pub async fn retry_delivery(
        &self,
        merchant_id: &str,
        event_id: &str,
    ) -> Result<EventDetailResponse> {
        let path = format!(
            "/events/{}/{}/retry",
            encode_segment(merchant_id),
            encode_segment(event_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }
}

/// Filters for [`Events::list`] and [`Events::list_by_profile`]. All fields are
/// optional; only the set ones are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct EventListParams {
    /// Only events created at or after this RFC 3339 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_after: Option<String>,
    /// Only events created at or before this RFC 3339 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_before: Option<String>,
    /// Page size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    /// Rows to skip.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<i64>,
    /// Only events about this object — a payment, refund, dispute, mandate,
    /// payout or subscription id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub object_id: Option<String>,
    /// One event by id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_id: Option<String>,
    /// Narrow to one shop. Refused on the profile-scoped route, which takes
    /// the shop from the credential.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Only these event classes, e.g. `"payments"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_classes: Option<Vec<String>>,
    /// Only these event types, e.g. `"payment_succeeded"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_types: Option<Vec<String>>,
    /// Only delivered (`true`) or undelivered (`false`) events.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_delivered: Option<bool>,
    /// Only these delivery kinds, e.g. `"manual_trigger"` for events a person
    /// fired by hand.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_attempts: Option<Vec<String>>,
}

impl EventListParams {
    /// Empty filters.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// The body of [`Events::trigger`] and [`Events::trigger_by_profile`].
#[derive(Debug, Clone, Serialize)]
pub struct EventManualTriggerRequest {
    /// The object to fire an event about: a payment or refund id.
    pub object_id: String,
    /// The event type to assert. The twelve payment and refund types — see
    /// [`ManualTriggerEventType`](crate::core::models::event::ManualTriggerEventType);
    /// the endpoint rejects the rest.
    pub event_type: String,
    /// Why it was fired. Recorded with the event.
    pub reason: String,
    /// The shop the object belongs to, when the route needs it named.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
}

impl EventManualTriggerRequest {
    /// Fire `event_type` about `object_id`, recording `reason`.
    pub fn new(
        object_id: impl Into<String>,
        event_type: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            object_id: object_id.into(),
            event_type: event_type.into(),
            reason: reason.into(),
            profile_id: None,
        }
    }

    /// Name the shop the object belongs to.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }
}

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

    #[tokio::test]
    async fn list_by_profile_posts_the_filter_body_to_the_profile_path() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"events":[]}"#)]);
        let params = EventListParams {
            limit: Some(10),
            event_classes: Some(vec!["payments".to_string()]),
            ..EventListParams::new()
        };
        client
            .events()
            .list_by_profile(Some(&params))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/events/profile/list");
        assert_eq!(seen[0].body_json()["event_classes"], json!(["payments"]));
        // Unset filters stay off the wire rather than going out as nulls: the
        // route is strict about the keys it accepts.
        assert!(seen[0].body_json().get("object_id").is_none());
    }

    #[tokio::test]
    async fn list_by_profile_sends_an_empty_object_when_given_no_params() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"events":[]}"#)]);
        client.events().list_by_profile(None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].body_json(), json!({}));
    }

    /// The list envelope is `events`, not `data`. Mutation: rename
    /// `EventListResponse::events` to read `data` — the row count goes to 0
    /// and the first assertion fails.
    #[tokio::test]
    async fn list_reads_the_events_keyed_envelope() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"events":[{"event_id":"evt_1","object_id":"pay_1","delivery_attempt":"manual_trigger"}],"total_count":1}"#,
        )]);
        let out = client.events().list("mer_1", None).await.unwrap();

        assert_eq!(out.events.len(), 1);
        assert_eq!(out.total_count, Some(1));
        assert_eq!(out.events[0].object_id.as_deref(), Some("pay_1"));
        assert_eq!(
            out.events[0].delivery_attempt.as_deref(),
            Some("manual_trigger")
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/events/mer_1");
    }

    /// Mutation: drop the `/trigger` suffix from the path, or send
    /// `profile_id` unconditionally — the URL assertion, then the body
    /// assertion, go red.
    #[tokio::test]
    async fn trigger_posts_the_manual_fire_to_the_merchant_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"event_id":"evt_1","object_status":"failed","status_overridden":true}"#,
        )]);
        let out = client
            .events()
            .trigger(
                "mer_1",
                &EventManualTriggerRequest::new(
                    "pay_1",
                    "payment_succeeded",
                    "processor confirmed out of band",
                ),
            )
            .await
            .unwrap();

        assert_eq!(out.status_overridden, Some(true));
        assert_eq!(out.object_status.as_deref(), Some("failed"));
        assert_eq!(out.event.event.event_id.as_deref(), Some("evt_1"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/events/mer_1/trigger");
        assert_eq!(seen[0].body_json()["event_type"], "payment_succeeded");
        assert_eq!(
            seen[0].body_json()["reason"],
            "processor confirmed out of band"
        );
        assert!(seen[0].body_json().get("profile_id").is_none());
    }

    /// The trigger routes are JWT-only, so a client carrying a dashboard token
    /// must send `Authorization: Bearer` and **no** `api-key`: presenting both
    /// leaves which credential the server honoured up to the server. Mutation:
    /// keep pushing `api-key` when a JWT is set — the second assertion fails.
    #[tokio::test]
    async fn a_jwt_client_triggers_with_a_bearer_and_no_api_key() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"status_overridden":false}"#)]);
        client
            .with_jwt("eyJhbGciOiJIUzI1NiJ9.dashboard.token")
            .events()
            .trigger(
                "mer_1",
                &EventManualTriggerRequest::new("pay_1", "payment_succeeded", "reconciled"),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].header("authorization"),
            Some("Bearer eyJhbGciOiJIUzI1NiJ9.dashboard.token")
        );
        assert_eq!(seen[0].header("api-key"), None);
    }

    /// Without a JWT the same call authenticates as it always did. Mutation:
    /// send the bearer unconditionally — the `authorization` assertion fails.
    #[tokio::test]
    async fn an_api_key_client_triggers_with_the_key_and_no_bearer() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"status_overridden":false}"#)]);
        client
            .events()
            .trigger(
                "mer_1",
                &EventManualTriggerRequest::new("pay_1", "payment_succeeded", "reconciled"),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("api-key"), Some("prd_test"));
        assert_eq!(seen[0].header("authorization"), None);
    }

    /// Mutation: point `trigger_by_profile` at `/events/profile/list` — the
    /// URL assertion fails.
    #[tokio::test]
    async fn trigger_by_profile_posts_to_the_profile_trigger_path() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"status_overridden":false}"#)]);
        client
            .events()
            .trigger_by_profile(
                &EventManualTriggerRequest::new("pay_1", "refund_succeeded", "manual")
                    .profile_id("pro_1"),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/events/profile/trigger");
        assert_eq!(seen[0].body_json()["profile_id"], "pro_1");
    }

    #[tokio::test]
    async fn list_delivery_attempts_gets_the_attempts_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"event_id":"evt_2","merchant_id":"mer_1","initial_attempt_id":"evt_1",
                 "delivery_attempt":"automatic_retry","is_delivery_successful":true,
                 "attempt_delivered":false,"withheld":null,
                 "request":{"body":"{}","headers":[]},
                 "response":{"status_code":500,"body":"boom"},"surprise_field":1}]"#,
        )]);
        let out = client
            .events()
            .list_delivery_attempts("mer_1", "evt_1")
            .await
            .unwrap();
        // The event fields decode: the old attempt shape left them all `None`.
        assert_eq!(out[0].event.event_id.as_deref(), Some("evt_2"));
        assert_eq!(out[0].event.is_delivery_successful, Some(true));
        assert_eq!(out[0].event.attempt_delivered, Some(false));
        assert_eq!(out[0].response.as_ref().unwrap()["status_code"], 500);
        assert!(out[0].withheld.is_none());
        assert_eq!(out[0].event.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/events/mer_1/evt_1/attempts");
    }
}