Skip to main content

storekit/
external_purchase.rs

1use core::ptr;
2
3use serde::Deserialize;
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};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12/// Represents the result returned by the `StoreKit` external purchase notice sheet.
13pub enum ExternalPurchaseNoticeResult {
14    /// The `StoreKit` flow continued.
15    Continued,
16    /// The person cancelled the `StoreKit` flow.
17    Cancelled,
18    /// The notice continued and `StoreKit` returned an external purchase token.
19    ContinuedWithExternalPurchaseToken {
20        /// Token returned by `StoreKit`.
21        token: String,
22    },
23    /// Preserves an unrecognized `StoreKit` case.
24    Unknown(String),
25}
26
27impl ExternalPurchaseNoticeResult {
28    /// Returns the raw `StoreKit` string for this notice result.
29    pub fn as_str(&self) -> &str {
30        match self {
31            Self::Continued => "continued",
32            Self::Cancelled => "cancelled",
33            Self::ContinuedWithExternalPurchaseToken { .. } => "continuedWithExternalPurchaseToken",
34            Self::Unknown(value) => value.as_str(),
35        }
36    }
37}
38
39#[derive(Debug, Clone, Copy, Default)]
40/// Helpers backed by `StoreKit` external purchase APIs.
41pub struct ExternalPurchase;
42
43impl ExternalPurchase {
44    /// Returns whether `StoreKit` can present the external purchase notice sheet.
45    pub fn can_present() -> Result<bool, StoreKitError> {
46        let mut raw_value = 0;
47        let mut error_message = ptr::null_mut();
48        let status = unsafe {
49            ffi::sk_external_purchase_can_present(&raw mut raw_value, &raw mut error_message)
50        };
51        if status == ffi::status::OK {
52            Ok(raw_value != 0)
53        } else {
54            Err(unsafe { error_from_status(status, error_message) })
55        }
56    }
57
58    /// Presents the `StoreKit` external purchase notice sheet.
59    pub fn present_notice_sheet() -> Result<ExternalPurchaseNoticeResult, StoreKitError> {
60        let mut result_json = ptr::null_mut();
61        let mut error_message = ptr::null_mut();
62        let status = unsafe {
63            ffi::sk_external_purchase_present_notice_result_json(
64                &raw mut result_json,
65                &raw mut error_message,
66            )
67        };
68        if status != ffi::status::OK {
69            return Err(unsafe { error_from_status(status, error_message) });
70        }
71        let payload = unsafe {
72            parse_json_ptr::<ExternalPurchaseNoticeResultPayload>(
73                result_json,
74                "external purchase notice result",
75            )
76        }?;
77        Ok(payload.into_notice_result())
78    }
79}
80
81#[derive(Debug, Clone, Copy, Default)]
82/// Helpers backed by `StoreKit` external purchase link APIs.
83pub struct ExternalPurchaseLink;
84
85impl ExternalPurchaseLink {
86    /// Returns whether `StoreKit` can open the external purchase link.
87    pub fn can_open() -> Result<bool, StoreKitError> {
88        let mut raw_value = 0;
89        let mut error_message = ptr::null_mut();
90        let status = unsafe {
91            ffi::sk_external_purchase_link_can_open(&raw mut raw_value, &raw mut error_message)
92        };
93        if status == ffi::status::OK {
94            Ok(raw_value != 0)
95        } else {
96            Err(unsafe { error_from_status(status, error_message) })
97        }
98    }
99
100    /// Returns the eligible external purchase URLs reported by `StoreKit`.
101    pub fn eligible_urls() -> Result<Option<Vec<String>>, StoreKitError> {
102        let mut urls_json = ptr::null_mut();
103        let mut error_message = ptr::null_mut();
104        let status = unsafe {
105            ffi::sk_external_purchase_link_eligible_urls_json(
106                &raw mut urls_json,
107                &raw mut error_message,
108            )
109        };
110        if status != ffi::status::OK {
111            return Err(unsafe { error_from_status(status, error_message) });
112        }
113        unsafe {
114            parse_optional_json_ptr::<Vec<String>>(urls_json, "eligible external purchase URLs")
115        }
116    }
117
118    /// Opens the default `StoreKit` external purchase link.
119    pub fn open() -> Result<(), StoreKitError> {
120        let mut error_message = ptr::null_mut();
121        let status = unsafe { ffi::sk_external_purchase_link_open(&raw mut error_message) };
122        if status == ffi::status::OK {
123            Ok(())
124        } else {
125            Err(unsafe { error_from_status(status, error_message) })
126        }
127    }
128
129    /// Opens the supplied `StoreKit`-eligible external purchase URL.
130    pub fn open_url(url: &str) -> Result<(), StoreKitError> {
131        let url = cstring_from_str(url, "external purchase URL")?;
132        let mut error_message = ptr::null_mut();
133        let status = unsafe {
134            ffi::sk_external_purchase_link_open_url(url.as_ptr(), &raw mut error_message)
135        };
136        if status == ffi::status::OK {
137            Ok(())
138        } else {
139            Err(unsafe { error_from_status(status, error_message) })
140        }
141    }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145/// Represents the notice type passed to `StoreKit` external purchase custom link APIs.
146pub enum ExternalPurchaseCustomLinkNoticeType {
147    /// Represents the `WithinApp` `StoreKit` case.
148    WithinApp,
149    /// Represents the `Browser` `StoreKit` case.
150    Browser,
151    /// Preserves an unrecognized `StoreKit` case.
152    Unknown(i64),
153}
154
155impl ExternalPurchaseCustomLinkNoticeType {
156    /// Returns the raw `StoreKit` integer for this notice type.
157    pub const fn as_raw(&self) -> i64 {
158        match self {
159            Self::WithinApp => 0,
160            Self::Browser => 1,
161            Self::Unknown(value) => *value,
162        }
163    }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
167/// Represents the result returned by `StoreKit` external purchase custom link UI.
168pub enum ExternalPurchaseCustomLinkNoticeResult {
169    /// The person cancelled the `StoreKit` flow.
170    Cancelled,
171    /// The `StoreKit` flow continued.
172    Continued,
173    /// Preserves an unrecognized `StoreKit` case.
174    Unknown(String),
175}
176
177impl ExternalPurchaseCustomLinkNoticeResult {
178    /// Returns the raw `StoreKit` string for this custom-link notice result.
179    pub fn as_str(&self) -> &str {
180        match self {
181            Self::Cancelled => "cancelled",
182            Self::Continued => "continued",
183            Self::Unknown(value) => value.as_str(),
184        }
185    }
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
189/// Wraps a token returned by `StoreKit` external purchase custom link APIs.
190pub struct ExternalPurchaseCustomLinkToken {
191    /// Value returned by `StoreKit`.
192    pub value: String,
193}
194
195#[derive(Debug, Clone, Copy, Default)]
196/// Helpers backed by `StoreKit` external purchase custom link APIs.
197pub struct ExternalPurchaseCustomLink;
198
199impl ExternalPurchaseCustomLink {
200    /// Returns whether `StoreKit` reports that the custom link flow is eligible.
201    pub fn is_eligible() -> Result<bool, StoreKitError> {
202        let mut raw_value = 0;
203        let mut error_message = ptr::null_mut();
204        let status = unsafe {
205            ffi::sk_external_purchase_custom_link_is_eligible(
206                &raw mut raw_value,
207                &raw mut error_message,
208            )
209        };
210        if status == ffi::status::OK {
211            Ok(raw_value != 0)
212        } else {
213            Err(unsafe { error_from_status(status, error_message) })
214        }
215    }
216
217    /// Presents the `StoreKit` custom-link notice UI.
218    pub fn show_notice(
219        notice_type: ExternalPurchaseCustomLinkNoticeType,
220    ) -> Result<ExternalPurchaseCustomLinkNoticeResult, StoreKitError> {
221        let raw_notice_type = i32::try_from(notice_type.as_raw()).map_err(|_| {
222            StoreKitError::InvalidArgument(format!(
223                "external purchase custom link notice type '{}' does not fit in i32",
224                notice_type.as_raw()
225            ))
226        })?;
227        let mut result_json = ptr::null_mut();
228        let mut error_message = ptr::null_mut();
229        let status = unsafe {
230            ffi::sk_external_purchase_custom_link_show_notice_result_json(
231                raw_notice_type,
232                &raw mut result_json,
233                &raw mut error_message,
234            )
235        };
236        if status != ffi::status::OK {
237            return Err(unsafe { error_from_status(status, error_message) });
238        }
239        let payload = unsafe {
240            parse_json_ptr::<ExternalPurchaseCustomLinkNoticeResultPayload>(
241                result_json,
242                "external purchase custom link notice result",
243            )
244        }?;
245        Ok(payload.into_notice_result())
246    }
247
248    /// Fetches a custom-link token from `StoreKit`.
249    pub fn token(
250        token_type: &str,
251    ) -> Result<Option<ExternalPurchaseCustomLinkToken>, StoreKitError> {
252        let token_type = cstring_from_str(token_type, "external purchase custom link token type")?;
253        let mut token_json = ptr::null_mut();
254        let mut error_message = ptr::null_mut();
255        let status = unsafe {
256            ffi::sk_external_purchase_custom_link_token_json(
257                token_type.as_ptr(),
258                &raw mut token_json,
259                &raw mut error_message,
260            )
261        };
262        if status != ffi::status::OK {
263            return Err(unsafe { error_from_status(status, error_message) });
264        }
265        unsafe {
266            parse_optional_json_ptr::<ExternalPurchaseCustomLinkTokenPayload>(
267                token_json,
268                "external purchase custom link token",
269            )
270        }
271        .map(|payload| {
272            payload.map(|payload| ExternalPurchaseCustomLinkToken {
273                value: payload.value,
274            })
275        })
276    }
277}
278
279#[derive(Debug, Deserialize)]
280struct ExternalPurchaseNoticeResultPayload {
281    kind: String,
282    token: Option<String>,
283}
284
285impl ExternalPurchaseNoticeResultPayload {
286    fn into_notice_result(self) -> ExternalPurchaseNoticeResult {
287        match self.kind.as_str() {
288            "continued" => ExternalPurchaseNoticeResult::Continued,
289            "cancelled" => ExternalPurchaseNoticeResult::Cancelled,
290            "continuedWithExternalPurchaseToken" => {
291                ExternalPurchaseNoticeResult::ContinuedWithExternalPurchaseToken {
292                    token: self.token.unwrap_or_default(),
293                }
294            }
295            other => ExternalPurchaseNoticeResult::Unknown(other.to_owned()),
296        }
297    }
298}
299
300#[derive(Debug, Deserialize)]
301struct ExternalPurchaseCustomLinkNoticeResultPayload {
302    kind: String,
303}
304
305impl ExternalPurchaseCustomLinkNoticeResultPayload {
306    fn into_notice_result(self) -> ExternalPurchaseCustomLinkNoticeResult {
307        match self.kind.as_str() {
308            "cancelled" => ExternalPurchaseCustomLinkNoticeResult::Cancelled,
309            "continued" => ExternalPurchaseCustomLinkNoticeResult::Continued,
310            other => ExternalPurchaseCustomLinkNoticeResult::Unknown(other.to_owned()),
311        }
312    }
313}
314
315#[derive(Debug, Deserialize)]
316struct ExternalPurchaseCustomLinkTokenPayload {
317    value: String,
318}