paddle_rust_sdk/
lib.rs

1#![allow(clippy::result_large_err)]
2
3//! # Paddle API Client
4//!
5//! An async client library for interaction with Paddle API, An async and ergonomic wrapper around Paddle's REST HTTP API.
6//!
7//! Every interaction is done via the [Paddle] client type.
8//!
9//! ## Init and Usage Example
10//!
11//! ```rust,no_run
12//! use paddle_rust_sdk::Paddle;
13//!
14//! #[tokio::main]
15//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
16//!     let client = Paddle::new(std::env::var("PADDLE_API_KEY")?, Paddle::SANDBOX)?;
17//!
18//!     let mut list = client.customers_list();
19//!     let mut paginated = list.per_page(2).send();
20//!     let customers = paginated.all().await?;
21//!
22//!     dbg!(customers);
23//!
24//!     Ok(())
25//! }
26//! ```
27//!
28//! The `examples/` dir has up to date working example code.
29//!
30//! ## Webhook signature verification
31//!
32//! Use the [Paddle::unmarshal] method to verify that received events are genuinely sent from Paddle. Additionally, this method returns the deserialized event struct.
33//!
34
35use reports::ReportType;
36use reqwest::{header::CONTENT_TYPE, IntoUrl, Method, StatusCode, Url};
37use serde::{de::DeserializeOwned, Serialize};
38
39pub mod entities;
40pub mod enums;
41pub mod error;
42pub mod ids;
43pub mod webhooks;
44
45pub mod addresses;
46pub mod adjustments;
47pub mod businesses;
48pub mod customers;
49pub mod discounts;
50pub mod events;
51pub mod paginated;
52pub mod payment_methods;
53pub mod prices;
54pub mod pricing_preview;
55pub mod products;
56pub mod reports;
57pub mod subscriptions;
58pub mod transactions;
59
60pub mod response;
61
62use entities::{
63    CustomerAuthenticationToken, Event, EventType, PricePreviewItem, ReportBase, Subscription,
64    Transaction, TransactionInvoice,
65};
66use enums::{
67    AdjustmentAction, CountryCodeSupported, CurrencyCode, DiscountType, Disposition, TaxCategory,
68};
69use ids::{
70    AddressID, AdjustmentID, BusinessID, CustomerID, DiscountID, PaddleID, PaymentMethodID,
71    PriceID, ProductID, SubscriptionID, TransactionID,
72};
73use webhooks::{MaximumVariance, Signature};
74
75use error::PaddleApiError;
76use response::{ErrorResponse, Response, SuccessResponse};
77
78pub use error::Error;
79
80type Result<T> = std::result::Result<SuccessResponse<T>, Error>;
81
82/// Paddle API client
83///
84/// This struct is used to create a new Paddle client instance.
85#[derive(Clone, Debug)]
86pub struct Paddle {
87    base_url: Url,
88    api_key: String,
89}
90
91impl Paddle {
92    pub const PRODUCTION: &'static str = "https://api.paddle.com";
93    pub const SANDBOX: &'static str = "https://sandbox-api.paddle.com";
94
95    /// List of IP addresses Paddle uses to call webhook endpoints from the Live environment
96    pub const ALLOWED_WEBHOOK_IPS_PRODUCTION: [&str; 6] = [
97        "34.232.58.13",
98        "34.195.105.136",
99        "34.237.3.244",
100        "35.155.119.135",
101        "52.11.166.252",
102        "34.212.5.7",
103    ];
104
105    /// List of IP addresses Paddle uses to call webhook endpoints from the Sandbox environment
106    pub const ALLOWED_WEBHOOK_IPS_SANDBOX: [&str; 6] = [
107        "34.194.127.46",
108        "54.234.237.108",
109        "3.208.120.145",
110        "44.226.236.210",
111        "44.241.183.62",
112        "100.20.172.113",
113    ];
114
115    /// Creates a new Paddle client instance.
116    ///
117    /// Example:
118    ///
119    /// ```rust,no_run
120    /// use paddle_rust_sdk::Paddle;
121    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
122    /// ```
123    pub fn new(
124        api_key: impl Into<String>,
125        base_url: impl IntoUrl,
126    ) -> std::result::Result<Self, Error> {
127        Ok(Self {
128            base_url: base_url.into_url()?,
129            api_key: api_key.into(),
130        })
131    }
132
133    /// Validate the integrity of a Paddle webhook request.
134    ///
135    /// - **request_body** - The raw body of the request. Don't transform or process the raw body of the request, including adding whitespace or applying other formatting. This results in a different signed payload, meaning signatures won't match when you compare.
136    /// - **secret_key** - Secret key created in Paddle dashboard. Each notification destination has it's own secret key.
137    /// - **signature** - "Paddle-Signature" HTTP request header from an incoming webhook sent by Paddle.
138    /// - **maximum_variance** - Maximum allowed age for a generated signature. [MaximumVariance::default] is 5 seconds. Pass `MaximumVariance(None)` to disable timestamp checking.
139    ///
140    /// **Return** - the deserialized [Event] struct.
141    ///
142    /// The `examples/` directory contains a demo webhook handler for Actix web.
143    pub fn unmarshal(
144        request_body: impl AsRef<str>,
145        secret_key: impl AsRef<str>,
146        signature: impl AsRef<str>,
147        maximum_variance: MaximumVariance,
148    ) -> std::result::Result<Event, Error> {
149        let signature: Signature = signature.as_ref().parse()?;
150        signature.verify(request_body.as_ref(), secret_key, maximum_variance)?;
151
152        let event = serde_json::from_str(request_body.as_ref())?;
153
154        Ok(event)
155    }
156
157    /// Get a request builder for fetching products. Use the after method to page through results.
158    ///
159    /// By default, Paddle returns products that are active. Use the status method to return products that are archived.
160    /// Use the include method to include related price entities in the response.
161    ///
162    /// # Example:
163    ///
164    /// ```rust,no_run
165    /// use paddle_rust_sdk::Paddle;
166    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
167    ///
168    /// let mut products_list = client.products_list();
169    /// let mut products = products_list.order_by_asc("id").per_page(20).send();
170    ///
171    /// while let Some(res) = products.next().await.unwrap() {
172    ///     dbg!(res.data);
173    /// }
174    /// ```
175    pub fn products_list(&self) -> products::ProductsList {
176        products::ProductsList::new(self)
177    }
178
179    /// Get a request builder for creating a new product.
180    ///
181    /// # Example:
182    ///
183    /// ```rust,no_run
184    /// use paddle_rust_sdk::Paddle;
185    /// use paddle_rust_sdk::enums::TaxCategory;
186    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
187    /// let product = client.products_create("My Product", TaxCategory::Standard).send().await.unwrap();
188    /// ```
189    pub fn product_create(
190        &self,
191        name: impl Into<String>,
192        tax_category: TaxCategory,
193    ) -> products::ProductCreate {
194        products::ProductCreate::new(self, name, tax_category)
195    }
196
197    /// Get a request builder for fetching a specific product.
198    ///
199    /// # Example:
200    ///
201    /// ```rust,no_run
202    /// use paddle_rust_sdk::Paddle;
203    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
204    /// let product = client.product_get("pro_01jqx9rd...").send().await.unwrap();
205    /// ```
206    pub fn product_get(&self, product_id: impl Into<ProductID>) -> products::ProductGet {
207        products::ProductGet::new(self, product_id)
208    }
209
210    /// Get a request builder for updating a specific product.
211    ///
212    /// # Example:
213    ///
214    /// ```rust,no_run
215    /// use paddle_rust_sdk::Paddle;
216    /// use paddle_rust_sdk::enums::TaxCategory;
217    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
218    /// let product = client.product_update("pro_01jqx9rd...").name("My New Name").send().await.unwrap();
219    /// ```
220    pub fn product_update(&self, product_id: impl Into<ProductID>) -> products::ProductUpdate {
221        products::ProductUpdate::new(self, product_id)
222    }
223
224    /// Get a request builder listing prices
225    ///
226    /// # Example:
227    ///
228    /// ```rust,no_run
229    /// use paddle_rust_sdk::Paddle;
230    ///
231    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
232    ///
233    /// let mut prices_list = client.prices_list();
234    /// let mut prices = prices_list.order_by_asc("id").per_page(20).send();
235    ///
236    /// while let Some(res) = prices.next().await.unwrap() {
237    ///     dbg!(res.data);
238    /// }
239    /// ```
240    pub fn prices_list(&self) -> prices::PricesList {
241        prices::PricesList::new(self)
242    }
243
244    /// Get a request builder for creating a new price.
245    ///
246    /// * `product_id` - Paddle ID for the product that this price is for.
247    /// * `description` - Internal description for this price, not shown to customers. Typically notes for your team.
248    /// * `amount` - Amount of the price in the smallest unit of the currency (e.g. 1000 cents for 10 USD).
249    /// * `currency` - Currency code for the price. Use the [CurrencyCode] enum to specify the currency.
250    ///
251    /// # Example:
252    ///
253    /// ```rust,no_run
254    /// use paddle_rust_sdk::Paddle;
255    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
256    /// let price = client.price_create("pro_01jqx9rd...", "Low price", 19.99, CurrencyCode::USD).send().await.unwrap();
257    /// ```
258    pub fn price_create(
259        &self,
260        product_id: impl Into<ProductID>,
261        description: impl Into<String>,
262        amount: u64,
263        currency: CurrencyCode,
264    ) -> prices::PricesCreate {
265        prices::PricesCreate::new(self, product_id, description, amount, currency)
266    }
267
268    /// Get a request builder for fetching a specific price by id.
269    ///
270    /// # Example:
271    ///
272    /// ```rust,no_run
273    /// use paddle_rust_sdk::Paddle;
274    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
275    /// let price = client.price_get("price_01jqx9rd...").send().await.unwrap();
276    /// ```
277    pub fn price_get(&self, price_id: impl Into<PriceID>) -> prices::PriceGet {
278        prices::PriceGet::new(self, price_id)
279    }
280
281    /// Get a request builder for updating a specific price.
282    ///
283    /// # Example:
284    ///
285    /// ```rust,no_run
286    /// use paddle_rust_sdk::Paddle;
287    /// use paddle_rust_sdk::enums::TaxCategory;
288    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
289    /// let price = client.price_update("pri_01jqxv...").name("Updated Name").send().await.unwrap();
290    /// ```
291    pub fn price_update(&self, price_id: impl Into<PriceID>) -> prices::PriceUpdate {
292        prices::PriceUpdate::new(self, price_id)
293    }
294
295    /// Get a request builder for fetching discounts.
296    ///
297    /// # Example:
298    ///
299    /// ```rust,no_run
300    /// use paddle_rust_sdk::Paddle;
301    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
302    ///
303    /// let list = client.discounts_list();
304    /// let mut discounts = list.send();
305    ///
306    /// while let Some(res) = discounts.next().await.unwrap() {
307    ///     dbg!(res.data);
308    /// }
309    /// ```
310    pub fn discounts_list(&self) -> discounts::DiscountsList {
311        discounts::DiscountsList::new(self)
312    }
313
314    /// Get a request builder for creating discounts.
315    ///
316    /// # Example:
317    ///
318    /// ```rust,no_run
319    /// use paddle_rust_sdk::Paddle;
320    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
321    /// let discount = client.discount_create("15", "Winter Holidays", DiscountType::Percentage).send().await.unwrap();
322    /// ```
323    pub fn discount_create(
324        &self,
325        amount: impl Into<String>,
326        description: impl Into<String>,
327        discount_type: DiscountType,
328    ) -> discounts::DiscountCreate {
329        discounts::DiscountCreate::new(self, amount, description, discount_type)
330    }
331
332    /// Get a request builder for fetching a specific discount by id.
333    ///
334    /// # Example:
335    ///
336    /// ```rust,no_run
337    /// use paddle_rust_sdk::Paddle;
338    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
339    /// let discount = client.discount_get("dsc_01jqzpbmnq...").send().await.unwrap();
340    /// ```
341    pub fn discount_get(&self, discount_id: impl Into<DiscountID>) -> discounts::DiscountGet {
342        discounts::DiscountGet::new(self, discount_id)
343    }
344
345    /// Get a request builder for creating discounts.
346    ///
347    /// # Example:
348    ///
349    /// ```rust,no_run
350    /// use paddle_rust_sdk::Paddle;
351    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
352    /// let discount = client.discount_update("dsc_01jqzpbmnq...").amount("18").send().await.unwrap();
353    /// ```
354    pub fn discount_update(&self, discount_id: impl Into<DiscountID>) -> discounts::DiscountUpdate {
355        discounts::DiscountUpdate::new(self, discount_id)
356    }
357
358    /// Get a request builder for fetching customers. Use the after method to page through results.
359    ///
360    /// By default, Paddle returns customers that are `active`. Use the status query parameter to return customers that are archived.
361    ///
362    /// # Example:
363    ///
364    /// ```rust,no_run
365    /// use paddle_rust_sdk::Paddle;
366    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
367    /// let customers = client.customers_list().send().await.unwrap();
368    /// ```
369    pub fn customers_list(&self) -> customers::CustomersList {
370        customers::CustomersList::new(self)
371    }
372
373    /// Get a request builder for creating a new customer.
374    ///
375    /// # Example:
376    ///
377    /// ```rust,no_run
378    /// use paddle_rust_sdk::Paddle;
379    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
380    /// let customers = client.customer_create("test@example.com").send().await.unwrap();
381    /// ```
382    pub fn customer_create(&self, email: impl Into<String>) -> customers::CustomerCreate {
383        customers::CustomerCreate::new(self, email.into())
384    }
385
386    /// Get a request builder for fetching a specific customer by id.
387    ///
388    /// # Example:
389    ///
390    /// ```rust,no_run
391    /// use paddle_rust_sdk::Paddle;
392    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
393    /// let discount = client.customer_get("ctm_01jqztc78e1xfdgwhcgjzdrvgd").send().await.unwrap();
394    /// ```
395    pub fn customer_get(&self, customer_id: impl Into<CustomerID>) -> customers::CustomerGet {
396        customers::CustomerGet::new(self, customer_id)
397    }
398
399    /// Get a request builder for updating customer data.
400    ///
401    /// # Example:
402    ///
403    /// ```rust,no_run
404    /// use paddle_rust_sdk::Paddle;
405    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
406    /// let discount = client.customer_update("ctm_01jqztc78e1xfdgwhcgjzdrvgd").email("new_email@example.com").send().await.unwrap();
407    /// ```
408    pub fn customer_update(&self, customer_id: impl Into<CustomerID>) -> customers::CustomerUpdate {
409        customers::CustomerUpdate::new(self, customer_id)
410    }
411
412    /// Get a request builder for fetching a list of credit balances for each currency for a customer.
413    ///
414    /// Each balance has three totals:
415    ///
416    /// * `available` - total available to use.
417    /// * `reserved` - total temporarily reserved for billed transactions.
418    /// * `used` - total amount of credit used.
419    ///
420    /// Credit is added to the available total initially. When used, it moves to the used total.
421    ///
422    /// The reserved total is used when a credit balance is applied to a transaction that's marked as billed, like when working with an issued invoice. It's not available for other transactions at this point, but isn't considered used until the transaction is completed. If a billed transaction is canceled, any reserved credit moves back to available.
423    ///
424    /// Credit balances are created automatically by Paddle when you take an action that results in Paddle creating a credit for a customer, like making prorated changes to a subscription. An empty data array is returned where a customer has no credit balances.
425    ///
426    /// The response is not paginated.
427    ///
428    /// # Example:
429    ///
430    /// ```rust,no_run
431    /// use paddle_rust_sdk::Paddle;
432    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
433    /// let discount = client.customer_credit_balances("ctm_01jqztc78e1xfdgwhcgjzdrvgd").send().await.unwrap();
434    /// ```
435    pub fn customer_credit_balances(
436        &self,
437        customer_id: impl Into<CustomerID>,
438    ) -> customers::CustomerCreditBalances {
439        customers::CustomerCreditBalances::new(self, customer_id)
440    }
441
442    /// Generates an authentication token for a customer.
443    ///
444    /// You can pass a generated authentication token to Paddle.js when opening a checkout to let customers work with saved payment methods.
445    ///
446    /// Authentication tokens are temporary and shouldn't be cached. They're valid until the expires_at date returned in the response.
447    pub async fn generate_auth_token(
448        &self,
449        customer_id: impl Into<CustomerID>,
450    ) -> Result<CustomerAuthenticationToken> {
451        let client = reqwest::Client::new();
452
453        let customer_id = customer_id.into();
454
455        let url = format!(
456            "{}customers/{}/auth-token",
457            self.base_url,
458            customer_id.as_ref()
459        );
460
461        let res: Response<_> = client
462            .post(url)
463            .bearer_auth(self.api_key.clone())
464            .send()
465            .await?
466            .json()
467            .await?;
468
469        match res {
470            Response::Success(success) => Ok(success),
471            Response::Error(error) => Err(Error::PaddleApi(error)),
472        }
473    }
474
475    /// Get a request builder for fetching customers addresses.
476    ///
477    /// By default, Paddle returns addresses that are `active`. Use the status query parameter to return addresses that are archived.
478    ///
479    /// # Example:
480    ///
481    /// ```rust,no_run
482    /// use paddle_rust_sdk::Paddle;
483    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
484    /// let customers = client.addresses_list("ctm_01jqztc78e1xfdgwhcgjzdrvgd").send().await.unwrap();
485    /// ```
486    pub fn addresses_list(&self, customer_id: impl Into<CustomerID>) -> addresses::AddressesList {
487        addresses::AddressesList::new(self, customer_id)
488    }
489
490    /// Get a request builder for creating a new customer address.
491    ///
492    /// # Example:
493    ///
494    /// ```rust,no_run
495    /// use paddle_rust_sdk::Paddle;
496    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
497    /// let customers = client.address_create("ctm_01jqztc78e1xfdgwhcgjzdrvgd", CountryCodeSupported::US).send().await.unwrap();
498    /// ```
499    pub fn address_create(
500        &self,
501        customer_id: impl Into<CustomerID>,
502        country_code: CountryCodeSupported,
503    ) -> addresses::AddressCreate {
504        addresses::AddressCreate::new(self, customer_id, country_code)
505    }
506
507    /// Get a request builder for getting an address for a customer using its ID and related customer ID.
508    ///
509    /// # Example:
510    ///
511    /// ```rust,no_run
512    /// use paddle_rust_sdk::Paddle;
513    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
514    /// let customers = client.address_get("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "add_01hv8gwdfkw5z6d1yy6pa3xyrz").send().await.unwrap();
515    /// ```
516    pub fn address_get(
517        &self,
518        customer_id: impl Into<CustomerID>,
519        address_id: impl Into<AddressID>,
520    ) -> addresses::AddressGet {
521        addresses::AddressGet::new(self, customer_id, address_id)
522    }
523
524    /// Get a request builder for updating an address for a customer using its ID and related customer ID.
525    ///
526    /// # Example:
527    ///
528    /// ```rust,no_run
529    /// use paddle_rust_sdk::Paddle;
530    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
531    /// let customers = client.address_update("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "add_01hv8gwdfkw5z6d1yy6pa3xyrz").first_line("Test").send().await.unwrap();
532    /// ```
533    pub fn address_update(
534        &self,
535        customer_id: impl Into<CustomerID>,
536        address_id: impl Into<AddressID>,
537    ) -> addresses::AddressUpdate {
538        addresses::AddressUpdate::new(self, customer_id, address_id)
539    }
540
541    /// Get a request builder for fetching customers businesses.
542    ///
543    /// By default, Paddle returns addresses that are `active`. Use the status query parameter to return businesses that are archived.
544    ///
545    /// # Example:
546    ///
547    /// ```rust,no_run
548    /// use paddle_rust_sdk::Paddle;
549    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
550    /// let customers = client.businesses_list("ctm_01jqztc78e1xfdgwhcgjzdrvgd").send().await.unwrap();
551    /// ```
552    pub fn businesses_list(
553        &self,
554        customer_id: impl Into<CustomerID>,
555    ) -> businesses::BusinessesList {
556        businesses::BusinessesList::new(self, customer_id)
557    }
558
559    /// Get a request builder for creating a new customer business.
560    ///
561    /// # Example:
562    ///
563    /// ```rust,no_run
564    /// use paddle_rust_sdk::Paddle;
565    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
566    /// let customers = client.business_create("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "Company Inc.").send().await.unwrap();
567    /// ```
568    pub fn business_create(
569        &self,
570        customer_id: impl Into<CustomerID>,
571        name: impl Into<String>,
572    ) -> businesses::BusinessCreate {
573        businesses::BusinessCreate::new(self, customer_id, name)
574    }
575
576    /// Get a request builder for getting a business for a customer using its ID and related customer ID.
577    ///
578    /// # Example:
579    ///
580    /// ```rust,no_run
581    /// use paddle_rust_sdk::Paddle;
582    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
583    /// let customers = client.business_get("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "biz_01jr85bypq4d3w139m53zw2559").send().await.unwrap();
584    /// ```
585    pub fn business_get(
586        &self,
587        customer_id: impl Into<CustomerID>,
588        business_id: impl Into<BusinessID>,
589    ) -> businesses::BusinessGet {
590        businesses::BusinessGet::new(self, customer_id, business_id)
591    }
592
593    /// Get a request builder for updating a business for a customer using its ID and related customer ID.
594    ///
595    /// # Example:
596    ///
597    /// ```rust,no_run
598    /// use paddle_rust_sdk::Paddle;
599    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
600    /// let customers = client.business_update("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "biz_01jr85bypq4d3w139m53zw2559").first_line("Test").send().await.unwrap();
601    /// ```
602    pub fn business_update(
603        &self,
604        customer_id: impl Into<CustomerID>,
605        business_id: impl Into<BusinessID>,
606    ) -> businesses::BusinessUpdate {
607        businesses::BusinessUpdate::new(self, customer_id, business_id)
608    }
609
610    /// Get a request builder for querying customer saved payment methods.
611    ///
612    /// # Example:
613    ///
614    /// ```rust,no_run
615    /// use paddle_rust_sdk::Paddle;
616    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
617    /// let customers = client.payment_methods_list("ctm_01jqztc78e1xfdgwhcgjzdrvgd").send().await.unwrap();
618    /// ```
619    pub fn payment_methods_list(
620        &self,
621        customer_id: impl Into<CustomerID>,
622    ) -> payment_methods::PaymentMethodsList {
623        payment_methods::PaymentMethodsList::new(self, customer_id)
624    }
625
626    /// Get a request builder for getting a saved payment for a customer using its ID and related customer ID.
627    ///
628    /// # Example:
629    ///
630    /// ```rust,no_run
631    /// use paddle_rust_sdk::Paddle;
632    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
633    /// let customers = client.payment_method_get("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "paymtd_01j2jff1m3es31sdkejpaym164").send().await.unwrap();
634    /// ```
635    pub fn payment_method_get(
636        &self,
637        customer_id: impl Into<CustomerID>,
638        payment_method_id: impl Into<PaymentMethodID>,
639    ) -> payment_methods::PaymentMethodGet {
640        payment_methods::PaymentMethodGet::new(self, customer_id, payment_method_id)
641    }
642
643    /// Deletes a customer payment method using its ID.
644    ///
645    /// When you delete a customer payment method, it's permanently removed from that customer.
646    ///
647    /// There's no way to recover a deleted payment method.
648    ///
649    /// # Example:
650    ///
651    /// ```rust,no_run
652    /// use paddle_rust_sdk::Paddle;
653    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
654    /// client.payment_method_delete("ctm_01jqztc78e1xfdgwhcgjzdrvgd", "paymtd_01j2jff1m3es31sdkejpaym164").await.unwrap();
655    /// ```
656    pub async fn payment_method_delete(
657        &self,
658        customer_id: impl Into<CustomerID>,
659        payment_method_id: impl Into<PaymentMethodID>,
660    ) -> std::result::Result<bool, Error> {
661        let client = reqwest::Client::new();
662
663        let url = format!(
664            "{}customers/{}/payment-methods/{}",
665            self.base_url,
666            customer_id.into().as_ref(),
667            payment_method_id.into().as_ref()
668        );
669
670        let response = client
671            .delete(url)
672            .bearer_auth(self.api_key.clone())
673            .send()
674            .await?;
675
676        Ok(response.status() == StatusCode::NO_CONTENT)
677    }
678
679    /// Creates a customer portal session for a customer.
680    ///
681    /// You can use this to generate authenticated links for a customer so that they're automatically signed in to the portal. Typically used when linking to the customer portal from your app where customers are already authenticated.
682    ///
683    /// You can include an array of subscription_ids to generate authenticated portal links that let customers make changes to their subscriptions. You can use these links as part of subscription management workflows rather than building your own billing screens.
684    ///
685    /// Customer portal sessions are temporary and shouldn't be cached.
686    ///
687    /// The customer portal is fully hosted by Paddle. For security and the best customer experience, don't embed the customer portal in an iframe.
688    ///
689    /// # Example:
690    ///
691    /// ```rust,no_run
692    /// use paddle_rust_sdk::Paddle;
693    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
694    /// let session = client.create_portal_session("ctm_01jqztc78e1xfdgwhcgjzdrvgd").send().await.unwrap();
695    /// dbg!(session.data.urls.general.overview);
696    /// dbg!(session.data.urls.subscriptions);
697    /// ```
698    pub fn create_portal_session(
699        &self,
700        customer_id: impl Into<CustomerID>,
701    ) -> customers::PortalSessionCreate {
702        customers::PortalSessionCreate::new(self, customer_id)
703    }
704
705    /// Get a request builder for querying transactions.
706    ///
707    /// Use the include method on the builder to include related entities in the response.
708    ///
709    /// # Example:
710    ///
711    /// ```rust,no_run
712    /// use paddle_rust_sdk::Paddle;
713    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
714    /// let transactions = client.transactions_list().send().await.unwrap();
715    /// ```
716    pub fn transactions_list(&self) -> transactions::TransactionsList {
717        transactions::TransactionsList::new(self)
718    }
719
720    /// Get a request builder for creating a transaction.
721    ///
722    /// See [Create Transaction](https://developer.paddle.com/api-reference/transactions/create-transaction) for more information.
723    ///
724    /// # Example:
725    ///
726    /// ```rust,no_run
727    /// use paddle_rust_sdk::Paddle;
728    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
729    ///
730    /// let res = client.transaction_create()
731    ///     .append_catalog_item("pri_01jqxvdyjkp961jzv4me7ezg4d", 1)
732    ///     .send()
733    ///     .await
734    ///     .unwrap();
735    ///
736    /// dbg!(res.data);
737    /// ```
738    pub fn transaction_create(&self) -> transactions::TransactionCreate {
739        transactions::TransactionCreate::new(self)
740    }
741
742    /// Get a request builder for fetching a transaction using its ID.
743    ///
744    /// # Example:
745    ///
746    /// ```rust,no_run
747    /// use paddle_rust_sdk::Paddle;
748    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
749    /// let res = client.transaction_get("txn_01hv8wptq8987qeep44cyrewp9").send().await.unwrap();
750    /// dbg!(res.data);
751    /// ```
752    pub fn transaction_get(
753        &self,
754        transaction_id: impl Into<TransactionID>,
755    ) -> transactions::TransactionGet {
756        transactions::TransactionGet::new(self, transaction_id)
757    }
758
759    /// Get a request builder for updating a transaction.
760    ///
761    /// # Example:
762    ///
763    /// ```rust,no_run
764    /// use paddle_rust_sdk::{enums::TransactionStatus, Paddle};
765    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
766    /// client.transaction_update("txn_01hv8wptq8987qeep44cyrewp9").status(TransactionStatus::Billed).send().await.unwrap();
767    /// ```
768    pub fn transaction_update(
769        &self,
770        transaction_id: impl Into<TransactionID>,
771    ) -> transactions::TransactionUpdate {
772        transactions::TransactionUpdate::new(self, transaction_id)
773    }
774
775    /// Returns a link to an invoice PDF for a transaction.
776    ///
777    /// Invoice PDFs are available for both automatically and manually-collected transactions:
778    ///   - The PDF for manually-collected transactions includes payment terms, purchase order number, and notes for your customer. It's a demand for payment from your customer. It's available for transactions that are `billed` or `completed`.
779    ///   - The PDF for automatically-collected transactions lets your customer know that payment was taken successfully. Customers may require this for for tax-reporting purposes. It's available for transactions that are `completed`.
780    ///
781    /// Invoice PDFs aren't available for zero-value transactions.
782    ///
783    /// The link returned is not a permanent link. It expires after an hour.
784    ///
785    /// # Example:
786    ///
787    /// ```rust,no_run
788    /// use paddle_rust_sdk::{enums::Disposition, Paddle};
789    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
790    /// let res = client.transaction_invoice("txn_01hv8wptq8987qeep44cyrewp9", Disposition::Inline).await.unwrap();
791    /// dbg!(res.data.url)
792    /// ```
793    pub async fn transaction_invoice(
794        &self,
795        transaction_id: impl Into<TransactionID>,
796        disposition: Disposition,
797    ) -> Result<TransactionInvoice> {
798        let transaction_id = transaction_id.into();
799
800        let url = format!("/transactions/{}/invoice", transaction_id.as_ref());
801        let params = ("disposition", disposition);
802
803        self.send(params, Method::GET, &url).await
804    }
805
806    /// Get a request builder for generating a transaction preview without creating a transaction entity. Typically used for creating more advanced, dynamic pricing pages where users can build their own plans.
807    ///
808    /// You can provide location information when previewing a transaction. You must provide this if you want Paddle to calculate tax or automatically localize prices. You can provide one of:
809    ///   - `customer_ip_address`: Paddle fetches location using the IP address to calculate totals.
810    ///   - `address`: Paddle uses the country and ZIP code (where supplied) to calculate totals.
811    ///   - `customer_id`, `address_id`, `business_id`: Paddle uses existing customer data to calculate totals. Typically used for logged-in customers.
812    ///
813    /// When supplying items, you can exclude items from the total calculation using the `include_in_totals` boolean.
814    ///
815    /// By default, recurring items with trials are considered to have a zero charge when previewing. Set `ignore_trials` to true to ignore trial periods against prices for transaction preview calculations.
816    ///
817    /// If successful, your response includes the data you sent with a details object that includes totals for the supplied prices.
818    ///
819    /// Transaction previews don't create transactions, so no `id` is returned.
820    pub fn transaction_preview(&self) -> transactions::TransactionPreview {
821        transactions::TransactionPreview::new(self)
822    }
823
824    /// Get a request builder to revise customer information for a billed or completed transaction.
825    ///
826    /// Revise a transaction to rectify incorrect customer, address, or business information on invoice documents generated by Paddle.
827    ///
828    /// You can revise transaction details that don't impact the tax rates on a transaction. This includes:
829    ///   - Customer name
830    ///   - Business name and tax or VAT number (`tax_identifier`)
831    ///   - Address details, apart from the country
832    ///
833    /// You can't remove a valid tax or VAT number, only replace it with another valid one. If a valid tax or VAT number is added, Paddle automatically creates an adjustment to refund any tax where applicable.
834    ///
835    /// Transactions can only be revised once.
836    ///
837    /// If successful, your response includes a copy of the transaction entity. Get a transaction using the `include` parameter with the `customer`, `address`, and `business` values to see the revised customer information.
838    ///
839    /// Only the customer information for this transaction is updated. The related customer, address, and business entities aren't updated.
840    pub fn transaction_revise(
841        &self,
842        transaction_id: impl Into<TransactionID>,
843    ) -> transactions::TransactionRevise {
844        transactions::TransactionRevise::new(self, transaction_id)
845    }
846
847    /// Get a request builder for querying subscriptions.
848    ///
849    /// # Example:
850    ///
851    /// ```rust,no_run
852    /// use paddle_rust_sdk::Paddle;
853    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
854    /// let subscriptions = client.subscriptions_list().send().await.unwrap();
855    /// ```
856    pub fn subscriptions_list(&self) -> subscriptions::SubscriptionsList {
857        subscriptions::SubscriptionsList::new(self)
858    }
859
860    /// Get a request builder for fetching a subscription using its ID.
861    ///
862    /// # Example:
863    ///
864    /// ```rust,no_run
865    /// use paddle_rust_sdk::Paddle;
866    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
867    /// let res = client.subscription_get("sub_01hv8y5ehszzq0yv20ttx3166y").send().await.unwrap();
868    /// dbg!(res.data);
869    /// ```
870    pub fn subscription_get(
871        &self,
872        subscription_id: impl Into<SubscriptionID>,
873    ) -> subscriptions::SubscriptionGet {
874        subscriptions::SubscriptionGet::new(self, subscription_id)
875    }
876
877    /// Get a request builder for getting a preview of changes to a subscription without actually applying them.
878    ///
879    /// Typically used for previewing proration before making changes to a subscription.
880    ///
881    /// If successful, your response includes `immediate_transaction`, `next_transaction`, and `recurring_transaction_details` so you can see expected transactions for the changes.
882    ///
883    /// The `update_summary` object contains details of prorated credits and charges created, along with the overall result of the update.
884    ///
885    /// # Example:
886    ///
887    /// ```rust,no_run
888    /// use paddle_rust_sdk::Paddle;
889    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
890    ///
891    /// let res = client.subscription_preview_update("sub_01hv8y5ehszzq0yv20ttx3166y")
892    ///     .next_billed_at(Utc::now() + Days::new(10))
893    ///     .proration_billing_mode(ProrationBillingMode::ProratedImmediately)
894    ///     .send()
895    ///     .await
896    ///     .unwrap();
897    ///
898    /// dbg!(res.data);
899    /// ```
900    pub fn subscription_preview_update(
901        &self,
902        subscription_id: impl Into<SubscriptionID>,
903    ) -> subscriptions::SubscriptionPreviewUpdate {
904        subscriptions::SubscriptionPreviewUpdate::new(self, subscription_id)
905    }
906
907    /// Get a request builder for updating a subscription using its ID.
908    ///
909    /// When making changes to items or the next billing date for a subscription, you must include the `proration_billing_mode` field to tell Paddle how to bill for those changes.
910    ///
911    /// Send the complete list of items that you'd like to be on a subscription — including existing items. If you omit items, they're removed from the subscription.
912    ///
913    /// For each item, send `price_id` and `quantity`. Paddle responds with the full price object for each price. If you're updating an existing item, you can omit the `quantity` if you don't want to update it.
914    ///
915    /// If successful, your response includes a copy of the updated subscription entity. When an update results in an immediate charge, responses may take longer than usual while a payment attempt is processed.
916    ///
917    /// # Example:
918    ///
919    /// ```rust,no_run
920    /// use paddle_rust_sdk::Paddle;
921    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
922    /// let res = client.subscription_get("sub_01hv8y5ehszzq0yv20ttx3166y").send().await.unwrap();
923    /// dbg!(res.data);
924    /// ```
925    pub fn subscription_update(
926        &self,
927        subscription_id: impl Into<SubscriptionID>,
928    ) -> subscriptions::SubscriptionUpdate {
929        subscriptions::SubscriptionUpdate::new(self, subscription_id)
930    }
931
932    /// Returns a transaction that you can pass to a checkout to let customers update their payment details. Only for subscriptions where collection_mode is automatic.
933    ///
934    /// The transaction returned depends on the status of the related subscription:
935    /// - Where a subscription is `past_due`, it returns the most recent `past_due` transaction.
936    /// - Where a subscription is `active`, it creates a new zero amount transaction for the items on a subscription.
937    ///
938    /// You can use the returned `checkout.url`, or pass the returned transaction ID to Paddle.js to open a checkout to present customers with a way of updating their payment details.
939    ///
940    /// The `customer`, `address`, `business`, `discount`, `adjustments` and `adjustments_totals` properties are only returned in the response if the API key has read permissions for those related entities.
941    pub async fn subscription_update_payment_method_transaction(
942        &self,
943        subscription_id: impl Into<SubscriptionID>,
944    ) -> Result<Transaction> {
945        let subscription_id = subscription_id.into();
946
947        let url = format!(
948            "/subscriptions/{}/update-payment-method-transaction",
949            subscription_id.as_ref()
950        );
951
952        self.send((), Method::GET, &url).await
953    }
954
955    /// Get a request builder for previewing creating a one-time charge for a subscription without billing that charge. Typically used for previewing calculations before making changes to a subscription.
956    ///
957    /// One-time charges are non-recurring items. These are price entities where the `billing_cycle` is `null`.
958    ///
959    /// If successful, your response includes `immediate_transaction`, `next_transaction`, and `recurring_transaction_details` so you can see expected transactions for the changes.
960    pub fn subscription_preview_one_time_charge(
961        &self,
962        subscription_id: impl Into<SubscriptionID>,
963    ) -> subscriptions::SubscriptionOneTimeChargePreview {
964        subscriptions::SubscriptionOneTimeChargePreview::new(self, subscription_id)
965    }
966
967    /// Get a request builder for creating a new one-time charge for a subscription. Use to bill non-recurring items to a subscription. Non-recurring items are price entities where the `billing_cycle` is `null`.
968    ///
969    /// If successful, Paddle responds with the updated subscription entity. However, one-time charges aren't held against the subscription entity, so the charges billed aren't returned in the response.
970    ///
971    /// Once created, to get details of a one-time charge:
972    /// - When created with `effective_from` as `next_billing_period`, get the subscription the charge was billed to and use the `include` query parameter with the `next_transaction` value.
973    /// - When created with `effective_from` as `immediately`, list transactions and use the `subscription_id` query parameter with the subscription ID of the subscription the charge was billed to.
974    ///
975    /// When an update results in an immediate charge, responses may take longer than usual while a payment attempt is processed.
976    pub fn subscription_one_time_charge(
977        &self,
978        subscription_id: impl Into<SubscriptionID>,
979    ) -> subscriptions::SubscriptionOneTimeCharge {
980        subscriptions::SubscriptionOneTimeCharge::new(self, subscription_id)
981    }
982
983    /// Activates a trialing subscription using its ID. Only automatically-collected subscriptions where the status is trialing can be activated.
984    ///
985    /// On activation, Paddle bills for a subscription immediately. Subscription billing dates are recalculated based on the activation date (the time the activation request is made).
986    ///
987    /// If successful, Paddle returns a copy of the updated subscription entity. The subscription status is `active`, and billing dates are updated to reflect the activation date.
988    ///
989    /// This operation results in an immediate charge, so responses may take longer than usual while a payment attempt is processed.
990    pub async fn subscription_activate(
991        &self,
992        subscription_id: impl Into<SubscriptionID>,
993    ) -> Result<Subscription> {
994        let subscription_id = subscription_id.into();
995
996        let url = format!("/subscriptions/{}/activate", subscription_id.as_ref());
997
998        self.send(serde_json::json!({}), Method::POST, &url).await
999    }
1000
1001    /// Get a request builder for pausing a subscription using its ID.
1002    ///
1003    /// By default, subscriptions are paused at the end of the billing period. When you send a request to pause, Paddle creates a `scheduled_change` against the subscription entity to say that it should pause at the end of the current billing period. Its `status` remains `active` until after the effective date of the scheduled change, at which point it changes to `paused`.
1004    ///
1005    /// To set a resume date, include the `resume_at` field in your request. The subscription remains paused until the resume date, or until you send a resume request. Omit to create an open-ended pause. The subscription remains paused indefinitely, until you send a resume request.
1006    pub fn subscription_pause(
1007        &self,
1008        subscription_id: impl Into<SubscriptionID>,
1009    ) -> subscriptions::SubscriptionPause {
1010        subscriptions::SubscriptionPause::new(self, subscription_id)
1011    }
1012
1013    /// Resumes a paused subscription using its ID. Only `paused` subscriptions can be resumed. If an `active` subscription has a scheduled change to pause in the future, use this operation to set or change the resume date.
1014    ///
1015    /// You can't resume a `canceled` subscription.
1016    ///
1017    /// On resume, Paddle bills for a subscription immediately by default. Subscription billing dates are recalculated based on the resume date. Use the `on_resume` field to change this behavior.
1018    ///
1019    /// If successful, Paddle returns a copy of the updated subscription entity:
1020    /// - When resuming a `paused` subscription immediately, the subscription status is `active`, and billing dates are updated to reflect the resume date.
1021    /// - When scheduling a `paused` subscription to resume on a date in the future, the subscription status is `paused`, and `scheduled_change.resume_at` is updated to reflect the scheduled resume date.
1022    /// - When changing the resume date for an `active` subscription that's scheduled to pause, the subscription status is `active` and `scheduled_change.resume_at` is updated to reflect the scheduled resume date.
1023    ///
1024    /// This operation may result in an immediate charge, so responses may take longer than usual while a payment attempt is processed.
1025    pub fn subscription_resume(
1026        &self,
1027        subscription_id: impl Into<SubscriptionID>,
1028    ) -> subscriptions::SubscriptionResume {
1029        subscriptions::SubscriptionResume::new(self, subscription_id)
1030    }
1031
1032    /// Get a request builder for canceling a subscription.
1033    ///
1034    /// By default, active subscriptions are canceled at the end of the billing period. When you send a request to cancel, Paddle creates a `scheduled_change` against the subscription entity to say that it should cancel at the end of the current billing period. Its `status` remains `active` until after the effective date of the scheduled change, at which point it changes to `canceled`.
1035    ///
1036    /// You can cancel a subscription right away by including `effective_from` in your request, setting the value to `immediately`. If successful, your response includes a copy of the updated subscription entity with the `status` of `canceled`. Canceling immediately is the default behavior for paused subscriptions.
1037    ///
1038    /// You can't reinstate a canceled subscription.
1039    pub fn subscription_cancel(
1040        &self,
1041        subscription_id: impl Into<SubscriptionID>,
1042    ) -> subscriptions::SubscriptionCancel {
1043        subscriptions::SubscriptionCancel::new(self, subscription_id)
1044    }
1045
1046    /// Get a request builder for retrieving adjustments from Paddle.
1047    ///
1048    /// Use the builder parameters to filter and page through results.
1049    ///
1050    /// # Example:
1051    ///
1052    /// ```rust,no_run
1053    /// use paddle_rust_sdk::Paddle;
1054    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
1055    /// let res = client.adjustments_list().send().await.unwrap();
1056    /// dbg!(res.data);
1057    /// ```
1058    pub fn adjustments_list(&self) -> adjustments::AdjustmentsList {
1059        adjustments::AdjustmentsList::new(self)
1060    }
1061
1062    /// Get a request builder for creating an adjustment for one or more transaction items.
1063    ///
1064    /// You can create adjustments to refund or credit all or part of a transaction and its items:
1065    /// - Refunds return an amount to a customer's original payment method. You can create refund adjustments for transactions that are `completed`.
1066    /// - Credits reduce the amount that a customer has to pay for a transaction. You can create credit adjustments for manually-collected transactions that are `billed` or `past_due`.
1067    ///
1068    /// You can create adjustments to refund transactions that are `completed`, or to reduce the amount to due on manually-collected transactions that are `billed` or `past_due`. Most refunds for live accounts are created with the status of `pending_approval` until reviewed by Paddle, but some are automatically approved. For sandbox accounts, Paddle automatically approves refunds every ten minutes.
1069    ///
1070    /// Adjustments can apply to some or all items on a transaction. You'll need the Paddle ID of the transaction to create a refund or credit for, along with the Paddle ID of any transaction items `(details.line_items[].id)`.
1071    ///
1072    /// # Example:
1073    ///
1074    /// ```rust,no_run
1075    /// use paddle_rust_sdk::{
1076    ///     enums::{AdjustmentAction, AdjustmentType},
1077    ///     Paddle,
1078    /// };
1079    ///
1080    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
1081    ///
1082    /// let res = client.adjustment_create("txn_01jkfx8v9z4pee0p5bd35x95bp", AdjustmentAction::Refund, "Refund reason")
1083    ///     .r#type(AdjustmentType::Full)
1084    ///     .send()
1085    ///     .await
1086    ///     .unwrap();
1087    ///
1088    /// dbg!(res.data);
1089    /// ```
1090    pub fn adjustment_create(
1091        &self,
1092        transaction_id: impl Into<TransactionID>,
1093        action: AdjustmentAction,
1094        reason: impl Into<String>,
1095    ) -> adjustments::AdjustmentCreate {
1096        adjustments::AdjustmentCreate::new(self, transaction_id, action, reason)
1097    }
1098
1099    /// Returns a link to a credit note PDF for an adjustment.
1100    ///
1101    /// Credit note PDFs are created for refunds and credits as a record of an adjustment.
1102    ///
1103    /// The link returned is not a permanent link. It expires after an hour.
1104    ///
1105    /// # Example:
1106    ///
1107    /// ```rust,no_run
1108    /// use paddle_rust_sdk::{enums::Disposition, Paddle};
1109    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
1110    /// let res = client.adjustment_credit_note("txn_01hv8wptq8987qeep44cyrewp9", Disposition::Inline).await.unwrap();
1111    /// dbg!(res.data.url)
1112    /// ```
1113    pub async fn adjustment_credit_note(
1114        &self,
1115        adjustment_id: impl Into<AdjustmentID>,
1116        disposition: Disposition,
1117    ) -> Result<TransactionInvoice> {
1118        let adjustment_id = adjustment_id.into();
1119
1120        let url = format!("/adjustments/{}/credit-note", adjustment_id.as_ref());
1121        let params = ("disposition", disposition);
1122
1123        self.send(params, Method::GET, &url).await
1124    }
1125
1126    /// Get a request builder for fetching pricing previews for one or more prices. Typically used for building pricing pages.
1127    ///
1128    /// You can provide location information when previewing prices. You must provide this if you want Paddle to calculate tax or automatically localize prices. You can provide one of:
1129    /// - `customer_ip_address`: Paddle fetches location using the IP address to calculate totals.
1130    /// - `address`: Paddle uses the country and ZIP code (where supplied) to calculate totals.
1131    /// - `customer_id`, `address_id`, `business_id`: Paddle uses existing customer data to calculate totals. Typically used for logged-in customers.
1132    ///
1133    /// If successful, your response includes the data you sent with a details object that includes totals for the supplied prices.
1134    ///
1135    /// Each line item includes `formatted_unit_totals` and `formatted_totals` objects that return totals formatted for the country or region you're working with, including the currency symbol.
1136    ///
1137    /// You can work with the preview prices operation using the Paddle.PricePreview() method in Paddle.js. When working with Paddle.PricePreview(), request and response fields are camelCase rather than snake_case.
1138    ///
1139    /// # Example:
1140    ///
1141    /// ```rust,no_run
1142    /// use paddle_rust_sdk::{enums::Disposition, Paddle};
1143    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
1144    ///
1145    /// let res = client.pricing_preview()
1146    ///     .send([PricePreviewItem { price_id: "pri_01jqxvdyjkp961jzv4me7ezg4d".into(), quantity: 1, }])
1147    ///     .await
1148    ///     .unwrap();
1149    ///
1150    /// dbg!(res.data)
1151    /// ```
1152    pub fn pricing_preview(
1153        &self,
1154        items: impl IntoIterator<Item = PricePreviewItem>,
1155    ) -> pricing_preview::PricingPreview {
1156        pricing_preview::PricingPreview::new(self, items)
1157    }
1158
1159    /// Get a request builder for fetching a single report in Paddle.
1160    pub fn reports_list<'a>(&'a self) -> reports::ReportsList<'a> {
1161        reports::ReportsList::new(self)
1162    }
1163
1164    /// Returns a report using its ID.
1165    pub async fn report_get(&self, report_id: impl Into<PaddleID>) -> Result<ReportBase> {
1166        let report_id = report_id.into();
1167
1168        let url = format!("/reports/{}", report_id.as_ref());
1169
1170        self.send((), Method::GET, &url).await
1171    }
1172
1173    /// Returns a link to a CSV file for a report.
1174    ///
1175    /// Only returned for reports that are ready. This means Paddle has completed processing the report and it's ready to download.
1176    ///
1177    /// The link returned is not a permanent link. It expires after 3 minutes.
1178    pub async fn report_download_url(
1179        &self,
1180        report_id: impl Into<PaddleID>,
1181    ) -> Result<TransactionInvoice> {
1182        let report_id = report_id.into();
1183
1184        let url = format!("/reports/{}/download-url", report_id.as_ref());
1185
1186        self.send((), Method::GET, &url).await
1187    }
1188
1189    /// Get a request builder for creating reports in Paddle.
1190    ///
1191    /// Reports are created as `pending` initially while Paddle generates your report. They move to `ready` when they're ready to download.
1192    ///
1193    /// You can download a report when it's ready using the get a CSV file for a report operation.
1194    ///
1195    /// If successful, your response includes a copy of the new report entity.
1196    pub fn report_create<'a, T: ReportType + DeserializeOwned>(
1197        &'a self,
1198        report_type: T,
1199    ) -> reports::ReportCreate<'a, T> {
1200        reports::ReportCreate::new(self, report_type)
1201    }
1202
1203    /// Returns a list of event types.
1204    ///
1205    /// The response is not paginated.
1206    ///
1207    /// # Example:
1208    ///
1209    /// ```rust,no_run
1210    /// use paddle_rust_sdk::{enums::Disposition, Paddle};
1211    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
1212    /// let res = client.event_types_list().await.unwrap();
1213    /// dbg!(res.data)
1214    /// ```
1215    pub async fn event_types_list(&self) -> Result<Vec<EventType>> {
1216        self.send((), Method::GET, "/event-types").await
1217    }
1218
1219    /// Returns a list of event types.
1220    ///
1221    /// The response is not paginated.
1222    ///
1223    /// # Example:
1224    ///
1225    /// ```rust,no_run
1226    /// use paddle_rust_sdk::{enums::Disposition, Paddle};
1227    /// let client = Paddle::new("your_api_key", Paddle::SANDBOX).unwrap();
1228    /// let res = client.events_list().send().await.unwrap();
1229    /// dbg!(res.data)
1230    /// ```
1231    pub fn events_list(&self) -> events::EventsList {
1232        events::EventsList::new(self)
1233    }
1234
1235    async fn send<T: DeserializeOwned>(
1236        &self,
1237        req: impl Serialize,
1238        method: Method,
1239        path: &str,
1240    ) -> Result<T> {
1241        let mut url = self.base_url.join(path)?;
1242        let client = reqwest::Client::new();
1243
1244        if method == reqwest::Method::GET {
1245            url.set_query(Some(&serde_qs::to_string(&req)?));
1246        }
1247
1248        let mut builder = client
1249            .request(method.clone(), url)
1250            .bearer_auth(self.api_key.clone())
1251            .header(CONTENT_TYPE, "application/json; charset=utf-8");
1252
1253        builder = match method {
1254            reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH => {
1255                builder.json(&req)
1256            }
1257            _ => builder,
1258        };
1259
1260        // Uncomment this to see the raw text response
1261        // let text = builder.send().await?.text().await?;
1262        // println!("{}", text);
1263        // todo!();
1264
1265        // Uncomment this to attempt to deserialize the response into an entity
1266        // Needed due to https://github.com/serde-rs/serde/issues/2157
1267
1268        // let res: serde_json::Value = builder.send().await?.json().await?;
1269        // let data_json = serde_json::to_string(&res["data"]).unwrap();
1270        // let res: Vec<entities::ReportBase> = serde_json::from_str(&data_json).unwrap();
1271        // // println!("{}", serde_json::to_string(&res["data"]).unwrap());
1272        // todo!();
1273
1274        let res: Response<_> = builder.send().await?.json().await?;
1275
1276        match res {
1277            Response::Success(success) => Ok(success),
1278            Response::Error(error) => Err(Error::PaddleApi(error)),
1279        }
1280    }
1281}
1282
1283fn comma_separated<S, T>(
1284    values: &Option<Vec<T>>,
1285    serializer: S,
1286) -> std::result::Result<S::Ok, S::Error>
1287where
1288    S: serde::Serializer,
1289    T: AsRef<str>,
1290{
1291    match values {
1292        Some(values) => {
1293            let values = values
1294                .iter()
1295                .map(|v| v.as_ref())
1296                .collect::<Vec<_>>()
1297                .join(",");
1298
1299            serializer.serialize_str(&values)
1300        }
1301        None => serializer.serialize_none(),
1302    }
1303}
1304
1305fn comma_separated_enum<S, T>(
1306    values: &Option<Vec<T>>,
1307    serializer: S,
1308) -> std::result::Result<S::Ok, S::Error>
1309where
1310    S: serde::Serializer,
1311    T: Serialize,
1312{
1313    match values {
1314        Some(values) => {
1315            let mut serialized = vec![];
1316
1317            for val in values {
1318                let serde_value = serde_json::to_value(val).map_err(serde::ser::Error::custom)?;
1319                let serialized_value = serde_value
1320                    .as_str()
1321                    .ok_or(serde::ser::Error::custom("Failed to serialize enum"))?
1322                    .to_string();
1323
1324                serialized.push(serialized_value);
1325            }
1326
1327            serializer.serialize_str(serialized.join(",").as_str())
1328        }
1329        None => serializer.serialize_none(),
1330    }
1331}