Skip to main content

storekit/
subscription_info.rs

1use core::ptr;
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5use crate::error::StoreKitError;
6use crate::ffi;
7use crate::private::{
8    cstring_from_str, error_from_status, parse_json_ptr, parse_optional_json_ptr,
9};
10use crate::renewal_info::{RenewalInfo, RenewalInfoPayload};
11use crate::renewal_state::RenewalState;
12use crate::subscription::{
13    SubscriptionOffer, SubscriptionOfferPayload, SubscriptionPeriod, SubscriptionPeriodPayload,
14};
15use crate::transaction::{Transaction, TransactionPayload};
16use crate::verification_result::{VerificationResult, VerificationResultPayload};
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19/// Wraps `StoreKit.Product.SubscriptionInfo.BillingPlanType`.
20pub enum BillingPlanType {
21    /// Represents the `Monthly` `StoreKit` case.
22    Monthly,
23    /// Represents the `UpFront` `StoreKit` case.
24    UpFront,
25    /// Preserves an unrecognized `StoreKit` case.
26    Unknown(String),
27}
28
29impl BillingPlanType {
30    /// Returns the raw `StoreKit` string for this billing plan type.
31    pub fn as_str(&self) -> &str {
32        match self {
33            Self::Monthly => "monthly",
34            Self::UpFront => "upFront",
35            Self::Unknown(value) => value.as_str(),
36        }
37    }
38
39    pub(crate) fn from_raw(raw: String) -> Self {
40        match raw.as_str() {
41            "monthly" => Self::Monthly,
42            "upFront" => Self::UpFront,
43            _ => Self::Unknown(raw),
44        }
45    }
46}
47
48impl Serialize for BillingPlanType {
49    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
50    where
51        S: Serializer,
52    {
53        serializer.serialize_str(self.as_str())
54    }
55}
56
57impl<'de> Deserialize<'de> for BillingPlanType {
58    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
59    where
60        D: Deserializer<'de>,
61    {
62        String::deserialize(deserializer).map(Self::from_raw)
63    }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
67/// Wraps `StoreKit.Product.SubscriptionInfo.CommitmentInfo`.
68pub struct SubscriptionCommitmentInfo {
69    /// Price reported by `StoreKit`.
70    pub price: String,
71    /// Localized display price reported by `StoreKit`.
72    pub display_price: String,
73    /// Billing period reported by `StoreKit`.
74    pub period: SubscriptionPeriod,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78/// Wraps `StoreKit.Product.SubscriptionInfo.PricingTerms`.
79pub struct SubscriptionPricingTerms {
80    /// Billing price reported by `StoreKit`.
81    pub billing_price: String,
82    /// Localized billing display price reported by `StoreKit`.
83    pub billing_display_price: String,
84    /// Billing period reported by `StoreKit`.
85    pub billing_period: SubscriptionPeriod,
86    /// Billing plan type reported by `StoreKit`.
87    pub billing_plan_type: BillingPlanType,
88    /// Commitment info reported by `StoreKit`.
89    pub commitment_info: SubscriptionCommitmentInfo,
90    /// Subscription offers reported by `StoreKit`.
91    pub subscription_offers: Vec<SubscriptionOffer>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95/// Wraps `StoreKit.Product.SubscriptionInfo`.
96pub struct SubscriptionInfo {
97    /// Introductory offer reported by `StoreKit`.
98    pub introductory_offer: Option<SubscriptionOffer>,
99    /// Promotional offers reported by `StoreKit`.
100    pub promotional_offers: Vec<SubscriptionOffer>,
101    /// Win-back offers reported by `StoreKit`.
102    pub win_back_offers: Vec<SubscriptionOffer>,
103    /// Subscription group identifier reported by `StoreKit`.
104    pub subscription_group_id: String,
105    /// Subscription period reported by `StoreKit`.
106    pub subscription_period: SubscriptionPeriod,
107    /// Pricing terms reported by `StoreKit`.
108    pub pricing_terms: Vec<SubscriptionPricingTerms>,
109    /// Subscription group level reported by `StoreKit`.
110    pub group_level: Option<i64>,
111    /// Subscription group display name reported by `StoreKit`.
112    pub group_display_name: Option<String>,
113}
114
115impl SubscriptionInfo {
116    /// Returns whether `StoreKit` reports that this subscription group is eligible for an introductory offer.
117    pub fn is_eligible_for_intro_offer(&self) -> Result<bool, StoreKitError> {
118        Self::is_eligible_for_intro_offer_for(&self.subscription_group_id)
119    }
120
121    /// Returns whether `StoreKit` reports that the supplied subscription group is eligible for an introductory offer.
122    pub fn is_eligible_for_intro_offer_for(group_id: &str) -> Result<bool, StoreKitError> {
123        let group_id = cstring_from_str(group_id, "subscription group id")?;
124        let mut raw_value = 0;
125        let mut error_message = ptr::null_mut();
126        let status = unsafe {
127            ffi::sk_subscription_info_is_eligible_for_intro_offer(
128                group_id.as_ptr(),
129                &raw mut raw_value,
130                &raw mut error_message,
131            )
132        };
133        if status == ffi::status::OK {
134            Ok(raw_value != 0)
135        } else {
136            Err(unsafe { error_from_status(status, error_message) })
137        }
138    }
139
140    /// Fetches the `StoreKit` subscription statuses for this subscription group.
141    pub fn status(&self) -> Result<Vec<SubscriptionStatus>, StoreKitError> {
142        Self::status_for(&self.subscription_group_id)
143    }
144
145    /// Fetches the `StoreKit` subscription statuses for the supplied subscription group identifier.
146    pub fn status_for(group_id: &str) -> Result<Vec<SubscriptionStatus>, StoreKitError> {
147        let group_id = cstring_from_str(group_id, "subscription group id")?;
148        let mut statuses_json = ptr::null_mut();
149        let mut error_message = ptr::null_mut();
150        let status = unsafe {
151            ffi::sk_subscription_info_statuses_json(
152                group_id.as_ptr(),
153                &raw mut statuses_json,
154                &raw mut error_message,
155            )
156        };
157        if status != ffi::status::OK {
158            return Err(unsafe { error_from_status(status, error_message) });
159        }
160        let payloads = unsafe {
161            parse_json_ptr::<Vec<SubscriptionStatusPayload>>(statuses_json, "subscription statuses")
162        }?;
163        payloads
164            .into_iter()
165            .map(SubscriptionStatusPayload::into_subscription_status)
166            .collect::<Result<Vec<_>, _>>()
167    }
168
169    /// Fetches the `StoreKit` subscription status for the supplied transaction identifier.
170    pub fn status_for_transaction(
171        transaction_id: u64,
172    ) -> Result<Option<SubscriptionStatus>, StoreKitError> {
173        let transaction_id = cstring_from_str(&transaction_id.to_string(), "transaction id")?;
174        let mut status_json = ptr::null_mut();
175        let mut error_message = ptr::null_mut();
176        let status = unsafe {
177            ffi::sk_subscription_info_status_for_transaction(
178                transaction_id.as_ptr(),
179                &raw mut status_json,
180                &raw mut error_message,
181            )
182        };
183        if status != ffi::status::OK {
184            return Err(unsafe { error_from_status(status, error_message) });
185        }
186        unsafe {
187            parse_optional_json_ptr::<SubscriptionStatusPayload>(
188                status_json,
189                "subscription status for transaction",
190            )
191        }
192        .and_then(|payload| {
193            payload
194                .map(SubscriptionStatusPayload::into_subscription_status)
195                .transpose()
196        })
197    }
198}
199
200#[derive(Debug, Clone)]
201/// Wraps `StoreKit.Product.SubscriptionInfo.Status`.
202pub struct SubscriptionStatus {
203    /// State reported by `StoreKit`.
204    pub state: RenewalState,
205    /// Transaction payload returned by `StoreKit`.
206    pub transaction: VerificationResult<Transaction>,
207    /// Renewal info payload returned by `StoreKit`.
208    pub renewal_info: VerificationResult<RenewalInfo>,
209}
210
211#[derive(Debug, Deserialize)]
212pub(crate) struct SubscriptionInfoPayload {
213    #[serde(rename = "introductoryOffer")]
214    introductory_offer: Option<SubscriptionOfferPayload>,
215    #[serde(rename = "promotionalOffers")]
216    promotional_offers: Vec<SubscriptionOfferPayload>,
217    #[serde(rename = "winBackOffers")]
218    win_back_offers: Vec<SubscriptionOfferPayload>,
219    #[serde(rename = "subscriptionGroupID")]
220    subscription_group_id: String,
221    #[serde(rename = "subscriptionPeriod")]
222    subscription_period: SubscriptionPeriodPayload,
223    #[serde(default, rename = "pricingTerms")]
224    pricing_terms: Vec<SubscriptionPricingTermsPayload>,
225    #[serde(rename = "groupLevel")]
226    group_level: Option<i64>,
227    #[serde(rename = "groupDisplayName")]
228    group_display_name: Option<String>,
229}
230
231#[derive(Debug, Deserialize)]
232pub(crate) struct SubscriptionCommitmentInfoPayload {
233    price: String,
234    #[serde(rename = "displayPrice")]
235    display_price: String,
236    period: SubscriptionPeriodPayload,
237}
238
239impl SubscriptionCommitmentInfoPayload {
240    pub(crate) fn into_subscription_commitment_info(self) -> SubscriptionCommitmentInfo {
241        SubscriptionCommitmentInfo {
242            price: self.price,
243            display_price: self.display_price,
244            period: self.period.into_subscription_period(),
245        }
246    }
247}
248
249#[derive(Debug, Deserialize)]
250pub(crate) struct SubscriptionPricingTermsPayload {
251    #[serde(rename = "billingPrice")]
252    billing_price: String,
253    #[serde(rename = "billingDisplayPrice")]
254    billing_display_price: String,
255    #[serde(rename = "billingPeriod")]
256    billing_period: SubscriptionPeriodPayload,
257    #[serde(rename = "billingPlanType")]
258    billing_plan_type: String,
259    #[serde(rename = "commitmentInfo")]
260    commitment_info: SubscriptionCommitmentInfoPayload,
261    #[serde(default, rename = "subscriptionOffers")]
262    subscription_offers: Vec<SubscriptionOfferPayload>,
263}
264
265impl SubscriptionPricingTermsPayload {
266    pub(crate) fn into_subscription_pricing_terms(self) -> SubscriptionPricingTerms {
267        SubscriptionPricingTerms {
268            billing_price: self.billing_price,
269            billing_display_price: self.billing_display_price,
270            billing_period: self.billing_period.into_subscription_period(),
271            billing_plan_type: BillingPlanType::from_raw(self.billing_plan_type),
272            commitment_info: self.commitment_info.into_subscription_commitment_info(),
273            subscription_offers: self
274                .subscription_offers
275                .into_iter()
276                .map(SubscriptionOfferPayload::into_subscription_offer)
277                .collect(),
278        }
279    }
280}
281
282impl SubscriptionInfoPayload {
283    pub(crate) fn into_subscription_info(self) -> SubscriptionInfo {
284        SubscriptionInfo {
285            introductory_offer: self
286                .introductory_offer
287                .map(SubscriptionOfferPayload::into_subscription_offer),
288            promotional_offers: self
289                .promotional_offers
290                .into_iter()
291                .map(SubscriptionOfferPayload::into_subscription_offer)
292                .collect(),
293            win_back_offers: self
294                .win_back_offers
295                .into_iter()
296                .map(SubscriptionOfferPayload::into_subscription_offer)
297                .collect(),
298            subscription_group_id: self.subscription_group_id,
299            subscription_period: self.subscription_period.into_subscription_period(),
300            pricing_terms: self
301                .pricing_terms
302                .into_iter()
303                .map(SubscriptionPricingTermsPayload::into_subscription_pricing_terms)
304                .collect(),
305            group_level: self.group_level,
306            group_display_name: self.group_display_name,
307        }
308    }
309}
310
311#[derive(Debug, Deserialize)]
312pub(crate) struct SubscriptionStatusPayload {
313    state: String,
314    transaction: VerificationResultPayload<TransactionPayload>,
315    #[serde(rename = "renewalInfo")]
316    renewal_info: VerificationResultPayload<RenewalInfoPayload>,
317}
318
319impl SubscriptionStatusPayload {
320    pub(crate) fn into_subscription_status(self) -> Result<SubscriptionStatus, StoreKitError> {
321        Ok(SubscriptionStatus {
322            state: RenewalState::from_raw(self.state),
323            transaction: self
324                .transaction
325                .into_result(Transaction::from_snapshot_payload)?,
326            renewal_info: self
327                .renewal_info
328                .into_result(|payload| Ok(payload.into_renewal_info()))?,
329        })
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use crate::subscription::{
337        SubscriptionOfferType, SubscriptionPaymentMode, SubscriptionPeriodUnit,
338    };
339    use serde_json::json;
340
341    #[test]
342    fn billing_plan_types_round_trip_known_values() {
343        let cases = [
344            ("monthly", BillingPlanType::Monthly),
345            ("upFront", BillingPlanType::UpFront),
346        ];
347
348        for (raw, billing_plan_type) in cases {
349            assert_eq!(BillingPlanType::from_raw(raw.to_owned()), billing_plan_type);
350            assert_eq!(billing_plan_type.as_str(), raw);
351        }
352    }
353
354    #[test]
355    fn unknown_billing_plan_type_is_preserved() {
356        let billing_plan_type = BillingPlanType::from_raw("seasonal".to_owned());
357
358        assert_eq!(
359            billing_plan_type,
360            BillingPlanType::Unknown("seasonal".into())
361        );
362        assert_eq!(billing_plan_type.as_str(), "seasonal");
363    }
364
365    #[test]
366    fn billing_plan_type_serializes_as_raw_string() {
367        assert_eq!(
368            serde_json::to_value(BillingPlanType::Monthly).expect("serialize monthly plan"),
369            json!("monthly")
370        );
371        assert_eq!(
372            serde_json::to_value(BillingPlanType::Unknown("custom".into()))
373                .expect("serialize custom plan"),
374            json!("custom")
375        );
376    }
377
378    #[test]
379    fn subscription_pricing_terms_payload_converts_nested_fields() {
380        let payload: SubscriptionPricingTermsPayload = serde_json::from_value(json!({
381            "billingPrice": "59.99",
382            "billingDisplayPrice": "$59.99",
383            "billingPeriod": {
384                "unit": "year",
385                "value": 1
386            },
387            "billingPlanType": "upFront",
388            "commitmentInfo": {
389                "price": "59.99",
390                "displayPrice": "$59.99",
391                "period": {
392                    "unit": "year",
393                    "value": 1
394                }
395            },
396            "subscriptionOffers": [{
397                "id": "winback",
398                "type": "winBack",
399                "price": "29.99",
400                "displayPrice": "$29.99",
401                "period": {
402                    "unit": "month",
403                    "value": 3
404                },
405                "periodCount": 1,
406                "paymentMode": "payUpFront"
407            }]
408        }))
409        .expect("deserialize pricing terms payload");
410        let pricing_terms = payload.into_subscription_pricing_terms();
411
412        assert_eq!(pricing_terms.billing_plan_type, BillingPlanType::UpFront);
413        assert_eq!(
414            pricing_terms.billing_period,
415            SubscriptionPeriod {
416                unit: SubscriptionPeriodUnit::Year,
417                value: 1,
418            }
419        );
420        assert_eq!(pricing_terms.commitment_info.price, "59.99");
421        let offer = pricing_terms
422            .subscription_offers
423            .first()
424            .expect("one subscription offer");
425        assert_eq!(offer.offer_type, SubscriptionOfferType::WinBack);
426        assert_eq!(offer.payment_mode, SubscriptionPaymentMode::PayUpFront);
427    }
428
429    #[test]
430    fn subscription_info_payload_converts_optional_fields() {
431        let payload: SubscriptionInfoPayload = serde_json::from_value(json!({
432            "promotionalOffers": [],
433            "winBackOffers": [],
434            "subscriptionGroupID": "group-1",
435            "subscriptionPeriod": {
436                "unit": "month",
437                "value": 1
438            },
439            "pricingTerms": [],
440            "groupLevel": 2,
441            "groupDisplayName": "Pro"
442        }))
443        .expect("deserialize subscription info payload");
444        let info = payload.into_subscription_info();
445
446        assert_eq!(info.subscription_group_id, "group-1");
447        assert_eq!(
448            info.subscription_period,
449            SubscriptionPeriod {
450                unit: SubscriptionPeriodUnit::Month,
451                value: 1,
452            }
453        );
454        assert_eq!(info.group_level, Some(2));
455        assert_eq!(info.group_display_name.as_deref(), Some("Pro"));
456        assert_eq!(info.pricing_terms.len(), 0);
457    }
458}