delopay 0.4.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
//! The subscription models: subscriptions, their invoices, purchasable items,
//! and cost estimates.

use std::fmt;

use serde::Deserialize;
use serde_json::Value;

use crate::core::models::common::{
    Currency, IntentStatus, InvoiceStatus, PaymentMethodType, SubscriptionPeriodUnit,
    SubscriptionStatus,
};

/// A subscription, as returned by create / retrieve / update / list.
///
/// The confirm and create-and-confirm flows return
/// [`ConfirmSubscriptionResponse`] instead, which additionally carries the
/// billing-processor subscription ID and the buyer-approval `redirect_url`.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Current lifecycle status.
    pub status: SubscriptionStatus,

    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Plan the subscription is on.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// Price the subscription is billed at.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Shop (business profile) ID the subscription belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Short-lived token used by client SDKs to authenticate confirm calls.
    /// Do not log or share it. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Coupon applied at creation, if any.
    #[serde(default)]
    pub coupon_code: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment leg for the current billing cycle, once a charge was attempted.
    #[serde(default)]
    pub payment: Option<SubscriptionPaymentData>,
    /// Invoice for the current billing cycle.
    #[serde(default)]
    pub invoice: Option<SubscriptionInvoice>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `client_secret` lets a client SDK confirm
// this subscription, so it is a bearer credential. Whether one was issued
// stays visible (`Some("[redacted]")` vs `None`) because that is usually the
// thing being debugged. Only the modeled field is covered -- `extra` prints
// in full.
impl fmt::Debug for SubscriptionResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubscriptionResponse")
            .field("id", &self.id)
            .field("status", &self.status)
            .field("merchant_reference_id", &self.merchant_reference_id)
            .field("plan_id", &self.plan_id)
            .field("item_price_id", &self.item_price_id)
            .field("profile_id", &self.profile_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("merchant_id", &self.merchant_id)
            .field("coupon_code", &self.coupon_code)
            .field("customer_id", &self.customer_id)
            .field("payment", &self.payment)
            .field("invoice", &self.invoice)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Returned by the create-and-confirm and confirm subscription calls.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConfirmSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Current lifecycle status.
    pub status: SubscriptionStatus,

    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Plan the subscription is on.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// Price the subscription is billed at.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Coupon applied, if any.
    #[serde(default)]
    pub coupon: Option<String>,
    /// Shop (business profile) ID the subscription belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment leg for the first billing cycle.
    #[serde(default)]
    pub payment: Option<SubscriptionPaymentData>,
    /// Invoice for the first billing cycle.
    #[serde(default)]
    pub invoice: Option<SubscriptionInvoice>,
    /// Subscription ID on the billing processor (Stripe Billing / PayPal).
    #[serde(default)]
    pub billing_processor_subscription_id: Option<String>,
    /// URL the customer must be redirected to in order to approve the
    /// subscription, for billing processors that require buyer approval (e.g.
    /// PayPal). `None` for processors that activate server-side.
    #[serde(default)]
    pub redirect_url: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by `Subscriptions::pause`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PauseSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Status after the pause took effect (or was scheduled).
    pub status: SubscriptionStatus,
    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// ISO 8601 timestamp the subscription was (or will be) paused at.
    #[serde(default)]
    pub paused_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by `Subscriptions::resume`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ResumeSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Status after resuming.
    pub status: SubscriptionStatus,
    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// ISO 8601 timestamp of the next billing cycle.
    #[serde(default)]
    pub next_billing_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by `Subscriptions::cancel`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CancelSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Status after the cancellation took effect (or was scheduled).
    pub status: SubscriptionStatus,
    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Customer the subscription billed.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// ISO 8601 timestamp the subscription was (or will be) cancelled at.
    #[serde(default)]
    pub cancelled_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Payment leg attached to a subscription's current billing cycle, present
/// once a charge has been attempted.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionPaymentData {
    /// The payment intent charging this cycle.
    pub payment_id: String,
    /// Status of that payment intent.
    pub status: IntentStatus,
    /// Amount in minor units.
    #[serde(default)]
    pub amount: Option<i64>,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Next action to drive on the client (redirect, render QR, etc.).
    #[serde(default)]
    pub next_action: Option<Value>,
    /// Client secret for client-side confirmation. Do not log or share it:
    /// it authorises completing this charge. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Gateway error code, if the charge failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, if the charge failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Payment method sub-type used.
    #[serde(default)]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written for the same reason as `SubscriptionResponse`: this
// `client_secret` confirms the cycle's payment.
impl fmt::Debug for SubscriptionPaymentData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubscriptionPaymentData")
            .field("payment_id", &self.payment_id)
            .field("status", &self.status)
            .field("amount", &self.amount)
            .field("currency", &self.currency)
            .field("next_action", &self.next_action)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("payment_method_type", &self.payment_method_type)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A single invoice raised for one billing cycle of a subscription.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionInvoice {
    /// Unique invoice ID.
    pub id: String,
    /// The subscription this invoice bills.
    pub subscription_id: String,
    /// Amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Invoice status.
    pub status: InvoiceStatus,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Customer billed.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment intent charging this invoice, once one exists.
    #[serde(default)]
    pub payment_intent_id: Option<String>,
    /// Payment method charged.
    #[serde(default)]
    pub payment_method_id: Option<String>,
    /// This invoice's ID on the billing processor (Stripe Billing / PayPal).
    #[serde(default)]
    pub billing_processor_invoice_id: Option<String>,
    /// Connector (billing processor) the invoice was raised through.
    #[serde(default)]
    pub provider_name: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A purchasable price option for a subscription item (plan or addon).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionItemPrice {
    /// Unique price ID (pass as `item_price_id` when creating a subscription).
    pub price_id: String,
    /// Amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Plan or addon ID this price belongs to.
    #[serde(default)]
    pub item_id: Option<String>,
    /// Billing interval unit (`"Day"`, `"Week"`, `"Month"`, `"Year"`).
    #[serde(default)]
    pub interval: Option<SubscriptionPeriodUnit>,
    /// Number of interval units per billing cycle.
    #[serde(default)]
    pub interval_count: Option<i64>,
    /// Trial length, when the price includes one.
    #[serde(default)]
    pub trial_period: Option<i64>,
    /// Unit of `trial_period`.
    #[serde(default)]
    pub trial_period_unit: Option<SubscriptionPeriodUnit>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A subscription item (plan or addon) with its available prices, as returned
/// by `Subscriptions::items`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionItem {
    /// Unique item ID.
    pub item_id: String,
    /// Display name.
    pub name: String,
    /// Description, when set.
    #[serde(default)]
    pub description: Option<String>,
    /// Available prices for this item. Named `price_id` on the wire.
    #[serde(default, rename = "price_id")]
    pub prices: Vec<SubscriptionItemPrice>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A single line of a subscription cost estimate.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionLineItem {
    /// Item this line bills.
    pub item_id: String,
    /// Item type, e.g. `"plan"`, `"addon"`.
    pub item_type: String,
    /// Line description.
    #[serde(default)]
    pub description: Option<String>,
    /// Amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Quantity billed.
    #[serde(default)]
    pub quantity: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Cost estimate for a subscription before creating it, as returned by
/// `Subscriptions::estimate`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionEstimateResponse {
    /// Total amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Plan estimated.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// Price estimated.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Coupon applied to the estimate.
    #[serde(default)]
    pub coupon_code: Option<String>,
    /// Customer the estimate was computed for.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Line-by-line breakdown.
    #[serde(default)]
    pub line_items: Vec<SubscriptionLineItem>,
    /// Billing interval unit, when the connector exposes it.
    #[serde(default)]
    pub interval: Option<SubscriptionPeriodUnit>,
    /// Number of interval units per cycle, when known.
    #[serde(default)]
    pub interval_count: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Kills a `Debug` that prints `&self.client_secret` on the subscription.
    #[test]
    fn subscription_response_debug_redacts_the_client_secret() {
        let res: SubscriptionResponse = serde_json::from_str(
            r#"{"id":"sub_1","status":"active","client_secret":"sub_1_secret_xyz"}"#,
        )
        .unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("sub_1_secret_xyz"));
        assert!(printed.contains("client_secret: Some(\"[redacted]\")"));
        assert!(printed.contains("sub_1"));
    }

    /// Kills a `Debug` that hard-codes the redaction marker.
    #[test]
    fn subscription_response_debug_shows_none_when_no_client_secret() {
        let res: SubscriptionResponse =
            serde_json::from_str(r#"{"id":"sub_1","status":"active"}"#).unwrap();
        assert!(format!("{res:?}").contains("client_secret: None"));
    }

    /// The nested payment leg carries its own secret; a redaction on the outer
    /// struct alone would still leak it, since `payment` is printed whole.
    #[test]
    fn subscription_payment_data_debug_redacts_the_client_secret() {
        let res: SubscriptionResponse = serde_json::from_str(
            r#"{"id":"sub_1","status":"active","payment":{"payment_id":"pay_1",
                "status":"requires_confirmation","client_secret":"pay_1_secret_nested"}}"#,
        )
        .unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("pay_1_secret_nested"));
        assert!(printed.contains("pay_1"));
    }

    #[test]
    fn subscription_payment_data_debug_shows_none_when_no_client_secret() {
        let data: SubscriptionPaymentData =
            serde_json::from_str(r#"{"payment_id":"pay_1","status":"succeeded"}"#).unwrap();
        assert!(format!("{data:?}").contains("client_secret: None"));
    }
}