shopify-sdk 1.0.0

A Rust SDK for the Shopify 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
//! ApplicationCharge resource implementation.
//!
//! This module provides the [`ApplicationCharge`] resource for managing one-time
//! charges in Shopify apps. Application charges are used to bill merchants
//! for one-time purchases within an app.
//!
//! # API Endpoints
//!
//! - `GET /application_charges.json` - List all application charges
//! - `POST /application_charges.json` - Create a new application charge
//! - `GET /application_charges/{id}.json` - Retrieve a single application charge
//!
//! Note: Application charges cannot be updated or deleted after creation.
//!
//! # Example
//!
//! ```rust,ignore
//! use shopify_sdk::rest::{RestResource, ResourceResponse};
//! use shopify_sdk::rest::resources::v2025_10::{ApplicationCharge, ApplicationChargeListParams};
//!
//! // Create a new application charge
//! let charge = ApplicationCharge {
//!     name: Some("Super Widget".to_string()),
//!     price: Some("9.99".to_string()),
//!     return_url: Some("https://myapp.com/charge-callback".to_string()),
//!     test: Some(true), // Test charges don't actually bill
//!     ..Default::default()
//! };
//! let saved = charge.save(&client).await?;
//!
//! // Redirect merchant to the confirmation_url for approval
//! if let Some(url) = saved.confirmation_url.as_ref() {
//!     println!("Redirect merchant to: {}", url);
//! }
//!
//! // Check charge status
//! if saved.is_active() {
//!     println!("Charge was accepted!");
//! }
//!
//! // List all charges
//! let charges = ApplicationCharge::all(&client, None).await?;
//! ```

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::rest::{ResourceOperation, ResourcePath, RestResource};
use crate::HttpMethod;

use super::common::{ChargeCurrency, ChargeStatus};

/// A one-time application charge.
///
/// Application charges allow apps to bill merchants for one-time purchases.
/// After creating a charge, redirect the merchant to the `confirmation_url`
/// for them to approve the charge.
///
/// # Charge Lifecycle
///
/// 1. App creates a charge via POST
/// 2. App redirects merchant to `confirmation_url`
/// 3. Merchant approves or declines the charge
/// 4. Merchant is redirected back to the app's `return_url`
/// 5. App checks the charge status
///
/// # Test Charges
///
/// Set `test: true` to create test charges that don't actually bill.
/// Test charges are automatically approved when created on development stores.
///
/// # Fields
///
/// ## Read-Only Fields
/// - `id` - The unique identifier of the charge
/// - `confirmation_url` - The URL to redirect merchant for approval
/// - `status` - The current status of the charge
/// - `currency` - The currency object with the currency code
/// - `created_at` - When the charge was created
/// - `updated_at` - When the charge was last updated
///
/// ## Writable Fields
/// - `name` - The name of the charge (displayed to merchant)
/// - `price` - The price of the charge
/// - `return_url` - The URL to redirect after merchant action
/// - `test` - Whether this is a test charge
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct ApplicationCharge {
    /// The unique identifier of the application charge.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub id: Option<u64>,

    /// The name of the application charge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// The price of the application charge.
    /// Must be a string representing the monetary amount (e.g., "9.99").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<String>,

    /// The current status of the charge.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub status: Option<ChargeStatus>,

    /// Whether this is a test charge.
    /// Test charges don't actually bill the merchant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test: Option<bool>,

    /// The URL to redirect the merchant after they approve/decline the charge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,

    /// The URL where the merchant can approve/decline the charge.
    /// Read-only field, populated after creating the charge.
    #[serde(skip_serializing)]
    pub confirmation_url: Option<String>,

    /// The currency information for the charge.
    /// Read-only field containing the currency code.
    #[serde(skip_serializing)]
    pub currency: Option<ChargeCurrency>,

    /// When the charge was created.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub created_at: Option<DateTime<Utc>>,

    /// When the charge was last updated.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub updated_at: Option<DateTime<Utc>>,
}

