Expand description
§storekit-rs
Safe Rust bindings for Apple’s StoreKit framework on macOS.
Status: v0.5.0. The
async_apimodule, gated on--features async, wrapsStoreKit2’s Swift async APIs as RustFutures viadoom_fish_utils::completion.
§Installation
[dependencies]
storekit-rs = "0.5"The package is storekit-rs; the library is imported as storekit. It runs on macOS 12 or later, and APIs that need a newer macOS return StoreKitError::NotSupported on older systems. Building compiles a Swift bridge, which needs Xcode with the macOS 26.4 SDK or newer.
Build a macOS binary that uses this crate with a deployment target of macOS 12.0 or later. The
Swift bridge uses Swift concurrency. Rust builds binaries for macOS 11.0 on Apple silicon and for
macOS 10.12 on x86_64 by default. With these targets, the binary loads the Swift runtime
through @rpath and stops at launch with an error such as
Library not loaded: @rpath/libswift_Concurrency.dylib. Set MACOSX_DEPLOYMENT_TARGET=12.0 in
the environment, or set it for the project in .cargo/config.toml:
[env]
MACOSX_DEPLOYMENT_TARGET = "12.0"Cargo does not link the binary again when only this variable changes, so run cargo clean
after you set it.
§Quick start
use storekit::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let products = Product::products_for(["com.example.pro.monthly"])?;
for product in products {
println!("{} — {}", product.display_name, product.display_price);
}
println!("payments enabled: {}", AppStore::can_make_payments()?);
Ok(())
}§Highlights
Product::products_for(...),Product::purchase(...),Product::purchase_in_window(...),Product::latest_transaction(), andProduct::current_entitlements()- Product formatting/localization helpers expose
StoreKitformat styles,SubscriptionPeriodconvenience constructors, and enum/unitlocalized_description()helpers PurchaseOptioncovers quantity, app-account tokens, custom payloads, promotional offers, win-back offers, and storefront-change policiesTransactionexposesall,current_entitlements,updates,unfinished, filtered product streams,latest_for,current_entitlement_for, verification, finishing, refund helpers, and advanced-commerce infoSubscriptionInfo::status_for(...),status_for_transaction(...),SubscriptionStatus::updates(), andSubscriptionStatus::all()surface renewal state plus status streamsPurchaseIntent::intents()andExternalPurchase{,Link,CustomLink}cover the newerStoreKitpurchase-intent and regulatory-link familiesAppStorenow includes merchandising presentation, age-rating lookups, and advanced-commerce product purchase supportStoreKitError::typed()recovers typedStoreKit, purchase, refund-request, and invalid-request framework errorsStorefront::current()andStorefront::updates()wrap theStoreKitstorefront APIsAppTransaction::shared()andAppTransaction::refresh()expose app-level verification resultsReceiptValidatorreads the local app receipt and decodes JWS payloads without publishing or mutating store stateStoreContext::current()summarizes bundle, receipt, payment, and device-verification context for headless tooling
§Verifying transactions
StoreKit returns every transaction, subscription status and app transaction together with the result of its JWS signature check. Read payloads through the checked accessors before granting access:
use storekit::Transaction;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut entitlements = Transaction::current_entitlements()?;
while let Some(result) = entitlements.next()? {
match result.payload_value() {
Ok(transaction) => println!("entitled to {}", transaction.data().product_id),
Err(error) => eprintln!("ignoring an unverified transaction: {error}"),
}
}
Ok(())
}payload_value()andinto_payload_value()return the payload only whenStoreKitverified it, andStoreKitError::Verificationotherwise, like Swift’s throwingpayloadValue.unverified_payload()andinto_unverified_payload()skip the check, likeunsafePayloadValue. Don’t grant entitlements from them.Transaction::finish()refuses to finish a transaction that failed verification.
§Threading and timeouts
- Synchronous calls block the calling thread until
StoreKitanswers. Calls that don’t present UI give up after 30 seconds: theStoreKittask is cancelled andStoreKitError::TimedOutis returned. - Calls that present
StoreKitUI run on the main actor:Product::purchase,Product::purchase_in_window,AppStore::present_merchandising,AdvancedCommerceProduct::purchase_in_window,AppStore::present_offer_code_redeem_sheet,Refund::begin_for_transaction_idandTransaction::begin_refund_request.- On the main thread they return
StoreKitError::NotSupportedright away, because the main actor could never run while they waited. - On any other thread they need the main thread to be running its run loop (for example
NSApplication.run). If the main actor doesn’t start the work within 10 seconds, they returnTimedOutand nothing is presented. Once the main actor has started it they wait up to 10 minutes, then cancel it and returnTimedOut; a purchase that still completes afterwards is delivered throughTransaction::updates().
- On the main thread they return
AppStore::request_review()is synchronous inStoreKitand runs inline when called on the main thread.ExternalPurchase::present_notice_sheet,ExternalPurchaseLink::openandopen_url, andExternalPurchaseCustomLink::show_noticeletStoreKitpresent its own sheet and use the 30-second limit.- To start a purchase or merchandising flow from the main thread without blocking it, enable the
asyncfeature and useAsyncPurchase::buy,AsyncPurchase::buy_in_window,AsyncAppStore::present_merchandisingorAsyncAppStore::request_review. The futures areSend, so they can be spawned onto any executor; don’t block the main thread on them. - Stream
next()waits until the next value arrives or the sequence ends.next_timeout()returnsStoreKitError::TimedOutwhen nothing arrives in time, and the stream stays open. Dropping a stream cancels itsStoreKitlistener. Keep aTransaction::updates()stream open for the life of the app, typically on its own thread, so renewals, refunds and Ask to Buy approvals aren’t missed. Transaction,VerificationResult<Transaction>andPurchaseResultareSend + Sync, so a purchase made on a worker thread can be handed back to the UI thread.
§Examples
The crate ships with numbered examples for each logical area:
01_product_lookup02_transaction_stream03_app_store_context04_storefront_current05_subscription_types06_subscription_info_status07_refund_request08_receipt_validator09_message_support10_app_transaction11_store_context12_renewal_info13_renewal_state14_purchase_option15_verification_result16_purchase_intent17_external_purchase18_advanced_commerce19_typed_errors20_async_products(requires--features async)21_async_app_transaction(requires--features async)22_async_storefront(requires--features async)
Run them all with:
for ex in examples/*.rs; do cargo run --example "$(basename "$ex" .rs)"; done§Async API
Enable the async feature to access StoreKit 2’s async Swift APIs as standard Rust Futures:
[dependencies]
storekit-rs = { version = "0.5", features = ["async"] }
pollster = "0.3" # or any async runtimeuse storekit::async_api::AsyncProducts;
fn main() {
let products = pollster::block_on(async {
AsyncProducts::fetch(["com.example.pro"])
.expect("invalid identifier")
.await
});
println!("{:?}", products);
}The following async types are available: AsyncProducts, AsyncPurchase, AsyncAppStore, AsyncAppTransaction and AsyncStorefront.
§Notes
StoreKit.Messageis unavailable on macOS, so the message module reportsNotSupportedthere.AppStore::show_manage_subscriptions()andAsyncAppStore::show_manage_subscriptions()always returnNotSupported:AppStore.showManageSubscriptions(in:)is scene-based and isn’t part of the macOSStoreKitSDK.- Refund, review, and offer-code presentation helpers use the key window’s
NSViewControllerand returnNotSupportedwhen there is none. Without a running main run loop they returnTimedOutafter 10 seconds (see Threading and timeouts). - Window-based purchase and merchandising APIs accept caller-owned
NSWindowHandlevalues when the host app has anAppKitwindow to lend toStoreKit. The window is retained for the duration of the flow, so it only has to be alive when the call is made. - The crate does not publish or call
cargo publish; release tagging is separate from drip-publisher rollout.
§License
Licensed under either of Apache-2.0 or MIT at your option.
Re-exports§
pub use advanced_commerce::AdvancedCommerceProduct;pub use advanced_commerce::AdvancedCommercePurchaseOption;pub use advanced_commerce::AppStoreMerchandisingKind;pub use advanced_commerce::AppStoreMerchandisingPresentationResult;pub use advanced_commerce::RenewalInfoAdvancedCommerceInfo;pub use advanced_commerce::RenewalInfoAdvancedCommerceItem;pub use advanced_commerce::RenewalInfoAdvancedCommercePriceIncreaseInfo;pub use advanced_commerce::RenewalInfoAdvancedCommercePriceIncreaseStatus;pub use advanced_commerce::TransactionAdvancedCommerceInfo;pub use advanced_commerce::TransactionAdvancedCommerceItem;pub use advanced_commerce::TransactionAdvancedCommerceItemDetails;pub use advanced_commerce::TransactionAdvancedCommerceOffer;pub use advanced_commerce::TransactionAdvancedCommerceOfferReason;pub use advanced_commerce::TransactionAdvancedCommerceRefund;pub use advanced_commerce::TransactionAdvancedCommerceRefundReason;pub use advanced_commerce::TransactionAdvancedCommerceRefundType;pub use app_store::AppStore;pub use app_store::AppStoreEnvironment;pub use app_store::AppStorePlatform;pub use app_transaction::AppTransaction;pub use error::InvalidRequestError;pub use error::ProductPurchaseError;pub use error::ProductPurchaseErrorCode;pub use error::RefundRequestError;pub use error::RefundRequestErrorCode;pub use error::StoreKitApiError;pub use error::StoreKitApiErrorCode;pub use error::StoreKitError;pub use error::StoreKitFrameworkError;pub use error::TypedStoreKitError;pub use error::VerificationErrorCode;pub use error::VerificationFailure;pub use external_purchase::ExternalPurchase;pub use external_purchase::ExternalPurchaseCustomLink;pub use external_purchase::ExternalPurchaseCustomLinkNoticeResult;pub use external_purchase::ExternalPurchaseCustomLinkNoticeType;pub use external_purchase::ExternalPurchaseCustomLinkToken;pub use external_purchase::ExternalPurchaseLink;pub use external_purchase::ExternalPurchaseNoticeResult;pub use message::Message;pub use message::MessageReason;pub use message::MessageStream;pub use product::Product;pub use product::ProductType;pub use purchase_intent::PurchaseIntent;pub use purchase_intent::PurchaseIntentStream;pub use purchase_option::PurchaseOption;pub use purchase_option::PurchaseResult;pub use receipt_validator::AppReceipt;pub use receipt_validator::ReceiptValidator;pub use refund::Refund;pub use refund::RefundRequestStatus;pub use renewal_info::ExpirationReason;pub use renewal_info::PriceIncreaseStatus;pub use renewal_info::RenewalCommitmentInfo;pub use renewal_info::RenewalInfo;pub use renewal_state::RenewalState;pub use store_context::StoreContext;pub use storefront::Storefront;pub use storefront::StorefrontStream;pub use subscription::SubscriptionOffer;pub use subscription::SubscriptionOfferType;pub use subscription::SubscriptionPaymentMode;pub use subscription::SubscriptionPeriod;pub use subscription::SubscriptionPeriodUnit;pub use subscription_info::BillingPlanType;pub use subscription_info::SubscriptionCommitmentInfo;pub use subscription_info::SubscriptionInfo;pub use subscription_info::SubscriptionPricingTerms;pub use subscription_info::SubscriptionStatus;pub use transaction::OfferPaymentMode;pub use transaction::OfferType;pub use transaction::OwnershipType;pub use transaction::RevocationReason;pub use transaction::RevocationType;pub use transaction::Transaction;pub use transaction::TransactionCommitmentInfo;pub use transaction::TransactionData;pub use transaction::TransactionOffer;pub use transaction::TransactionReason;pub use transaction::TransactionStream;pub use verification_result::VerificationMetadata;pub use verification_result::VerificationResult;pub use window::NSWindowHandle;
Modules§
- advanced_
commerce StoreKitadvanced-commerce wrappers and related value types.- app_
store - Wrappers for
StoreKit.AppStoreAPIs. - app_
transaction - Wrappers for
StoreKit.AppTransaction. - async_
api async - Async API for
StoreKit— Tier 1 Future wrappers. - error
- Typed errors surfaced by the
StoreKitframework. - external_
purchase - Wrappers for
StoreKitexternal purchase APIs. - message
- Wrappers for
StoreKit.Messageand related APIs. - prelude
- Common imports.
- product
- Wrappers for
StoreKit.Productand related value types. - purchase_
intent - Wrappers for
StoreKit.PurchaseIntentand its stream APIs. - purchase_
option - Purchase options and results used with
StoreKit.Product.purchase. - receipt_
validator - Helpers for
StoreKitreceipts, app transactions, and JWS payloads. - refund
- Helpers for
StoreKitrefund request APIs. - renewal_
info - Wrappers for
StoreKit.RenewalInfoand related enums. - renewal_
state - Wrappers for
StoreKit.Product.SubscriptionInfo.RenewalState. - store_
context - Helpers that collect bundle context used alongside
StoreKitAPIs. - storefront
- Wrappers for
StoreKit.Storefrontand storefront streams. - subscription
- Wrappers for
StoreKit.Product.SubscriptionInfovalue types. - subscription_
info - Wrappers for
StoreKit.Product.SubscriptionInfo.Statusand related APIs. - transaction
- Wrappers for
StoreKit.Transactionand transaction streams. - verification_
result - Wrappers for
StoreKit.VerificationResultand verification metadata. - window
- Opaque
NSWindowhandles used withStoreKitAPIs that present UI.
Structs§
- Product
Formatting - Carries localized formatting derived from
StoreKit.Product. - Subscription
Group Status Stream - Wraps the
StoreKitsubscription-group status stream. - Subscription
Group Statuses - Carries the
StoreKitstatuses for a subscription group. - Subscription
Status Stream - Wraps the
StoreKitsubscription status update stream.