StoreKit

RSS for tag

Support in-app purchases and interactions with the App Store using StoreKit.

StoreKit Documentation

Posts under StoreKit subtopic

Post

Replies

Boosts

Views

Activity

Migrating to StoreKit 2
Hi Friends, I have an iOS app, which uses around 500 in app purchases for various modules. I am using StoreKit for in app purchase, now trying to migrate this to StoreKit 2. I am using Product.products(for:) method to fetch all the products by sending identifiers of all the 500 In app purchases. In response, I am getting details of only 160 products, the method is not returning remaining in app purchases. What could be the reason for this behaviour, how to get rid of the issue? May be is this the issue will happen only on TestFlight? If someone from Apple assures about it, we have plan to submit the app. Please advise, Thank you.
0
0
75
May ’25
IAP Sandbox - No Products
Hello, I've been trying to get the sandbox environment working for in-app purchases, but so far, no luck. I can use a storekit config file to simulate purchases just fine. The item is a single consumable product. I've checked that my product ID matches, followed the advice tendered to other forum users, created a sandbox user, all to no avail. I've signed into the app store using my sandbox account on one phone - I can't get the "Sandbox User" option to appear on the second after attempting to make a purchase (per https://developer.apple.com/documentation/storekit/testing-in-app-purchases-with-sandbox ). What I'm wondering is, do I need to get the in-app-purchase approved/released through App Review before I can even perform testing or something? I've signed all agreements, set up our banking information, everything seems to be in order, but I just cannot get the StoreKIt products call to return anything. ( let products = try await Product.products(for: productId) ) Is there anything else I can check? I've also checked everything here: https://forums.developer.apple.com/forums/thread/652077 Thanks!
1
0
609
Dec ’24
How to deal with the following "Bad Gateway_message" prompt after purchase
Payment completed with error: Error Domain=ASDErrorDomain Code=500 "(null)" UserInfo={client-environment-type=Sandbox, storefront-country-code=USA, NSUnderlyingError=0x2828a5950 {Error Domain=AMSErrorDomain Code=305 "Purchase Failed" UserInfo={NSLocalizedDescription=Purchase Failed, AMSURL=https://sandbox.itunes.apple.com/WebObjects/MZBuy.woa/wa/inAppBuy?guid=00008030-000164513691402E, AMSStatusCode=200, AMSServerPayload={ "cancel-purchase-batch" = 1; customerMessage = "Bad Gateway_message"; failureType = ""; "m-allowed" = 0; pings = ( ); }, NSLocalizedFailureReason=Server canceled the purchase}}}
0
0
253
Dec ’24
TestFlight Subscription Upgrade Handling
Looking for assistance in managing subscription upgrades for TestFlight users. I have a few monthly subscriptions, 30days, each with a different set of available features, 1 with all, and 1 with fewer. (All are in proper order and grouped in App Store connection subscriptions) subscribing seems to be working fine, and purchasing an upgrade is going ok. what is not: reflecting the upgraded plan in app (currently reflects it will start in 30days when current subscription expires) I’m lead to believe this will be resolved with a live app in App Store, that will then handle prorating, terminate the old plan and immediately start the new one. looking for help getting TestFlight to show immediate upgrades.
0
0
84
May ’25
Transaction.environment is undefined/nil in TestFlight
I'm using Transaction.environment to determine server behavior. https://developer.apple.com/documentation/storekit/apptransaction/environment https://developer.apple.com/documentation/storekit/appstore/environment I gather this information on the app using StoreKit and then send it to the server: originalTransactionId = transaction.originalID originalTransactionEnvironment = transaction.environment When testing within Xcode, on a simulator, the value sent to the server for originalTransactionEnvironment is Xcode - as expected. When testing on a device using a TestFlight build, the value sent to the server for originalTransactionEnvironment is undefined/nil. I expected it to be Sandbox - and later in production it should be Production. Most importantly, the value sent to the server for originalTransactionId in the TestFlight version is not undefined/nil - it is the value I expected it would be. The transaction was originally for a subscription purchase, if that makes a difference. So the transaction is available, and information like originalID is also available. Why is transaction.environment not available? What is the behavior in production?
0
0
267
Dec ’24
StoreKit2 Subscription Verification
My question is simple, I do not have much experience in writing swift code, I am only doing it to create a small executable that I can call from my python application which completes Subcription Management. I was hoping someone with more experience could point out my flaws along with giving me tips on how to verify that the check is working for my applicaiton. Any inight is appreciated, thank you. import Foundation import StoreKit class SubscriptionValidator { static func getReceiptURL() -> URL? { guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else { print("No receipt found.") return nil } return appStoreReceiptURL } static func validateReceipt() -> Bool { guard let receiptURL = getReceiptURL(), let receiptData = try? Data(contentsOf: receiptURL) else { print("Could not read receipt.") return false } let receiptString = receiptData.base64EncodedString() let validationResult = sendReceiptToApple(receiptString: receiptString) return validationResult } static func sendReceiptToApple(receiptString: String) -> Bool { let isSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" let urlString = isSandbox ? "https://sandbox.itunes.apple.com/verifyReceipt" : "https://buy.itunes.apple.com/verifyReceipt" let url = URL(string: urlString)! let requestData: [String: Any] = [ "receipt-data": receiptString, "password": "0b7f88907b77443997838c72be52f5fc" ] guard let requestBody = try? JSONSerialization.data(withJSONObject: requestData) else { print("Error creating request body.") return false } var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = requestBody request.setValue("application/json", forHTTPHeaderField: "Content-Type") let semaphore = DispatchSemaphore(value: 0) var isValid = false let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil, let jsonResponse = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let status = jsonResponse["status"] as? Int else { print("Receipt validation failed.") semaphore.signal() return } if status == 0, let receipt = jsonResponse["receipt"] as? [String: Any], let inApp = receipt["in_app"] as? [[String: Any]] { for purchase in inApp { if let expiresDateMS = purchase["expires_date_ms"] as? String, let expiresDate = Double(expiresDateMS) { let expiryDate = Date(timeIntervalSince1970: expiresDate / 1000.0) if expiryDate > Date() { isValid = true } } } } semaphore.signal() } task.resume() semaphore.wait() return isValid } }
0
0
312
Feb ’25
Using child accounts with sandbox IAP testing
Hello, thank you for your time. I'm using several physical devices to test IAPs in builds from xCode. Some of my test devices are logged into child accounts from my family account. Child accounts "Ask Permission" from devices logged into adult accounts in the family. when you attempt to make a purchase. I'm hoping to be able to use these devices to test my IAPs but I get the following error after supplying the password for the sandbox account: Unable to Ask Permission You can't ask permission because you have signed in with iCloud and iTunes accounts that are not associated with each other. [Environment: Sandbox] Is there any way to make this work?
2
0
985
Jan ’25
Issues with Integration of Promotional Offers in React Native app
Hi All, We are trying to integrate Promotional Offer in our app, We have a React Native app and are using react-native-iap for handling our in app purchases, as per the documentation we are generating signature in our BE and passing the proper details to the function as well, but for subscription request which have offer applied we are getting the apple pop up properly as well with offer details but when trying to subscribe it gives us SKErrroDomain: 12, for subscription without applying offer the subscription goes through but when we apply the offer we get the above error. Our app is currently in Development Stages and has not been sent for review sam for our subscription plans as well. Please let me know what could be the probable cause for this and help us resolve the issue. This is the code snippet of ours for the front end : export const buySubscription = async (subscriptionData: any) => { try { if (subscriptionData.offer_id) { const response = await getSubscriptionSignature( subscriptionData.productId, subscriptionData.offer_id, ); const offerData = response?.data; const offer = { identifier: offerData?.offer_id, keyIdentifier: offerData?.key_id, nonce: offerData?.nonce, signature: offerData?.signature, timestamp: Number(offerData?.timestamp), }; await requestSubscription({ sku: subscriptionData.productId, withOffer: offer, }); } else { await requestSubscription({ sku: subscriptionData.productId }); } } catch (err) { logger.error('Subscription error: ' + JSON.stringify(err)); throw err; } }; and 
from my python Backend which generates the signature:

def generate_signature(self, product_id: str, offer_id: str) -> dict: """ Generate signature for Apple StoreKit promotional offers. Args: product_id: The product identifier from App Store Connect offer_id: The promotional offer identifier Returns: dict: Contains signature and required metadata Reference: https://developer.apple.com/documentation/storekit/in-app_purchase/original_api_for_in-app_purchase/subscriptions_and_offers/implementing_promotional_offers_in_your_app """ try: # Generate UUID without dashes and use as nonce nonce = str(uuid.uuid4()) timestamp = get_current_time_ms() # milliseconds # Create the payload string in exact order required by Apple payload_components = [ self.bundle_id, # App Bundle ID self.key_id, # Key ID from App Store Connect product_id, # Product identifier offer_id, # Promotional offer identifier nonce, # UUID without dashes str(timestamp) # Current timestamp in milliseconds ] payload_str = "\u2063".join(payload_components) # Use Unicode separator logger.debug(f"Signing payload: {payload_str}") # Create SHA256 hash of the payload digest = hashes.Hash(hashes.SHA256()) digest.update(payload_str.encode('utf-8')) payload_hash = digest.finalize() # Sign the hash using ES256 (ECDSA with SHA-256) signature = self.private_key.sign( data=payload_hash, signature_algorithm=ec.ECDSA(hashes.SHA256()) ) # Encode signature in base64 signature_b64 = base64.b64encode(signature).decode('utf-8') logger.info(f"Generated signature for product {product_id} and offer {offer_id}") return { "key_id": self.key_id, # Changed to match Apple's naming "nonce": nonce, # UUID without dashes "timestamp": timestamp, # As integer "signature": signature_b64, # Base64 encoded signature "product_id": product_id, # Changed to match Apple's naming "offer_id": offer_id # Changed to match Apple's naming } except Exception as e: logger.error(f"Failed to generate signature: {str(e)}") raise HTTPException( status_code=500, detail=f"Failed to generate signature: {str(e)}" )
0
0
52
Apr ’25
[In-App Purchase] first trial but "is_trial_period" false
This question is about In-App Purchase. This is an inquiry from one of our customers. We have set up a free trial. This is your first time using the service, but you have stated that you have been charged. Document. https://developer.apple.com/documentation/appstorereceipts/is_trial_period 「You can use this value to determine whether the specific record is in a subscription trial period. If a previous subscription period in the receipt has the value "true" for either the is_trial_period or is_in_intro_offer_period keys, the user is not eligible for a free trial or introductory price within that subscription group.」 Our expectation is that is_trial_period is true. Receipt is not contain is_trial_period : true or is_in_intro_offer_period : true. Only one case has occurred. Other customers are no problem.
0
0
384
Dec ’24
Sandbox Testing Issue: 'Submit for Review' Button Missing for Subscription IAPSubmit
Hello Developers! I am trying to run a test In-App Purchase (IAP) for a renewable subscription product in the sandbox environment. I have set up everything required for sandbox testing, but it’s unclear whether the subscription product needs to be pre-approved by Apple for testing. If approval is required, I have already added the necessary metadata, but the status still shows "Ready for Submit." Additionally, when I save the page, a "Submit for Review" button briefly appears for a fraction of a second on the subscription page before disappearing. Is this button missing, or is there a known issue with this process? This is my first time running this test, and I would appreciate any pointers or suggestions. Thanks!
1
0
66
Mar ’25
How to validate Streamlined Purchasing with storekit 2
users download app with Streamlined Purchasing ,but the logic of checking subscription doesn't work. there the code: func checkSubscriptionStatus() async { for await entitlement in Transaction.currentEntitlements { guard case .verified(let transaction) = entitlement else { continue } if transaction.productID == monthlyProductID || transaction.productID == yearlyProductID { if transaction.revocationDate == nil && !transaction.isUpgraded { let activeSubscribed = transaction.expirationDate ?? .distantFuture > .now if activeSubscribed { hasActiveSubscription = activeSubscribed // other operation } } } } }
0
0
235
Mar ’25
Get the region currently used in the macOS App Store
How can I get the region region currently used in the macOS App Store? Preferably via Swift libraries, but any command / function will suffice. The following StoreKit property seems to always return the region for the Apple Account associated with my macOS user. await Storefront.current?.countryCode See the Apple docs. My macOS Apple Account region is US; in the App Store, when I sign into a different Apple Account whose region is GB (UK), Storefront.current?.countryCode continues to return US, not GB (or UK). I correctly see prices in pounds instead of in dollars, British spelling instead of American spelling, apps listed in my purchased tab for the UK (not the US) Apple Account, and, in the Account Settings dialog, the UK Apple Account email address, billing address & Country/Region set to United Kingdom. I didn't get any relevant results from the following command lines: defaults find GB defaults find UK defaults find uk-apple-id@example.com defaults find uk-apple-id The following didn't change after I signed into the UK Apple Account in the App Store: $ defaults read com.apple.AppStoreComponents { ASCLocaleID = "en-US@calendar=gregorian"; } Maybe Storefront.current?.countryCode only specifies the country code for the Storefront that will be used for in-app purchases, instead of for purchasing new apps from the App Store; maybe the former is tied to the Apple Account for the macOS user, instead of to the Apple Account for the App Store. If that's the case, what other mechanism can I use to obtain the country code for the App Store storefront?
0
0
55
Apr ’25
StoreKit2 currentEntitlements after downgrade followed by upgrade
I'm testing subscription downgrade and upgrade cycles in sandbox, and seeing a behavior I can't explain. Code is generally similar to WWDC sample code for StoreKit2, including listening to incoming transactions. Three entitlement levels, say, Standard, Plus, Pro Corresponding subscription plans all same duration (quarterly) I go through this purchase sequence quickly, Purchase the Pro plan Before the Pro plan expires, purchase the Standard plan Still before the Pro plan expires, purchase the Plus plan Transaction.currentEntitlements after each of the purchases (logged in transaction listener), After step 1: { Pro plan } After Step 2: { (only) Pro plan } After Step 3: { Plus plan , Pro plan } I was expecting to see {Standard, Pro } in entitlements after step 2 (user entitlement calculated from the set is still correct -- Pro). If that's not the case then why after step 3 entitlements includes both Plus and Pro plans?
2
0
516
Oct ’24
Example requests for Apple Server Notifications V2
Dear Apple Support, We are currently in the process of migrating from Apple Server Notifications v1 to v2. As you know, once we switch from v1 to v2 in App Store Connect, this change is irreversible. Our team needs to ensure that our backend environment, developed in Python with Django and using the app-store-server-library==1.5.0, is fully prepared to handle all possible notification types before making that final switch. While we can receive a basic test notification from Apple, it doesn’t provide the range of data or scenarios (e.g., INITIAL_BUY, RENEWAL, GRACE_PERIOD, etc.) that our code must be able to process, store in our database, and respond to accordingly. Without comprehensive, example-rich raw notification data, we are left guessing the structure and full scope of incoming v2 notifications. Could you please provide us with a set of raw, fully representative notification payloads for every notification type supported in v2? With these examples, we can simulate the entire lifecycle of subscription events, verify our logic, and confidently complete our migration. Thank you very much for your assistance.
1
0
448
Jan ’25
ASDServerErrorDomain Code=3512
有人遇到这个问题吗,在支付的时候提示未知错误,具体的错误信息如下: 交易失败,outTradeNo:2025022631999900326, productId:com.f6car.p0001, error:Err-or -Domain=SKErrorDomain Code=0 "发生未知错误" UserInfo={NSLocalizedDescription=发生未知错误, NSUnderlyingError=0x302f50120 {Error Domain=ASDServerErrorDomain Code=3512 "无效的应用程序外部版本。" UserInfo={NSLocalizedFailureReason=无效的应用程序外部版本。}}} 寻求解决方案,感谢.
0
0
226
Feb ’25
Using Storekit development, unsubscribe and resubscribe callback problem
The app subscription function uses StoreKit. After canceling the subscription, I try to subscribe again and get the following error. I remember it was working fine before iOS 18 was released. { NSLocalizedDescription = "\U53d1\U751f\U672a\U77e5\U9519\U8bef"; NSUnderlyingError = "Error Domain=ASDErrorDomain Code=825 "(null)""; } Hope you can help me solve this problem as soon as possible. Thanks
0
0
270
Jan ’25