impl ApplicationCharge {
    /// Returns `true` if the charge is active (approved and billed).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if charge.is_active() {
    ///     println!("Charge has been paid!");
    /// }
    /// ```
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.status.as_ref().map_or(false, ChargeStatus::is_active)
    }

    /// Returns `true` if the charge is pending merchant approval.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if charge.is_pending() {
    ///     println!("Waiting for merchant approval");
    /// }
    /// ```
    #[must_use]
    pub fn is_pending(&self) -> bool {
        self.status.as_ref().map_or(false, ChargeStatus::is_pending)
    }

    /// Returns `true` if this is a test charge.
    ///
    /// Test charges don't actually bill the merchant and are
    /// automatically approved on development stores.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if charge.is_test() {
    ///     println!("This is a test charge");
    /// }
    /// ```
    #[must_use]
    pub fn is_test(&self) -> bool {
        self.test.unwrap_or(false)
    }
}

impl RestResource for ApplicationCharge {
    type Id = u64;
    type FindParams = ApplicationChargeFindParams;
    type AllParams = ApplicationChargeListParams;
    type CountParams = ();

    const NAME: &'static str = "ApplicationCharge";
    const PLURAL: &'static str = "application_charges";

    /// Paths for the ApplicationCharge resource.
    ///
    /// Note: ApplicationCharge has limited CRUD - no Update or Delete operations.
    const PATHS: &'static [ResourcePath] = &[
        ResourcePath::new(
            HttpMethod::Get,
            ResourceOperation::Find,
            &["id"],
            "application_charges/{id}",
        ),
        ResourcePath::new(
            HttpMethod::Get,
            ResourceOperation::All,
            &[],
            "application_charges",
        ),
        ResourcePath::new(
            HttpMethod::Post,
            ResourceOperation::Create,
            &[],
            "application_charges",
        ),
        // No Update or Delete paths - charges cannot be modified after creation
    ];

    fn get_id(&self) -> Option<Self::Id> {
        self.id
    }
}

/// Parameters for finding a single application charge.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct ApplicationChargeFindParams {
    /// Comma-separated list of fields to include in the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<String>,
}

