Skip to main content

storekit/
transaction.rs

1use core::ffi::c_void;
2use core::ptr;
3use std::ptr::NonNull;
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7
8use crate::advanced_commerce::{
9    TransactionAdvancedCommerceInfo, TransactionAdvancedCommerceInfoPayload,
10};
11use crate::app_store::AppStoreEnvironment;
12use crate::error::{StoreKitError, VerificationFailure};
13use crate::ffi;
14use crate::private::{
15    cstring_from_str, decode_base64, duration_to_timeout_ms, error_from_status, json_cstring,
16    parse_json_ptr, parse_optional_json_ptr, stream_timed_out, NO_TIMEOUT,
17};
18use crate::product::ProductType;
19use crate::refund::{Refund, RefundRequestStatus};
20use crate::storefront::{Storefront, StorefrontPayload};
21use crate::subscription::{SubscriptionPeriod, SubscriptionPeriodPayload};
22use crate::subscription_info::BillingPlanType;
23pub use crate::verification_result::VerificationResult;
24
25use crate::verification_result::VerificationResultPayload;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28/// Wraps `StoreKit.Transaction.Reason`.
29pub enum TransactionReason {
30    /// Represents the `Purchase` `StoreKit` case.
31    Purchase,
32    /// Represents the `Renewal` `StoreKit` case.
33    Renewal,
34    /// Preserves an unrecognized `StoreKit` case.
35    Unknown(String),
36}
37
38impl TransactionReason {
39    /// Returns the raw `StoreKit` string for this transaction reason.
40    pub fn as_str(&self) -> &str {
41        match self {
42            Self::Purchase => "purchase",
43            Self::Renewal => "renewal",
44            Self::Unknown(value) => value.as_str(),
45        }
46    }
47
48    fn from_raw(raw: String) -> Self {
49        match raw.as_str() {
50            "purchase" => Self::Purchase,
51            "renewal" => Self::Renewal,
52            _ => Self::Unknown(raw),
53        }
54    }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58/// Wraps `StoreKit.Transaction.RevocationReason`.
59pub enum RevocationReason {
60    /// Represents the `DeveloperIssue` `StoreKit` case.
61    DeveloperIssue,
62    /// Represents the `other` `StoreKit` case.
63    Other,
64    /// Preserves an unrecognized `StoreKit` case.
65    Unknown(String),
66}
67
68impl RevocationReason {
69    /// Returns the raw `StoreKit` string for this revocation reason.
70    pub fn as_str(&self) -> &str {
71        match self {
72            Self::DeveloperIssue => "developerIssue",
73            Self::Other => "other",
74            Self::Unknown(value) => value.as_str(),
75        }
76    }
77
78    fn from_raw(raw: String) -> Self {
79        match raw.as_str() {
80            "developerIssue" => Self::DeveloperIssue,
81            "other" => Self::Other,
82            _ => Self::Unknown(raw),
83        }
84    }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88/// Wraps `StoreKit.Transaction.RevocationType`.
89pub enum RevocationType {
90    /// Represents the `FamilyRevocation` `StoreKit` case.
91    FamilyRevocation,
92    /// Represents the `FullRefund` `StoreKit` case.
93    FullRefund,
94    /// Represents the `ProratedRefund` `StoreKit` case.
95    ProratedRefund,
96    /// Preserves an unrecognized `StoreKit` case.
97    Unknown(String),
98}
99
100impl RevocationType {
101    /// Returns the raw `StoreKit` string for this revocation type.
102    pub fn as_str(&self) -> &str {
103        match self {
104            Self::FamilyRevocation => "familyRevocation",
105            Self::FullRefund => "fullRefund",
106            Self::ProratedRefund => "proratedRefund",
107            Self::Unknown(value) => value.as_str(),
108        }
109    }
110
111    fn from_raw(raw: String) -> Self {
112        match raw.as_str() {
113            "familyRevocation" => Self::FamilyRevocation,
114            "fullRefund" => Self::FullRefund,
115            "proratedRefund" => Self::ProratedRefund,
116            _ => Self::Unknown(raw),
117        }
118    }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122/// Wraps the offer type attached to `StoreKit.Transaction`.
123pub enum OfferType {
124    /// Represents the `Introductory` `StoreKit` case.
125    Introductory,
126    /// Represents the `Promotional` `StoreKit` case.
127    Promotional,
128    /// Represents the `Code` `StoreKit` case.
129    Code,
130    /// Represents the `WinBack` `StoreKit` case.
131    WinBack,
132    /// Preserves an unrecognized `StoreKit` case.
133    Unknown(String),
134}
135
136impl OfferType {
137    /// Returns the raw `StoreKit` string for this offer type.
138    pub fn as_str(&self) -> &str {
139        match self {
140            Self::Introductory => "introductory",
141            Self::Promotional => "promotional",
142            Self::Code => "code",
143            Self::WinBack => "winBack",
144            Self::Unknown(value) => value.as_str(),
145        }
146    }
147
148    fn from_raw(raw: String) -> Self {
149        match raw.as_str() {
150            "introductory" => Self::Introductory,
151            "promotional" => Self::Promotional,
152            "code" => Self::Code,
153            "winBack" => Self::WinBack,
154            _ => Self::Unknown(raw),
155        }
156    }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
160/// Wraps the offer payment mode attached to `StoreKit.Transaction`.
161pub enum OfferPaymentMode {
162    /// Represents the `FreeTrial` `StoreKit` case.
163    FreeTrial,
164    /// Represents the `PayAsYouGo` `StoreKit` case.
165    PayAsYouGo,
166    /// Represents the `PayUpFront` `StoreKit` case.
167    PayUpFront,
168    /// Represents the `OneTime` `StoreKit` case.
169    OneTime,
170    /// Preserves an unrecognized `StoreKit` case.
171    Unknown(String),
172}
173
174impl OfferPaymentMode {
175    /// Returns the raw `StoreKit` string for this offer payment mode.
176    pub fn as_str(&self) -> &str {
177        match self {
178            Self::FreeTrial => "freeTrial",
179            Self::PayAsYouGo => "payAsYouGo",
180            Self::PayUpFront => "payUpFront",
181            Self::OneTime => "oneTime",
182            Self::Unknown(value) => value.as_str(),
183        }
184    }
185
186    fn from_raw(raw: String) -> Self {
187        match raw.as_str() {
188            "freeTrial" => Self::FreeTrial,
189            "payAsYouGo" => Self::PayAsYouGo,
190            "payUpFront" => Self::PayUpFront,
191            "oneTime" => Self::OneTime,
192            _ => Self::Unknown(raw),
193        }
194    }
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198/// Carries offer metadata attached to `StoreKit.Transaction`.
199pub struct TransactionOffer {
200    /// `StoreKit` identifier for this value.
201    pub id: Option<String>,
202    /// Offer type reported by `StoreKit`.
203    pub offer_type: OfferType,
204    /// Payment mode reported by `StoreKit`.
205    pub payment_mode: Option<OfferPaymentMode>,
206    /// Subscription period reported by `StoreKit`.
207    pub period: Option<SubscriptionPeriod>,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
211/// Wraps `StoreKit.Transaction.CommitmentInfo`.
212pub struct TransactionCommitmentInfo {
213    /// Billing period number reported by `StoreKit`.
214    pub billing_period_number: u64,
215    /// Total billing periods reported by `StoreKit`.
216    pub total_billing_periods: u64,
217    /// Expiration date reported by `StoreKit`.
218    pub expiration_date: String,
219    /// Price reported by `StoreKit`.
220    pub price: String,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
224/// Wraps `StoreKit.Transaction.OwnershipType`.
225pub enum OwnershipType {
226    /// Represents the `Purchased` `StoreKit` case.
227    Purchased,
228    /// Represents the `FamilyShared` `StoreKit` case.
229    FamilyShared,
230    /// Preserves an unrecognized `StoreKit` case.
231    Unknown(String),
232}
233
234impl OwnershipType {
235    fn from_raw(raw: String) -> Self {
236        match raw.as_str() {
237            "purchased" => Self::Purchased,
238            "familyShared" => Self::FamilyShared,
239            _ => Self::Unknown(raw),
240        }
241    }
242}
243
244#[derive(Debug, Clone, PartialEq, Eq)]
245/// Carries decoded fields from a `StoreKit.Transaction` payload.
246pub struct TransactionData {
247    /// `StoreKit` identifier for this value.
248    pub id: u64,
249    /// Original `StoreKit` transaction identifier.
250    pub original_id: u64,
251    /// Web order line item identifier reported by `StoreKit`.
252    pub web_order_line_item_id: Option<String>,
253    /// Product identifier reported by `StoreKit`.
254    pub product_id: String,
255    /// Subscription group identifier reported by `StoreKit`.
256    pub subscription_group_id: Option<String>,
257    /// Bundle identifier reported by `StoreKit`.
258    pub app_bundle_id: String,
259    /// Purchase date reported by `StoreKit`.
260    pub purchase_date: String,
261    /// Original purchase date reported by `StoreKit`.
262    pub original_purchase_date: String,
263    /// Expiration date reported by `StoreKit`.
264    pub expiration_date: Option<String>,
265    /// Purchased quantity reported by `StoreKit`.
266    pub purchased_quantity: u64,
267    /// Whether `StoreKit` reported `upgraded`.
268    pub is_upgraded: bool,
269    /// Ownership type reported by `StoreKit`.
270    pub ownership_type: OwnershipType,
271    /// Signature timestamp reported by `StoreKit`.
272    pub signed_date: String,
273    /// `StoreKit`-provided `jws_representation` value.
274    pub jws_representation: String,
275    /// Verification failure reported by `StoreKit`.
276    pub verification_failure: Option<VerificationFailure>,
277    /// Revocation date reported by `StoreKit`.
278    pub revocation_date: Option<String>,
279    /// Revocation reason reported by `StoreKit`.
280    pub revocation_reason: Option<RevocationReason>,
281    /// Revocation type reported by `StoreKit`.
282    pub revocation_type: Option<RevocationType>,
283    /// Product type reported by `StoreKit`.
284    pub product_type: Option<ProductType>,
285    /// App account token reported by `StoreKit`.
286    pub app_account_token: Option<String>,
287    /// Environment reported by `StoreKit`.
288    pub environment: Option<AppStoreEnvironment>,
289    /// Reason reported by `StoreKit`.
290    pub reason: Option<TransactionReason>,
291    /// Storefront metadata reported by `StoreKit`.
292    pub storefront: Option<Storefront>,
293    /// Price reported by `StoreKit`.
294    pub price: Option<String>,
295    /// Currency code reported by `StoreKit`.
296    pub currency_code: Option<String>,
297    /// Billing plan type reported by `StoreKit`.
298    pub billing_plan_type: Option<BillingPlanType>,
299    /// Commitment info reported by `StoreKit`.
300    pub commitment_info: Option<TransactionCommitmentInfo>,
301    /// App transaction identifier reported by `StoreKit`.
302    pub app_transaction_id: Option<String>,
303    /// Offer metadata reported by `StoreKit`.
304    pub offer: Option<TransactionOffer>,
305    /// Decoded JSON representation returned by `StoreKit`.
306    pub json_representation: Vec<u8>,
307}
308
309#[derive(Debug)]
310pub(crate) struct TransactionHandle(NonNull<c_void>);
311
312unsafe impl Send for TransactionHandle {}
313unsafe impl Sync for TransactionHandle {}
314
315impl TransactionHandle {
316    pub(crate) unsafe fn from_raw(ptr: *mut c_void) -> Option<Self> {
317        NonNull::new(ptr).map(Self)
318    }
319
320    fn try_clone(&self) -> Option<Self> {
321        NonNull::new(unsafe { ffi::sk_transaction_retain(self.0.as_ptr()) }).map(Self)
322    }
323}
324
325impl Drop for TransactionHandle {
326    fn drop(&mut self) {
327        unsafe { ffi::sk_transaction_release(self.0.as_ptr()) };
328    }
329}
330
331#[derive(Debug)]
332/// Wraps a live `StoreKit.Transaction` handle plus decoded payload data.
333pub struct Transaction {
334    handle: Option<TransactionHandle>,
335    data: TransactionData,
336    advanced_commerce_info: Option<TransactionAdvancedCommerceInfo>,
337}
338
339impl Clone for Transaction {
340    fn clone(&self) -> Self {
341        Self {
342            handle: self.handle.as_ref().and_then(TransactionHandle::try_clone),
343            data: self.data.clone(),
344            advanced_commerce_info: self.advanced_commerce_info.clone(),
345        }
346    }
347}
348
349impl Transaction {
350    /// Creates a stream backed by `StoreKit.Transaction.currentEntitlements`.
351    pub fn current_entitlements() -> Result<TransactionStream, StoreKitError> {
352        TransactionStream::new(&TransactionStreamConfig::current_entitlements())
353    }
354
355    /// Creates a stream backed by `StoreKit.Transaction.all`.
356    pub fn all() -> Result<TransactionStream, StoreKitError> {
357        TransactionStream::new(&TransactionStreamConfig::all())
358    }
359
360    /// Creates a stream backed by `StoreKit.Transaction.updates`.
361    pub fn updates() -> Result<TransactionStream, StoreKitError> {
362        TransactionStream::new(&TransactionStreamConfig::updates())
363    }
364
365    /// Creates a stream backed by `StoreKit.Transaction.unfinished`.
366    pub fn unfinished() -> Result<TransactionStream, StoreKitError> {
367        TransactionStream::new(&TransactionStreamConfig::unfinished())
368    }
369
370    /// Creates a stream of all `StoreKit` transactions for the supplied product identifier.
371    pub fn all_for(product_id: &str) -> Result<TransactionStream, StoreKitError> {
372        TransactionStream::new(&TransactionStreamConfig::all_for(product_id))
373    }
374
375    /// Creates a stream of current `StoreKit` entitlements for the supplied product identifier.
376    pub fn current_entitlements_for(product_id: &str) -> Result<TransactionStream, StoreKitError> {
377        TransactionStream::new(&TransactionStreamConfig::current_entitlements_for(
378            product_id,
379        ))
380    }
381
382    /// Fetches the latest `StoreKit` transaction for the supplied product identifier.
383    pub fn latest_for(product_id: &str) -> Result<Option<VerificationResult<Self>>, StoreKitError> {
384        let product_id = cstring_from_str(product_id, "product id")?;
385        let mut transaction_handle = ptr::null_mut();
386        let mut result_json = ptr::null_mut();
387        let mut error_message = ptr::null_mut();
388        let status = unsafe {
389            ffi::sk_transaction_latest_for(
390                product_id.as_ptr(),
391                &raw mut transaction_handle,
392                &raw mut result_json,
393                &raw mut error_message,
394            )
395        };
396        if status != ffi::status::OK {
397            return Err(unsafe { error_from_status(status, error_message) });
398        }
399        let transaction_handle = unsafe { TransactionHandle::from_raw(transaction_handle) };
400
401        let payload = unsafe {
402            parse_optional_json_ptr::<VerificationResultPayload<TransactionPayload>>(
403                result_json,
404                "latest transaction",
405            )
406        }?;
407        payload
408            .map(|payload| {
409                payload.into_result(|payload| Self::from_raw_parts(transaction_handle, payload))
410            })
411            .transpose()
412    }
413
414    /// Fetches the current `StoreKit` entitlement transaction for the supplied product identifier.
415    pub fn current_entitlement_for(
416        product_id: &str,
417    ) -> Result<Option<VerificationResult<Self>>, StoreKitError> {
418        let product_id = cstring_from_str(product_id, "product id")?;
419        let mut transaction_handle = ptr::null_mut();
420        let mut result_json = ptr::null_mut();
421        let mut error_message = ptr::null_mut();
422        let status = unsafe {
423            ffi::sk_transaction_current_entitlement_for(
424                product_id.as_ptr(),
425                &raw mut transaction_handle,
426                &raw mut result_json,
427                &raw mut error_message,
428            )
429        };
430        if status != ffi::status::OK {
431            return Err(unsafe { error_from_status(status, error_message) });
432        }
433        let transaction_handle = unsafe { TransactionHandle::from_raw(transaction_handle) };
434
435        let payload = unsafe {
436            parse_optional_json_ptr::<VerificationResultPayload<TransactionPayload>>(
437                result_json,
438                "current entitlement transaction",
439            )
440        }?;
441        payload
442            .map(|payload| {
443                payload.into_result(|payload| Self::from_raw_parts(transaction_handle, payload))
444            })
445            .transpose()
446    }
447
448    /// Returns the decoded `StoreKit.Transaction` payload data.
449    pub const fn data(&self) -> &TransactionData {
450        &self.data
451    }
452
453    /// Returns advanced-commerce metadata attached to this `StoreKit` transaction.
454    pub const fn advanced_commerce_info(&self) -> Option<&TransactionAdvancedCommerceInfo> {
455        self.advanced_commerce_info.as_ref()
456    }
457
458    /// Returns whether this wrapper still owns a live `StoreKit` handle.
459    pub const fn has_live_handle(&self) -> bool {
460        self.handle.is_some()
461    }
462
463    /// Asks `StoreKit` to verify this transaction again.
464    pub fn verify(&self) -> Result<(), StoreKitError> {
465        self.handle.as_ref().map_or_else(
466            || {
467                self.data
468                    .verification_failure
469                    .clone()
470                    .map_or(Ok(()), |failure| Err(StoreKitError::Verification(failure)))
471            },
472            |handle| {
473                let mut error_message = ptr::null_mut();
474                let status = unsafe {
475                    ffi::sk_transaction_verify(handle.0.as_ptr(), &raw mut error_message)
476                };
477                if status == ffi::status::OK {
478                    Ok(())
479                } else {
480                    Err(unsafe { error_from_status(status, error_message) })
481                }
482            },
483        )
484    }
485
486    /// Calls `StoreKit.Transaction.finish()`.
487    pub fn finish(&self) -> Result<(), StoreKitError> {
488        self.handle.as_ref().map_or_else(
489            || {
490                Err(StoreKitError::NotSupported(
491                    "transaction snapshots cannot be finished because they do not carry a live StoreKit handle"
492                        .to_owned(),
493                ))
494            },
495            |handle| {
496                let mut error_message = ptr::null_mut();
497                let status = unsafe { ffi::sk_transaction_finish(handle.0.as_ptr(), &raw mut error_message) };
498                if status == ffi::status::OK {
499                    Ok(())
500                } else {
501                    Err(unsafe { error_from_status(status, error_message) })
502                }
503            },
504        )
505    }
506
507    /// Begins a `StoreKit` refund request for this transaction.
508    pub fn begin_refund_request(&self) -> Result<RefundRequestStatus, StoreKitError> {
509        Refund::begin_for_transaction_id(self.data.id)
510    }
511
512    pub(crate) fn from_raw_parts(
513        handle: Option<TransactionHandle>,
514        payload: TransactionPayload,
515    ) -> Result<Self, StoreKitError> {
516        let (data, advanced_commerce_info) = payload.into_transaction_parts()?;
517        Ok(Self {
518            handle,
519            data,
520            advanced_commerce_info,
521        })
522    }
523
524    pub(crate) fn from_snapshot_payload(
525        payload: TransactionPayload,
526    ) -> Result<Self, StoreKitError> {
527        let (data, advanced_commerce_info) = payload.into_transaction_parts()?;
528        Ok(Self {
529            handle: None,
530            data,
531            advanced_commerce_info,
532        })
533    }
534}
535
536#[derive(Debug)]
537/// Wraps the `StoreKit` transaction stream APIs.
538pub struct TransactionStream {
539    handle: NonNull<c_void>,
540    finished: bool,
541}
542
543impl Drop for TransactionStream {
544    fn drop(&mut self) {
545        unsafe { ffi::sk_transaction_stream_release(self.handle.as_ptr()) };
546    }
547}
548
549impl TransactionStream {
550    fn new(config: &TransactionStreamConfig) -> Result<Self, StoreKitError> {
551        let config_json = json_cstring(config, "transaction stream config")?;
552        let mut error_message = ptr::null_mut();
553        let handle = unsafe {
554            ffi::sk_transaction_stream_create(config_json.as_ptr(), &raw mut error_message)
555        };
556        let handle = NonNull::new(handle)
557            .ok_or_else(|| unsafe { error_from_status(ffi::status::UNKNOWN, error_message) })?;
558        Ok(Self {
559            handle,
560            finished: false,
561        })
562    }
563
564    /// Returns whether this `StoreKit` stream has reached the end of the sequence.
565    pub const fn is_finished(&self) -> bool {
566        self.finished
567    }
568
569    #[allow(clippy::should_implement_trait)]
570    /// Waits for the next value from the `StoreKit` stream, or for the end of the sequence.
571    pub fn next(&mut self) -> Result<Option<VerificationResult<Transaction>>, StoreKitError> {
572        self.next_with(NO_TIMEOUT)
573    }
574
575    /// Waits for the next value from the `StoreKit` stream up to the supplied timeout.
576    pub fn next_timeout(
577        &mut self,
578        timeout: Duration,
579    ) -> Result<Option<VerificationResult<Transaction>>, StoreKitError> {
580        self.next_with(duration_to_timeout_ms(timeout))
581    }
582
583    fn next_with(
584        &mut self,
585        timeout_ms: i64,
586    ) -> Result<Option<VerificationResult<Transaction>>, StoreKitError> {
587        let mut transaction_handle = ptr::null_mut();
588        let mut verification_json = ptr::null_mut();
589        let mut error_message = ptr::null_mut();
590        let status = unsafe {
591            ffi::sk_transaction_stream_next(
592                self.handle.as_ptr(),
593                timeout_ms,
594                &raw mut transaction_handle,
595                &raw mut verification_json,
596                &raw mut error_message,
597            )
598        };
599
600        match status {
601            ffi::status::OK => {
602                let transaction_handle = unsafe { TransactionHandle::from_raw(transaction_handle) };
603                let payload = unsafe {
604                    parse_json_ptr::<VerificationResultPayload<TransactionPayload>>(
605                        verification_json,
606                        "transaction verification result",
607                    )
608                }?;
609                payload
610                    .into_result(|payload| Transaction::from_raw_parts(transaction_handle, payload))
611                    .map(Some)
612            }
613            ffi::status::END_OF_STREAM => {
614                self.finished = true;
615                Ok(None)
616            }
617            ffi::status::TIMED_OUT => Err(stream_timed_out("transaction")),
618            _ => Err(unsafe { error_from_status(status, error_message) }),
619        }
620    }
621}
622
623#[derive(Debug, Serialize)]
624struct TransactionStreamConfig {
625    kind: &'static str,
626    #[serde(rename = "productID", skip_serializing_if = "Option::is_none")]
627    product_id: Option<String>,
628}
629
630impl TransactionStreamConfig {
631    const fn all() -> Self {
632        Self {
633            kind: "all",
634            product_id: None,
635        }
636    }
637
638    const fn current_entitlements() -> Self {
639        Self {
640            kind: "currentEntitlements",
641            product_id: None,
642        }
643    }
644
645    const fn updates() -> Self {
646        Self {
647            kind: "updates",
648            product_id: None,
649        }
650    }
651
652    const fn unfinished() -> Self {
653        Self {
654            kind: "unfinished",
655            product_id: None,
656        }
657    }
658
659    fn all_for(product_id: &str) -> Self {
660        Self {
661            kind: "allFor",
662            product_id: Some(product_id.to_owned()),
663        }
664    }
665
666    fn current_entitlements_for(product_id: &str) -> Self {
667        Self {
668            kind: "currentEntitlementsFor",
669            product_id: Some(product_id.to_owned()),
670        }
671    }
672}
673
674#[derive(Debug, Deserialize)]
675pub(crate) struct TransactionOfferPayload {
676    id: Option<String>,
677    #[serde(rename = "type")]
678    offer_type: String,
679    #[serde(rename = "paymentMode")]
680    payment_mode: Option<String>,
681    period: Option<SubscriptionPeriodPayload>,
682}
683
684impl TransactionOfferPayload {
685    pub(crate) fn into_transaction_offer(self) -> TransactionOffer {
686        TransactionOffer {
687            id: self.id,
688            offer_type: OfferType::from_raw(self.offer_type),
689            payment_mode: self.payment_mode.map(OfferPaymentMode::from_raw),
690            period: self
691                .period
692                .map(SubscriptionPeriodPayload::into_subscription_period),
693        }
694    }
695}
696
697#[derive(Debug, Deserialize)]
698pub(crate) struct TransactionCommitmentInfoPayload {
699    #[serde(rename = "billingPeriodNumber")]
700    billing_period_number: u64,
701    #[serde(rename = "totalBillingPeriods")]
702    total_billing_periods: u64,
703    #[serde(rename = "expirationDate")]
704    expiration_date: String,
705    price: String,
706}
707
708impl TransactionCommitmentInfoPayload {
709    pub(crate) fn into_transaction_commitment_info(self) -> TransactionCommitmentInfo {
710        TransactionCommitmentInfo {
711            billing_period_number: self.billing_period_number,
712            total_billing_periods: self.total_billing_periods,
713            expiration_date: self.expiration_date,
714            price: self.price,
715        }
716    }
717}
718
719#[derive(Debug, Deserialize)]
720pub(crate) struct TransactionPayload {
721    id: u64,
722    #[serde(rename = "originalID")]
723    original_id: u64,
724    #[serde(rename = "webOrderLineItemID")]
725    web_order_line_item_id: Option<String>,
726    #[serde(rename = "productID")]
727    product_id: String,
728    #[serde(rename = "subscriptionGroupID")]
729    subscription_group_id: Option<String>,
730    #[serde(rename = "appBundleID")]
731    app_bundle_id: String,
732    #[serde(rename = "purchaseDate")]
733    purchase_date: String,
734    #[serde(rename = "originalPurchaseDate")]
735    original_purchase_date: String,
736    #[serde(rename = "expirationDate")]
737    expiration_date: Option<String>,
738    #[serde(rename = "purchasedQuantity")]
739    purchased_quantity: u64,
740    #[serde(rename = "isUpgraded")]
741    is_upgraded: bool,
742    #[serde(rename = "ownershipType")]
743    ownership_type: String,
744    #[serde(rename = "signedDate")]
745    signed_date: String,
746    #[serde(rename = "jwsRepresentation")]
747    jws_representation: String,
748    #[serde(rename = "verificationError")]
749    verification_error: Option<crate::error::VerificationErrorPayload>,
750    #[serde(rename = "revocationDate")]
751    revocation_date: Option<String>,
752    #[serde(rename = "revocationReason")]
753    revocation_reason: Option<String>,
754    #[serde(rename = "revocationType")]
755    revocation_type: Option<String>,
756    #[serde(rename = "productType")]
757    product_type: Option<String>,
758    #[serde(rename = "appAccountToken")]
759    app_account_token: Option<String>,
760    environment: Option<String>,
761    reason: Option<String>,
762    storefront: Option<StorefrontPayload>,
763    price: Option<String>,
764    #[serde(rename = "currencyCode")]
765    currency_code: Option<String>,
766    #[serde(rename = "billingPlanType")]
767    billing_plan_type: Option<String>,
768    #[serde(rename = "commitmentInfo")]
769    commitment_info: Option<TransactionCommitmentInfoPayload>,
770    #[serde(rename = "appTransactionID")]
771    app_transaction_id: Option<String>,
772    offer: Option<TransactionOfferPayload>,
773    #[serde(rename = "advancedCommerceInfo")]
774    advanced_commerce_info: Option<TransactionAdvancedCommerceInfoPayload>,
775    #[serde(rename = "jsonRepresentationBase64")]
776    json_representation_base64: String,
777}
778
779impl TransactionPayload {
780    fn into_transaction_parts(
781        self,
782    ) -> Result<(TransactionData, Option<TransactionAdvancedCommerceInfo>), StoreKitError> {
783        let advanced_commerce_info = self
784            .advanced_commerce_info
785            .map(TransactionAdvancedCommerceInfoPayload::into_transaction_advanced_commerce_info);
786        Ok((
787            TransactionData {
788                id: self.id,
789                original_id: self.original_id,
790                web_order_line_item_id: self.web_order_line_item_id,
791                product_id: self.product_id,
792                subscription_group_id: self.subscription_group_id,
793                app_bundle_id: self.app_bundle_id,
794                purchase_date: self.purchase_date,
795                original_purchase_date: self.original_purchase_date,
796                expiration_date: self.expiration_date,
797                purchased_quantity: self.purchased_quantity,
798                is_upgraded: self.is_upgraded,
799                ownership_type: OwnershipType::from_raw(self.ownership_type),
800                signed_date: self.signed_date,
801                jws_representation: self.jws_representation,
802                verification_failure: self
803                    .verification_error
804                    .map(crate::error::VerificationFailure::from_payload),
805                revocation_date: self.revocation_date,
806                revocation_reason: self.revocation_reason.map(RevocationReason::from_raw),
807                revocation_type: self.revocation_type.map(RevocationType::from_raw),
808                product_type: self.product_type.map(ProductType::from_raw),
809                app_account_token: self.app_account_token,
810                environment: self.environment.map(AppStoreEnvironment::from_raw),
811                reason: self.reason.map(TransactionReason::from_raw),
812                storefront: self.storefront.map(StorefrontPayload::into_storefront),
813                price: self.price,
814                currency_code: self.currency_code,
815                billing_plan_type: self.billing_plan_type.map(BillingPlanType::from_raw),
816                commitment_info: self
817                    .commitment_info
818                    .map(TransactionCommitmentInfoPayload::into_transaction_commitment_info),
819                app_transaction_id: self.app_transaction_id,
820                offer: self
821                    .offer
822                    .map(TransactionOfferPayload::into_transaction_offer),
823                json_representation: decode_base64(
824                    &self.json_representation_base64,
825                    "transaction JSON representation",
826                )?,
827            },
828            advanced_commerce_info,
829        ))
830    }
831}