use serde::{Deserialize, Serialize};
#[cfg(target_os = "android")]
#[manganis::ffi("src/android/in_app_purchases")]
unsafe extern "Kotlin" {
pub type InAppPurchasesPlugin;
}
#[cfg(target_os = "android")]
const IN_APP_PURCHASES_CLASS: &str =
"dev.dioxus.g3_native_plugins.in_app_purchases.InAppPurchasesPlugin";
#[cfg(target_os = "android")]
type InAppPurchasesHandle = crate::android_bridge::AndroidPlugin;
#[cfg(target_os = "ios")]
type InAppPurchasesHandle = InAppPurchasesPlugin;
#[cfg(target_os = "ios")]
#[manganis::ffi("src/ios")]
unsafe extern "Swift" {
pub type InAppPurchasesPlugin;
pub fn prepareFromRust(this: &InAppPurchasesPlugin);
pub fn startProductsRequestFromRust(this: &InAppPurchasesPlugin, idsJson: String);
pub fn takeProductsFromRust(this: &InAppPurchasesPlugin) -> Option<String>;
pub fn startPurchaseFromRust(this: &InAppPurchasesPlugin, payloadJson: String);
pub fn startRestoreFromRust(this: &InAppPurchasesPlugin);
pub fn takeEntitlementsFromRust(this: &InAppPurchasesPlugin) -> Option<String>;
pub fn finishFromRust(this: &InAppPurchasesPlugin, payloadJson: String);
pub fn getPurchaseStateFromRust(this: &InAppPurchasesPlugin) -> Option<String>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProductKind {
Consumable,
#[default]
NonConsumable,
Subscription,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionPeriod {
pub unit: String,
pub count: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionOffer {
pub id: String,
pub display_price: String,
pub price_micros: i64,
pub period: SubscriptionPeriod,
pub is_free_trial: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Product {
pub id: String,
pub kind: ProductKind,
pub title: String,
pub description: String,
pub display_price: String,
pub price_micros: i64,
pub currency_code: String,
pub subscription_period: Option<SubscriptionPeriod>,
pub offers: Vec<SubscriptionOffer>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Entitlement {
pub product_id: String,
pub transaction_id: String,
pub purchase_token: String,
pub purchased_at_ms: u64,
pub expires_at_ms: Option<u64>,
pub is_active: bool,
pub will_auto_renew: bool,
pub needs_finishing: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalContentLinkToken {
pub external_transaction_token: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PurchaseState {
#[default]
Idle,
Purchasing,
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub struct InAppPurchases {
plugin: Option<InAppPurchasesHandle>,
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
pub struct InAppPurchases;
#[cfg(any(target_os = "android", target_os = "ios"))]
impl InAppPurchases {
pub(crate) fn new() -> Self {
Self { plugin: None }
}
fn get_plugin(&mut self) -> Result<&InAppPurchasesHandle, String> {
if self.plugin.is_none() {
#[cfg(target_os = "android")]
let created = InAppPurchasesHandle::new(IN_APP_PURCHASES_CLASS)?;
#[cfg(target_os = "ios")]
let created = InAppPurchasesPlugin::new()
.map_err(|error| format!("Failed to create InAppPurchasesPlugin: {error:?}"))?;
self.plugin = Some(created);
}
Ok(self.plugin.as_ref().unwrap())
}
pub fn prepare(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit("prepareFromRust")?;
#[cfg(target_os = "ios")]
prepareFromRust(plugin)?;
Ok(())
}
pub fn start_products_request(&mut self, ids: &[String]) -> Result<(), String> {
let ids = serde_json::to_string(ids)
.map_err(|error| format!("Failed to encode product ids: {error}"))?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit_str("startProductsRequestFromRust", &ids)?;
#[cfg(target_os = "ios")]
startProductsRequestFromRust(plugin, ids)?;
Ok(())
}
pub fn poll_products(&mut self) -> Result<Option<Vec<Product>>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let taken = plugin.call_string("takeProductsFromRust")?;
#[cfg(target_os = "ios")]
let taken = takeProductsFromRust(plugin)?;
let Some(json) = taken else {
return Ok(None);
};
Self::decode(&json, "products")
}
pub fn start_purchase(
&mut self,
product_id: &str,
offer_id: Option<&str>,
) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit_str_str(
"startPurchaseFromRust",
product_id,
offer_id.unwrap_or_default(),
)?;
#[cfg(target_os = "ios")]
{
let payload = serde_json::to_string(&serde_json::json!({
"productId": product_id,
"offerId": offer_id.unwrap_or_default(),
}))
.map_err(|error| format!("Failed to encode purchase request: {error}"))?;
startPurchaseFromRust(plugin, payload)?;
}
Ok(())
}
pub fn start_restore(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit("startRestoreFromRust")?;
#[cfg(target_os = "ios")]
startRestoreFromRust(plugin)?;
Ok(())
}
pub fn poll_entitlements(&mut self) -> Result<Option<Vec<Entitlement>>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let taken = plugin.call_string("takeEntitlementsFromRust")?;
#[cfg(target_os = "ios")]
let taken = takeEntitlementsFromRust(plugin)?;
let Some(json) = taken else {
return Ok(None);
};
Self::decode(&json, "entitlements")
}
pub fn finish(&mut self, transaction_id: &str, consume: bool) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit_str_bool("finishFromRust", transaction_id, consume)?;
#[cfg(target_os = "ios")]
{
let payload = serde_json::to_string(&serde_json::json!({
"transactionId": transaction_id,
"consume": consume,
}))
.map_err(|error| format!("Failed to encode finish request: {error}"))?;
finishFromRust(plugin, payload)?;
}
Ok(())
}
pub fn start_external_content_link_token(&mut self) -> Result<(), String> {
#[cfg(target_os = "android")]
self.get_plugin()?
.call_unit("startExternalContentLinkTokenFromRust")?;
Ok(())
}
pub fn poll_external_content_link_token(
&mut self,
) -> Result<Option<ExternalContentLinkToken>, String> {
#[cfg(target_os = "android")]
{
let taken = self
.get_plugin()?
.call_string("takeExternalContentLinkTokenFromRust")?;
let Some(json) = taken else {
return Ok(None);
};
return Self::decode(&json, "external content link token");
}
#[cfg(target_os = "ios")]
Ok(None)
}
pub fn launch_external_content_link(&mut self, url: &str) -> Result<(), String> {
#[cfg(target_os = "android")]
self.get_plugin()?
.call_unit_str("launchExternalContentLinkFromRust", url)?;
Ok(())
}
pub fn poll_external_content_link_launch(&mut self) -> Result<Option<()>, String> {
#[cfg(target_os = "android")]
{
let taken = self
.get_plugin()?
.call_string("takeExternalContentLinkLaunchResultFromRust")?;
let Some(json) = taken else {
return Ok(None);
};
let _: Option<serde_json::Value> = Self::decode(&json, "external content link launch")?;
return Ok(Some(()));
}
#[cfg(target_os = "ios")]
Ok(None)
}
pub fn purchase_state(&mut self) -> PurchaseState {
let Ok(plugin) = self.get_plugin() else {
return PurchaseState::Idle;
};
#[cfg(target_os = "android")]
let state = plugin
.call_string("getPurchaseStateFromRust")
.ok()
.flatten();
#[cfg(target_os = "ios")]
let state = getPurchaseStateFromRust(plugin).ok().flatten();
match state.as_deref() {
Some("purchasing") => PurchaseState::Purchasing,
_ => PurchaseState::Idle,
}
}
fn decode<T: serde::de::DeserializeOwned>(json: &str, what: &str) -> Result<Option<T>, String> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| format!("Failed to read {what}: {error}"))?;
if let Some(error) = value.get("error").and_then(|error| error.as_str()) {
return Err(error.to_string());
}
serde_json::from_value(value)
.map(Some)
.map_err(|error| format!("Failed to read {what}: {error}"))
}
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
impl InAppPurchases {
pub(crate) fn new() -> Self {
Self
}
pub fn prepare(&mut self) -> Result<(), String> {
Ok(())
}
pub fn start_products_request(&mut self, _ids: &[String]) -> Result<(), String> {
Ok(())
}
pub fn poll_products(&mut self) -> Result<Option<Vec<Product>>, String> {
Ok(None)
}
pub fn start_purchase(
&mut self,
_product_id: &str,
_offer_id: Option<&str>,
) -> Result<(), String> {
Ok(())
}
pub fn start_restore(&mut self) -> Result<(), String> {
Ok(())
}
pub fn poll_entitlements(&mut self) -> Result<Option<Vec<Entitlement>>, String> {
Ok(None)
}
pub fn finish(&mut self, _transaction_id: &str, _consume: bool) -> Result<(), String> {
Ok(())
}
pub fn start_external_content_link_token(&mut self) -> Result<(), String> {
Ok(())
}
pub fn poll_external_content_link_token(
&mut self,
) -> Result<Option<ExternalContentLinkToken>, String> {
Ok(None)
}
pub fn launch_external_content_link(&mut self, _url: &str) -> Result<(), String> {
Ok(())
}
pub fn poll_external_content_link_launch(&mut self) -> Result<Option<()>, String> {
Ok(None)
}
pub fn purchase_state(&mut self) -> PurchaseState {
PurchaseState::Idle
}
}