/// Parameters for listing application charges.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct ApplicationChargeListParams {
    /// Maximum number of results to return (default: 50, max: 250).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,

    /// Return charges after this ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since_id: Option<u64>,

    /// Comma-separated list of fields to include in the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rest::{get_path, ResourceOperation};

    #[test]
    fn test_application_charge_serialization() {
        let charge = ApplicationCharge {
            id: Some(12345),
            name: Some("Pro Widget".to_string()),
            price: Some("19.99".to_string()),
            status: Some(ChargeStatus::Pending),
            test: Some(true),
            return_url: Some("https://myapp.com/callback".to_string()),
            confirmation_url: Some("https://shop.myshopify.com/confirm".to_string()),
            currency: Some(ChargeCurrency::new("USD")),
            created_at: Some(
                DateTime::parse_from_rfc3339("2024-01-15T10:30:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
            ),
            updated_at: Some(
                DateTime::parse_from_rfc3339("2024-01-15T10:35:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
            ),
        };

        let json = serde_json::to_string(&charge).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // Writable fields should be present
        assert_eq!(parsed["name"], "Pro Widget");
        assert_eq!(parsed["price"], "19.99");
        assert_eq!(parsed["test"], true);
        assert_eq!(parsed["return_url"], "https://myapp.com/callback");

        // Read-only fields should be omitted
        assert!(parsed.get("id").is_none());
        assert!(parsed.get("status").is_none());
        assert!(parsed.get("confirmation_url").is_none());
        assert!(parsed.get("currency").is_none());
        assert!(parsed.get("created_at").is_none());
        assert!(parsed.get("updated_at").is_none());
    }

    #[test]
    fn test_application_charge_deserialization() {
        let json = r#"{
            "id": 675931192,
            "name": "Super Duper Expensive action",
            "price": "100.00",
            "status": "active",
            "test": false,
            "return_url": "https://super-duper.shopifyapps.com/",
            "confirmation_url": "https://jsmith.myshopify.com/admin/charges/675931192/confirm_application_charge",
            "currency": {
                "currency": "USD"
            },
            "created_at": "2024-01-15T10:30:00Z",
            "updated_at": "2024-01-15T10:35:00Z"
        }"#;

        let charge: ApplicationCharge = serde_json::from_str(json).unwrap();

        assert_eq!(charge.id, Some(675931192));
        assert_eq!(
            charge.name,
            Some("Super Duper Expensive action".to_string())
        );
        assert_eq!(charge.price, Some("100.00".to_string()));
        assert_eq!(charge.status, Some(ChargeStatus::Active));
        assert_eq!(charge.test, Some(false));
        assert_eq!(
            charge.return_url,
            Some("https://super-duper.shopifyapps.com/".to_string())
        );
        assert!(charge.confirmation_url.is_some());
        assert_eq!(charge.currency.as_ref().unwrap().code(), Some("USD"));
        assert!(charge.created_at.is_some());
        assert!(charge.updated_at.is_some());
    }

    #[test]
    fn test_application_charge_convenience_methods() {
        // Test is_active
        let active_charge = ApplicationCharge {
            status: Some(ChargeStatus::Active),
            ..Default::default()
        };
        assert!(active_charge.is_active());
        assert!(!active_charge.is_pending());

        // Test is_pending
        let pending_charge = ApplicationCharge {
            status: Some(ChargeStatus::Pending),
            ..Default::default()
        };
        assert!(pending_charge.is_pending());
        assert!(!pending_charge.is_active());

        // Test is_test
        let test_charge = ApplicationCharge {
            test: Some(true),
            ..Default::default()
        };
        assert!(test_charge.is_test());

        let non_test_charge = ApplicationCharge {
            test: Some(false),
            ..Default::default()
        };
        assert!(!non_test_charge.is_test());

        // Test default (no test field)
        let default_charge = ApplicationCharge::default();
        assert!(!default_charge.is_test());
        assert!(!default_charge.is_active());
        assert!(!default_charge.is_pending());
    }

    #[test]
    fn test_application_charge_paths() {
        // Find path
        let find_path = get_path(
            ApplicationCharge::PATHS,
            ResourceOperation::Find,
            &["id"],
        );
        assert!(find_path.is_some());
        assert_eq!(find_path.unwrap().template, "application_charges/{id}");

        // All path
        let all_path = get_path(ApplicationCharge::PATHS, ResourceOperation::All, &[]);
        assert!(all_path.is_some());
        assert_eq!(all_path.unwrap().template, "application_charges");

        // Create path
        let create_path = get_path(ApplicationCharge::PATHS, ResourceOperation::Create, &[]);
        assert!(create_path.is_some());
        assert_eq!(create_path.unwrap().template, "application_charges");
        assert_eq!(create_path.unwrap().http_method, HttpMethod::Post);

        // No Update path
        let update_path = get_path(
            ApplicationCharge::PATHS,
            ResourceOperation::Update,
            &["id"],
        );
        assert!(update_path.is_none());

        // No Delete path
        let delete_path = get_path(
            ApplicationCharge::PATHS,
            ResourceOperation::Delete,
            &["id"],
        );
        assert!(delete_path.is_none());

        // No Count path
        let count_path = get_path(ApplicationCharge::PATHS, ResourceOperation::Count, &[]);
        assert!(count_path.is_none());
    }

    #[test]
    fn test_application_charge_list_params() {
        let params = ApplicationChargeListParams {
            limit: Some(50),
            since_id: Some(100),
            fields: Some("id,name,price".to_string()),
        };

        let json = serde_json::to_value(&params).unwrap();
        assert_eq!(json["limit"], 50);
        assert_eq!(json["since_id"], 100);
        assert_eq!(json["fields"], "id,name,price");

        // Empty params should serialize to empty object
        let empty_params = ApplicationChargeListParams::default();
        let empty_json = serde_json::to_value(&empty_params).unwrap();
        assert_eq!(empty_json, serde_json::json!({}));
    }

    #[test]
    fn test_application_charge_constants() {
        assert_eq!(ApplicationCharge::NAME, "ApplicationCharge");
        assert_eq!(ApplicationCharge::PLURAL, "application_charges");
    }

    #[test]
    fn test_application_charge_get_id() {
        let charge_with_id = ApplicationCharge {
            id: Some(12345),
            ..Default::default()
        };
        assert_eq!(charge_with_id.get_id(), Some(12345));

        let charge_without_id = ApplicationCharge::default();
        assert_eq!(charge_without_id.get_id(), None);
    }
}