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

Transitioning a freemium app to StoreKit 2
I'm currently working on transitioning to StoreKit 2. In order to see if my users are legacy users who purchased the app before I implemented an in-app purchase, I am trying to use the original purchase date for the app. Unfortunately, it's returning 0 seconds since 1970. func updateOriginalPurchaseStatus() async throws { let transaction = try await checkVerified(AppTransaction.shared) self.originalPurchaseVersion = transaction.originalAppVersion self.originalPurchaseDate = transaction.originalPurchaseDate } This is from the transaction: [3] = { key = "originalPurchaseDate" value = number (number = 0) } Currently trying to figure out when I actually purchased the app, but it might be as early as 2012. And I likely used a download code.
2
0
236
Mar ’25
Unable to make a sandbox purchasing with SubscriptionStoreView
Hi I'm writing my first in-app purchase app, and I'm trying to do some testing with sandbox accounts. I wrote my subscription page use SwiftUI SubscriptionStoreView. And I read the documentation it says : The sandbox account appears in Settings > App Store after the first time you use the device to attempt a purchase in a development-signed app. But I have no idea how to make a sandbox purchasing. Every time I click the subscription button it just making a purchase in xcode environment. Did I missed anything? What can I do to make a sandbox pruchasing?
2
0
482
Oct ’24
StoreKit 2 – IAP Subscriptions Not Appearing in Sandbox
I am experiencing an issue with my iOS app where StoreKit 2 in-app subscriptions are not appearing when using Product.products(for:). I have done all the necessary configurations, but the products still return an empty array ([]). Here are the details of my setup: • App ID / Bundle ID: com.tstore.vocabely • Product IDs: • com.tstore.vocabely.base • com.tstore.vocabely.pro • com.tstore.vocabely.ultimate • Paid Apps Agreement: Active • IAP Status in App Store Connect: Ready to Submit / Approved • Testing Environment: • Device: iPhone (real device) • iOS Version: [insert your iOS version] • Xcode Version: [insert your Xcode version] • Sandbox Tester Account used • Code Snippet: Using Product.products(for: productIDs) in StoreKitManager to fetch products I have verified: • Product IDs match exactly with App Store Connect • Paid Apps Agreement is Active • Using a real device, not a simulator • Sandbox account is properly signed in Despite all of this, fetchProducts() still returns an empty array. Could you please assist me in troubleshooting why my subscriptions are not appearing in the Sandbox environment? Thank you for your support.
2
0
96
Aug ’25
Receiving 404 Error for APNs Server Notifications When Validating signedPayload
Hi everyone, I'm experiencing an issue with APNs server notifications where I receive a 404 error when trying to validate the signedPayload from Apple's notification. Below is a sanitized version of my code: class ServerNotificationAppleController extends Controller { // URL for StoreKit keys (Sandbox environment) private $storeKitKeysUrl = 'https://api.storekit-sandbox.itunes.apple.com/inApps/v1/keys'; public function handleNotification(Request $request) { \Log::info($request); $signedPayload = $request->input('signedPayload'); if (!$signedPayload) { return response()->json(['error' => 'signedPayload not provided'], 400); } // Step 1: Create your JWT token (token creation logic can be in a separate service) $jwtToken = $this->generateAppleJWT(); // Step 2: Send a request to the StoreKit keys endpoint $response = Http::withHeaders([ 'Authorization' => 'Bearer ' . $jwtToken, ])->get($this->storeKitKeysUrl); Log::info('Apple Keys Status:', ['status' => $response->status()]); Log::info('Apple Keys Body:', ['body' => $response->body()]); if ($response->status() !== 200) { return response()->json(['error' => "Apple public keys couldn't be retrieved"], 401); } $keysData = $response->json(); // Step 3: Validate the signedPayload $validatedPayload = $this->validateSignedPayload($signedPayload, $keysData); if (!$validatedPayload) { return response()->json(['error' => 'Invalid signedPayload'], 400); } // Process the validated data as needed Log::info("Apple Purchase Data:", (array)$validatedPayload); return response()->json(['message' => 'Notification processed successfully'], 200); } private function generateAppleJWT() { // API key details (replace placeholders with actual values) $keyId = config('services.apple.key_id'); // e.g., <YOUR_KEY_ID> $issuerId = config('services.apple.issuer_id'); // e.g., <YOUR_ISSUER_ID> $privateKey = file_get_contents(storage_path(config('services.apple.private_key'))); // Set current UTC time and expiration time (20 minutes later) $nowUtc = Carbon::now('UTC'); $expirationUtc = $nowUtc->copy()->addMinutes(20); // Create the payload with UTC timestamps $payload = [ 'iss' => $issuerId, 'iat' => $nowUtc->timestamp, 'exp' => $expirationUtc->timestamp, 'aud' => 'appstoreconnect-v1', 'bid' => 'com.example.app', // Replace with your Bundle ID if necessary ]; // Generate the JWT token return JWT::encode($payload, $privateKey, 'ES256', $keyId); } private function validateSignedPayload($signedPayload, $keysData) { try { $jwkKeys = JWK::parseKeySet($keysData); return JWT::decode($signedPayload, $jwkKeys, ['RS256']); } catch (\Exception $e) { Log::error("Apple Purchase Validation Error: " . $e->getMessage()); return null; } } } I’m particularly puzzled by the fact that I receive a 404 error when trying to retrieve the public keys from the StoreKit keys endpoint. Has anyone encountered this issue or can provide insight into what might be causing the error? Any help or suggestions would be greatly appreciated. Thanks!
2
0
350
Mar ’25
What happens if the transaction is not finished?
For auto-renewable subscriptions, it is necessary to call the transaction completion after the purchase. I understand that this needs to be called at the correct timing. StoreKit v1: https://developer.apple.com/documentation/storekit/in-app_purchase/original_api_for_in-app_purchase/finishing_a_transaction Question If the transaction does not finish for a long period, is the purchase cancelled and a refund issued? If so, how long is this period? For example case1: When I renewed the auto-renewable subscription from the OS settings app but did not open my own app. case2: When there was a malfunction in my own app. Similar forum https://developer.apple.com/forums/thread/656255
2
1
493
Oct ’24
IAP receipt validation fails with status code: 21002
I have implemented IAP. The purchases are successful. The refresh receipt is working fine, which then calls the requestDidFinish(_ request: SKRequest) delegate. I'm fetching the receipt url through 'Bundle.main.appStoreReceiptURL'. When I convert the receipt data in base64 string and send it to app store's sandbox api and try to validate the receipt, it fails giving status code : 21002.
2
0
99
Aug ’25
In iOS 26 beta3 version, the finishTransaction method is unable to remove transactions from the SKPaymentQueue, causing transactions to remain in the queue even after being processed.
We have some users who have upgraded to iOS 26 beta3. Currently, we observe that when these users make in-app purchases, our code calls [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; method, and we clearly receive the successful removal callback in the delegate method - (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray<SKPaymentTransaction *> *)transactions. However, when users click on products with the same productId again, the method - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions still returns information about previously removed transactions, preventing users from making further in-app purchases.
2
2
432
Jul ’25
DID_FAIL_TO_RENEW Notification with a null gracePeriodExpiresDate
We are seeking clarification on the behavior of App Store Server Notifications V2. Summary In our production environment, we received a notification with notificationType: DID_FAIL_TO_RENEW and subtype: GRACE_PERIOD. However, the gracePeriodExpiresDate field in the payload was null. We understand this notification indicates that a user's subscription has entered a grace period. The null value for its expiration date is unexpected, and we are looking for an official explanation of this behavior and the correct way to handle it. The Scenario Here are the details of the notification we received: Notification Type: DID_FAIL_TO_RENEW Notification Subtype: GRACE_PERIOD Environment: Production Upon decoding the signedRenewalInfo JWS from the responseBodyV2, we found that the gracePeriodExpiresDate field inside the JWSRenewalInfoDecodedPayload was null. The notificationUUID for this event was in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. Our Implementation and its Impact Our backend is designed to ensure service continuity during a grace period, as recommended in the documentation. Current Logic: Receive the DID_FAIL_TO_RENEW / GRACE_PERIOD notification. Extract the gracePeriodExpiresDate. Extend the user's subscription expiration date in our database to match this date. Because the gracePeriodExpiresDate was null in this case, our logic failed, creating a risk of service interruption for the user. Context and Investigation We have performed the following checks: App Store Connect Settings: We have confirmed that Billing Grace Period is enabled for the relevant subscription group. Sandbox Environment: We have been unable to reproduce this scenario in the Sandbox. User Context: We believe the user in this case was experiencing a failed payment when attempting to renew for the first time after a free trial period. Questions To ensure we handle this scenario correctly, we would appreciate clarification on the following points: Conditions for Null: Under what specific conditions does a DID_FAIL_TO_RENEW notification with a GRACE_PERIOD subtype contain a null gracePeriodExpiresDate? Expected Behavior: Is this null value an expected behavior for certain scenarios, such as the first failed renewal after a free trial? Best Practice: If this is an expected behavior, what is the correct way to handle it? How should our backend interpret a null gracePeriodExpiresDate to ensure service continuity for the user?
2
2
144
Jul ’25
[macOS] AppTransaction questions (internet connection requirement)
Hello, I hope to find out more about how AppTransaction works on macOS, specifically about its internet connection requirements: if I use this to validate that the app is a legit purchase from the Mac App Store, I would not want it to have an always-on requirement just to validate. Does AppTransaction require the user to always be online for AppTransaction.shared ? When an app is downloaded from the Mac App Store, is the data needed for AppTransaction automatically embedded during that download, or is that data downloaded upon first launch of the app, therefore requiring an internet connection at launch time? Once the data/receipt has been downloaded by AppTransaction, is it cached until the app's next update, or is it cleared at some time during the version's life and needs to be re-downloaded, therefore requiring an internet connection at launch? Where is that receipt/data stored? Also, if you don't mind me sneaking in this non-related but sort of related question, in terms of receipt validation: Does macOS Sequoia's MAC address rotation feature affect receipt validation in any way when using IOKit? Thank you kindly, – Matthias
2
4
568
Apr ’25
Unable to retrieve data from In App Purchase
I want to add in-app purchasing to my app, but I can't figure out what part of my workflow is wrong. I created a product for my app in iTunes Connect (the product ID is com.mycompany.products.***) and it's in "Ready to submit" status. I created a sandbox test user for this app. I connected to iTunes on a real device using the sandbox AppleID. I went back to XCode and added in-app purchasing to my app. I turned on developer mode on the real device and logged in as the sandbox user. I built the app and ran it on a real device (not the simulator). I tried to get product information (com.mycompany.products.***) but nothing was returned. In-app purchasing is registered in App Store Connect and the status is "Ready to submit". The code only retrieves product information in a simple way, so I don't think there's a problem. inAppPurchase.getProducts(["com.mycompany.products.***"]).then(console.log).catch(console.error); But it only returns an empty array. What could be wrong? Any help would be much appreciated.
2
1
56
Jul ’25
Non-consumable IAP for free trial
Hello. My newly released app includes a 1 day free trial. I've done this by creating a non-consumable in-app purchase priced at 0. I consider the free trial active if there's a transaction (from Transaction.currentEntitlements) for that product such that transaction.originalPurchaseDate is less than 24 hours ago. This works fine locally in the simulator and also in TestFlight, however it does not seem to work in the actual app from the App Store. The user can "purchase" it fine; they see the purchase sheet with the product name and the $0.00 price, and when they double press the side button it all seems to work. However, the app then behaves as if it didn't work. The free trial product is no longer available though. One thing is that I didn't follow the naming convention “XX-day Trial”. Could that be the problem? If so, is that meant to be for the product reference name?
2
0
295
Feb ’25
Production review failed because IAP products cannot be loaded
My app has a couple of consumable IAP items. I have tested this extensively and it works in all test scenarios including loads of beta testers using testflight. However, Apple's production reviewer reports that loading of the products hangs in their setup. This is very frustrating as I have no means of recreating the problem. My first product was tested ok an all my IAP items are approved for release. However, I did not explicitly assign them to my build. I read somewhere that you need to do that but could not find in App Store Connect after my first product was approved. Below is the relevant code section. What am I missing? class DonationManager: NSObject, ObservableObject, SKProductsRequestDelegate, SKPaymentTransactionObserver { @Published var products: [SKProduct] = [] // This is observed by a view. But apparently that view never gets populated in Apple's production review setup @Published var isPurchasing: Bool = false @Published var purchaseMessage: String? = nil let productIDs: Set<String> = ["Donation_5", "Donation_10", "Donation_25", "Donation_50"] override init() { super.init() SKPaymentQueue.default().add(self) fetchProducts() } deinit { SKPaymentQueue.default().remove(self) } func fetchProducts() { print("Attempting to fetch products with IDs: \(productIDs)") let request = SKProductsRequest(productIdentifiers: productIDs) request.delegate = self request.start() } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { DispatchQueue.main.async { self.products = response.products.sorted { $0.price.compare($1.price) == .orderedAscending } print("Successfully fetched \(self.products.count) products.") if !response.invalidProductIdentifiers.isEmpty { print("Invalid Product Identifiers: \(response.invalidProductIdentifiers)") self.purchaseMessage = NSLocalizedString("Some products could not be loaded. Please check App Store Connect.", comment: "") } else if self.products.isEmpty { print("No products were fetched. This could indicate a problem with App Store Connect configuration or network.") self.purchaseMessage = NSLocalizedString("No products available. Please try again later.", comment: "") } } } ...and the view showing the items: @StateObject private var donationManager = DonationManager() var body: some View { VStack(spacing: 24) { Spacer() // Donation options ------------------- if donationManager.products.isEmpty { ProgressView(NSLocalizedString("Loading donation options...", comment: "")) .foregroundColor(DARK_BROWN) .italic() .font(.title3) .padding(.top, 16) } else { ForEach(donationManager.products, id: \.self) { product in Button(action: { donationManager.buy(product: product) }) { HStack { Image(systemName: "cup.and.saucer.fill") .foregroundColor(.pink) Text("\(product.localizedTitle) \(product.priceLocale.currencySymbol ?? "$")\(product.price)") } .buttonStyle() } .disabled(donationManager.isPurchasing) } }
2
0
176
Jul ’25
Transaction.currentEntitlements returning empty response
Hi there 👋🏻 We are facing an issue that started on 24 June 2025 where some users that have an active subscription with an offer are not being able to use/restore their subscription since Transaction.currentEntitlements is empty. We have tried to call the server with this endpoint https://developer.apple.com/documentation/appstoreserverapi/get-transaction-history and it's returning the correct transactions correctly. Any idea what is happening?
2
4
178
Jun ’25
Mac Appstore StoreKit 2 - validate purchase & where is purchase receipt cached?
This is re-posted from this Stack Overflow post. I am looking at validating the purchase of a paid app from Mac AppStore. Based on this WWDC video about StoreKit 2, I am attempting to this with AppTransaction. I have not found meaningful high-level documentation about this specific use case beyond that. My approach is to first get the "cached" AppTransaction by calling AppTransaction.shared. If that is not there I proceed to getting it from Apple, via AppTransaction.refresh(). If they don't have it, or when the network is down, the user automagically gets the familiar "log in to your store account" UI that has been around as long as the Mac AppStore. Once I have the AppTransaction I use it to verify we are on the right device, using code like this, where the returned Bool represents validation success: guard let deviceVID = AppStore.deviceVerificationID?.uuidString.lowercased() else { return false } let nonce = appTransaction.deviceVerificationNonce.uuidString.lowercased() let combo = nonce + deviceVID let digest = SHA384.hash(data: Data(combo.utf8)) return (digest == appTransaction.deviceVerification) My first question is: Does that look like the right approach? Is there something else I should do, or check? My second question is around testing this approach. Refreshing the AppTransaction in the sandbox invariably yields a valid item, even if the app version does not yet exist in AppStoreConnect. This is also the case when I log out in the App Store app on the Mac. This makes me think it is using my AppleID which I am logged into in System Settings. Does that sound right? I would like to be able to remove / delete the cached AppTransactions - where might I find those on the system? Thanks for everyone's help!
2
1
1.7k
Oct ’24
Facing issue on getting inApp procuts
I have created 5 consumable products on store but when i am trying to check on mobile using xcode with debug mode i am get fetching products successfully can u guys help me out why its happening. here is debug error --IAPTest[5101:295128] UnityIAP: Requesting 5 products --IAPTest[5101:295128] UnityIAP: Requesting product data... --IAPTest[5101:295371] UnityIAP: Received 0 products and 5 invalid products i have test same project with another apple account's app bundle ID or iAP products its working fine have a look of those app's debug screen show Perfect Not Perfect
2
1
377
Nov ’24
Incorrect storefront country code
Both the legacy StoreKit API and the new StoreKit 2 API return the incorrect storefront countryCode. My actual Apple ID region is Germany, and my Sandbox test user is set to France, yet the SDK consistently returns USA. Expected Results: The returned storefront countryCode should reflect the correct region - sandbox user region if signed in and real user region if not signed in with sandbox). Actual Results: Returned country code is USA with both SKPaymentQueue.default().storefront?.countryCode and await Storefront.current?.countryCode. Signing out/in, device reboot and even reset do not help, I'm stuck with USA storefront.
2
0
113
May ’25
Sandbox user can't see StoreKit subscriptions
Hi everyone, I’m struggling to get StoreKit 2 to fetch products in my SwiftUI app while using a sandbox user. I think I’ve followed all necessary setup steps in Xcode, App Store Connect, and my physical test device, but Product.products(for:) always returns an empty array. I’d appreciate any insights! What I’ve Done Local App Setup (Xcode 16.2) Created a blank SwiftUI Xcode project. Enabled In-App Purchase capability under Signing & Capabilities. Implemented minimal StoreKit 2 code to fetch available products (see below). Using the correct bundle identifier, which matches App Store Connect. App Store Connect Configuration Registered the app with the same bundle identifier. Created an Auto-Renewable Subscription with: Product ID: v1 (matches my code). All fields filled (pricing, localization, etc.). Status: Ready for Review. Linked the subscription to the latest app version in App Store Connect. Sandbox User & Testing Setup Created a sandbox tester account. Logged in with the sandbox user under Settings → Developer → Sandbox Apple ID. This was on my physical device (iOS 18.2). Installed and ran the app directly from Xcode (⌘+R). Issue: StoreKit Returns No Products Product.products(for:) does not return any products. There are no errors thrown, just an empty array. I confirmed that StoreKit Configuration is set to None in Xcode. No StoreKit-related logs appear in the Console. Code Snippets //StoreKitManager.swift import StoreKit import SwiftUI @MainActor class StoreKitManager: ObservableObject { @Published var products: [Product] = [] @Published var errorMessage: String? func fetchProducts() async { do { let productIDs: Set<String> = ["v1"] // Matches App Store Connect let fetchedProducts = try await Product.products(for: productIDs) print(fetchedProducts) // Debug output DispatchQueue.main.async { self.products = fetchedProducts } } catch { DispatchQueue.main.async { self.errorMessage = "Failed to fetch products: \(error.localizedDescription)" } } } } //ContentView.swift import SwiftUI struct ContentView: View { @StateObject private var storeKitManager = StoreKitManager() var body: some View { VStack { if let errorMessage = storeKitManager.errorMessage { Text(errorMessage).foregroundColor(.red) } else if storeKitManager.products.isEmpty { Text("No products available") } else { List(storeKitManager.products, id: \.id) { product in VStack(alignment: .leading) { Text(product.displayName).font(.headline) Text(product.description).font(.subheadline) Text("\(product.price.formatted(.currency(code: product.priceFormatStyle.currencyCode ?? "USD")))") .bold() } } } Button("Fetch Products") { Task { await storeKitManager.fetchProducts() } } } .padding() .onAppear { Task { await storeKitManager.fetchProducts() } } } } #Preview { ContentView() } Additional Information iOS Version: 18.2 Xcode Version: 16.2 macOS Version: 15.3.1 Device: Physical iPhone (not simulator) TestFlight Build: Not used (app is run directly from Xcode) StoreKit Configuration: Set to None
2
0
373
Mar ’25
Consumable in-app purchases
I implemented consumable in-app purchases in an iPhone app using StoreKit's ProductView(). When I tap the payment button in ProductView(), I am taken to the payment screen and once the payment is completed, the desired code appears to be executed, so there doesn't seem to be a problem, but when I tap the payment button in ProductView() again, the desired code is executed without being taken to the payment screen. So one payment can be used any number of times. I thought I wrote it exactly according to the reference, but will it be okay in a production environment? Is there any code that is necessary?
2
0
202
Jul ’25