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)]
28pub enum TransactionReason {
30 Purchase,
32 Renewal,
34 Unknown(String),
36}
37
38impl TransactionReason {
39 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)]
58pub enum RevocationReason {
60 DeveloperIssue,
62 Other,
64 Unknown(String),
66}
67
68impl RevocationReason {
69 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)]
88pub enum RevocationType {
90 FamilyRevocation,
92 FullRefund,
94 ProratedRefund,
96 Unknown(String),
98}
99
100impl RevocationType {
101 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)]
122pub enum OfferType {
124 Introductory,
126 Promotional,
128 Code,
130 WinBack,
132 Unknown(String),
134}
135
136impl OfferType {
137 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)]
160pub enum OfferPaymentMode {
162 FreeTrial,
164 PayAsYouGo,
166 PayUpFront,
168 OneTime,
170 Unknown(String),
172}
173
174impl OfferPaymentMode {
175 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)]
198pub struct TransactionOffer {
200 pub id: Option<String>,
202 pub offer_type: OfferType,
204 pub payment_mode: Option<OfferPaymentMode>,
206 pub period: Option<SubscriptionPeriod>,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct TransactionCommitmentInfo {
213 pub billing_period_number: u64,
215 pub total_billing_periods: u64,
217 pub expiration_date: String,
219 pub price: String,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub enum OwnershipType {
226 Purchased,
228 FamilyShared,
230 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)]
245pub struct TransactionData {
247 pub id: u64,
249 pub original_id: u64,
251 pub web_order_line_item_id: Option<String>,
253 pub product_id: String,
255 pub subscription_group_id: Option<String>,
257 pub app_bundle_id: String,
259 pub purchase_date: String,
261 pub original_purchase_date: String,
263 pub expiration_date: Option<String>,
265 pub purchased_quantity: u64,
267 pub is_upgraded: bool,
269 pub ownership_type: OwnershipType,
271 pub signed_date: String,
273 pub jws_representation: String,
275 pub verification_failure: Option<VerificationFailure>,
277 pub revocation_date: Option<String>,
279 pub revocation_reason: Option<RevocationReason>,
281 pub revocation_type: Option<RevocationType>,
283 pub product_type: Option<ProductType>,
285 pub app_account_token: Option<String>,
287 pub environment: Option<AppStoreEnvironment>,
289 pub reason: Option<TransactionReason>,
291 pub storefront: Option<Storefront>,
293 pub price: Option<String>,
295 pub currency_code: Option<String>,
297 pub billing_plan_type: Option<BillingPlanType>,
299 pub commitment_info: Option<TransactionCommitmentInfo>,
301 pub app_transaction_id: Option<String>,
303 pub offer: Option<TransactionOffer>,
305 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)]
332pub 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 pub fn current_entitlements() -> Result<TransactionStream, StoreKitError> {
352 TransactionStream::new(&TransactionStreamConfig::current_entitlements())
353 }
354
355 pub fn all() -> Result<TransactionStream, StoreKitError> {
357 TransactionStream::new(&TransactionStreamConfig::all())
358 }
359
360 pub fn updates() -> Result<TransactionStream, StoreKitError> {
362 TransactionStream::new(&TransactionStreamConfig::updates())
363 }
364
365 pub fn unfinished() -> Result<TransactionStream, StoreKitError> {
367 TransactionStream::new(&TransactionStreamConfig::unfinished())
368 }
369
370 pub fn all_for(product_id: &str) -> Result<TransactionStream, StoreKitError> {
372 TransactionStream::new(&TransactionStreamConfig::all_for(product_id))
373 }
374
375 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 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 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 pub const fn data(&self) -> &TransactionData {
450 &self.data
451 }
452
453 pub const fn advanced_commerce_info(&self) -> Option<&TransactionAdvancedCommerceInfo> {
455 self.advanced_commerce_info.as_ref()
456 }
457
458 pub const fn has_live_handle(&self) -> bool {
460 self.handle.is_some()
461 }
462
463 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 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 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)]
537pub 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 pub const fn is_finished(&self) -> bool {
566 self.finished
567 }
568
569 #[allow(clippy::should_implement_trait)]
570 pub fn next(&mut self) -> Result<Option<VerificationResult<Transaction>>, StoreKitError> {
572 self.next_with(NO_TIMEOUT)
573 }
574
575 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}