@capgo/native-purchases 7.19.3: its iOS source as built into the ExpoCards iPhone app ============================================================================== This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. Original: the npm package @capgo/native-purchases, version 7.19.3 (https://www.npmjs.com/package/@capgo/native-purchases/v/7.19.3), from https://github.com/Cap-go/capacitor-native-purchases, by Martin Donadieu (Capgo) and its contributors. The iPhone app is built with the three Swift files below and nothing else of the plugin: its Android part is left out of the Android app, and its JavaScript is not used. Modified by ExpoCards (tools/patch-storekit.mjs), in one file, NativePurchasesPlugin.swift, in its listener for StoreKit's Transaction.updates. Two edits: 1. it no longer calls transaction.finish() itself: the app finishes a purchase once its server has added it; 2. its "transactionUpdated" event is kept until the app is listening (retainUntilConsumed: true), so an early one is not dropped. The change, as a diff of that listener: - await transaction.finish() - try? await Task.sleep(nanoseconds: 500_000_000) - await MainActor.run { - self?.notifyListeners("transactionUpdated", data: payload) - } + // ExpoCards patch (tools/patch-storekit.mjs): not finished here. The app finishes it + // (acknowledgePurchase) once its server has added the purchase, + // and the event waits for the app's listener instead of being dropped. + try? await Task.sleep(nanoseconds: 500_000_000) + await MainActor.run { + self?.notifyListeners("transactionUpdated", data: payload, retainUntilConsumed: true) + } The other two files are unchanged. Each file follows in full. ------------------------------------------------------------------------------ File: ios/Sources/NativePurchasesPlugin/NativePurchasesPlugin.swift (modified by ExpoCards, as above) ------------------------------------------------------------------------------ import Foundation import Capacitor import StoreKit @objc(NativePurchasesPlugin) public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin { public let identifier = "NativePurchasesPlugin" public let jsName = "NativePurchases" public let pluginMethods: [CAPPluginMethod] = [ CAPPluginMethod(name: "isBillingSupported", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "purchaseProduct", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "restorePurchases", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getProducts", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getProduct", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getPurchases", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "manageSubscriptions", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "acknowledgePurchase", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "consumePurchase", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getAppTransaction", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "isEntitledToOldBusinessModel", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getStorefront", returnType: CAPPluginReturnPromise) ] private let pluginVersion: String = "7.19.3" private var transactionUpdatesTask: Task? @objc func getPluginVersion(_ call: CAPPluginCall) { call.resolve(["version": self.pluginVersion]) } override public func load() { super.load() startTransactionUpdatesListener() } deinit { transactionUpdatesTask?.cancel() transactionUpdatesTask = nil } private func startTransactionUpdatesListener() { transactionUpdatesTask?.cancel() transactionUpdatesTask = Task.detached { [weak self] in for await result in Transaction.updates { guard !Task.isCancelled else { break } switch result { case .verified(let transaction): let payload = await TransactionHelpers.buildTransactionResponse( from: transaction, jwsRepresentation: result.jwsRepresentation, alwaysIncludeWillCancel: true ) // ExpoCards patch (tools/patch-storekit.mjs): not finished here. The app finishes it // (acknowledgePurchase) once its server has added the purchase, // and the event waits for the app's listener instead of being dropped. try? await Task.sleep(nanoseconds: 500_000_000) await MainActor.run { self?.notifyListeners("transactionUpdated", data: payload, retainUntilConsumed: true) } case .unverified(let transaction, let error): await MainActor.run { self?.notifyListeners("transactionVerificationFailed", data: [ "transactionId": String(transaction.id), "error": error.localizedDescription ]) } } } } } @objc func isBillingSupported(_ call: CAPPluginCall) { call.resolve(["isBillingSupported": true]) } @objc func getStorefront(_ call: CAPPluginCall) { print("getStorefront") Task { let storefront = await Storefront.current await MainActor.run { if let storefront = storefront { call.resolve([ "countryCode": storefront.countryCode, "storefrontId": storefront.id ]) } else { // No storefront (e.g. alternative distribution). print("getStorefront: no storefront available") call.resolve(["countryCode": ""]) } } } } @objc func purchaseProduct(_ call: CAPPluginCall) { print("purchaseProduct") let productIdentifier = call.getString("productIdentifier", "") let quantity = call.getInt("quantity", 1) let appAccountToken = call.getString("appAccountToken") let autoAcknowledge = call.getBool("autoAcknowledgePurchases") ?? true if productIdentifier.isEmpty { call.reject("productIdentifier is Empty, give an id") return } print("Auto-acknowledge enabled: \(autoAcknowledge)") Task { @MainActor in do { let products = try await Product.products(for: [productIdentifier]) guard let product = products.first else { call.reject("Cannot find product for id \(productIdentifier)") return } var purchaseOptions = Set() purchaseOptions.insert(.quantity(quantity)) if let token = appAccountToken, !token.isEmpty, let uuid = UUID(uuidString: token) { purchaseOptions.insert(.appAccountToken(uuid)) } let result = try await product.purchase(options: purchaseOptions) print("purchaseProduct result \(result)") await self.handlePurchaseResult(result, call: call, autoFinish: autoAcknowledge) } catch { print(error) call.reject(error.localizedDescription) } } } @MainActor private func handlePurchaseResult( _ result: Product.PurchaseResult, call: CAPPluginCall, autoFinish: Bool ) async { switch result { case let .success(verificationResult): switch verificationResult { case .verified(let transaction): let response = await TransactionHelpers.buildTransactionResponse( from: transaction, jwsRepresentation: verificationResult.jwsRepresentation ) if autoFinish { print("Auto-finishing transaction: \(transaction.id)") await transaction.finish() } else { print("Manual finish required for transaction: \(transaction.id)") } call.resolve(response) case .unverified(_, let error): call.reject(error.localizedDescription) } case .pending: call.reject("Transaction pending") case .userCancelled: call.reject("User cancelled") @unknown default: call.reject("Unknown error") } } @objc func restorePurchases(_ call: CAPPluginCall) { print("restorePurchases") Task { do { try await AppStore.sync() for transaction in SKPaymentQueue.default().transactions { SKPaymentQueue.default().finishTransaction(transaction) } await MainActor.run { call.resolve() } } catch { await MainActor.run { call.reject(error.localizedDescription) } } } } @objc func getProducts(_ call: CAPPluginCall) { let productIdentifiers = call.getArray("productIdentifiers", String.self) ?? [] let productType = call.getString("productType", "inapp") print("productIdentifiers \(productIdentifiers)") print("productType \(productType)") Task { do { let products = try await Product.products(for: productIdentifiers) print("products \(products)") let productsJson: [[String: Any]] = products.map { $0.dictionary } await MainActor.run { call.resolve(["products": productsJson]) } } catch { print("error \(error)") await MainActor.run { call.reject(error.localizedDescription) } } } } @objc func getProduct(_ call: CAPPluginCall) { let productIdentifier = call.getString("productIdentifier") ?? "" let productType = call.getString("productType", "inapp") print("productIdentifier \(productIdentifier)") print("productType \(productType)") if productIdentifier.isEmpty { call.reject("productIdentifier is empty") return } Task { do { let products = try await Product.products(for: [productIdentifier]) print("products \(products)") if let product = products.first { await MainActor.run { call.resolve(["product": product.dictionary]) } } else { await MainActor.run { call.reject("Product not found") } } } catch { print(error) await MainActor.run { call.reject(error.localizedDescription) } } } } @objc func getPurchases(_ call: CAPPluginCall) { print("getPurchases") let appAccountTokenFilter = call.getString("appAccountToken") Task { let allPurchases = await TransactionHelpers.collectAllPurchases( appAccountTokenFilter: appAccountTokenFilter ) await MainActor.run { call.resolve(["purchases": allPurchases]) } } } @objc func manageSubscriptions(_ call: CAPPluginCall) { print("manageSubscriptions") Task { @MainActor in do { guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { call.reject("Unable to get window scene") return } try await AppStore.showManageSubscriptions(in: windowScene) call.resolve() } catch { print("manageSubscriptions error: \(error)") call.reject(error.localizedDescription) } } } @objc func acknowledgePurchase(_ call: CAPPluginCall) { print("acknowledgePurchase called on iOS") guard let purchaseToken = call.getString("purchaseToken") else { call.reject("purchaseToken is required") return } guard let transactionId = UInt64(purchaseToken) else { call.reject("Invalid purchaseToken format") return } Task { var foundTransaction: Transaction? for await verificationResult in Transaction.all { if case .verified(let transaction) = verificationResult, transaction.id == transactionId { foundTransaction = transaction break } } guard let transaction = foundTransaction else { await MainActor.run { call.reject("Transaction not found or already finished. Transaction ID: \(transactionId)") } return } print("Manually finishing transaction: \(transaction.id)") await transaction.finish() await MainActor.run { print("Transaction finished successfully") call.resolve() } } } @objc func consumePurchase(_ call: CAPPluginCall) { call.reject("consumePurchase is only available on Android") } } // MARK: - iOS 16+ App Transaction Methods extension NativePurchasesPlugin { @objc func getAppTransaction(_ call: CAPPluginCall) { if #available(iOS 16.0, *) { Task { @MainActor in await self.handleGetAppTransaction(call) } } else { call.reject("App Transaction requires iOS 16.0 or later") } } @objc func isEntitledToOldBusinessModel(_ call: CAPPluginCall) { guard let targetBuildNumber = call.getString("targetBuildNumber"), !targetBuildNumber.isEmpty else { call.reject("targetBuildNumber is required on iOS") return } if #available(iOS 16.0, *) { Task { @MainActor in await self.handleIsEntitledToOldBusinessModel(call, targetBuildNumber: targetBuildNumber) } } else { call.reject("App Transaction requires iOS 16.0 or later") } } @available(iOS 16.0, *) @MainActor private func handleGetAppTransaction(_ call: CAPPluginCall) async { print("getAppTransaction called on iOS") do { let verificationResult = try await AppTransaction.shared switch verificationResult { case .verified(let appTransaction): let response: [String: Any] = [ "originalAppVersion": appTransaction.originalAppVersion, "originalPurchaseDate": ISO8601DateFormatter().string( from: appTransaction.originalPurchaseDate ), "bundleId": appTransaction.bundleID, "appVersion": Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "", "jwsRepresentation": verificationResult.jwsRepresentation, "environment": appTransaction.environment.environmentString ] call.resolve(["appTransaction": response]) case .unverified(_, let error): call.reject("App transaction verification failed: \(error.localizedDescription)") } } catch { print("getAppTransaction error: \(error)") call.reject("Failed to get app transaction: \(error.localizedDescription)") } } @available(iOS 16.0, *) @MainActor private func handleIsEntitledToOldBusinessModel( _ call: CAPPluginCall, targetBuildNumber: String ) async { print("isEntitledToOldBusinessModel called with targetBuildNumber: \(targetBuildNumber)") do { let verificationResult = try await AppTransaction.shared switch verificationResult { case .verified(let appTransaction): let originalBuildNumber = appTransaction.originalAppVersion let originalInt = Int(originalBuildNumber) ?? 0 let targetInt = Int(targetBuildNumber) ?? 0 call.resolve([ "isOlderVersion": originalInt < targetInt, "originalAppVersion": originalBuildNumber ]) case .unverified(_, let error): call.reject("App transaction verification failed: \(error.localizedDescription)") } } catch { print("isEntitledToOldBusinessModel error: \(error)") call.reject("Failed to get app transaction: \(error.localizedDescription)") } } } @available(iOS 16.0, *) private extension AppStore.Environment { var environmentString: String { switch self { case .sandbox: return "Sandbox" case .production: return "Production" case .xcode: return "Xcode" default: return "Production" } } } ------------------------------------------------------------------------------ File: ios/Sources/NativePurchasesPlugin/Product+CapacitorPurchasesPlugin.swift (unchanged) ------------------------------------------------------------------------------ // // Extensions.swift // CapgoCapacitorPurchases // // Created by Martin DONADIEU on 2023-08-08. // import Foundation import StoreKit extension Product { var dictionary: [String: Any] { // /** // * Currency code for price and original price. // */ // readonly currencyCode: string; // /** // * Currency symbol for price and original price. // */ // readonly currencySymbol: string; // /** // * Boolean indicating if the product is sharable with family // */ // readonly isFamilyShareable: boolean; // /** // * Group identifier for the product. // */ // readonly subscriptionGroupIdentifier: string; // /** // * The Product subscription group identifier. // */ // readonly subscriptionPeriod: SubscriptionPeriod; // /** // * The Product introductory Price. // */ // readonly introductoryPrice: SKProductDiscount | null; // /** // * The Product discounts list. // */ // readonly discounts: SKProductDiscount[]; return [ "identifier": self.id, "description": self.description, "title": self.displayName, "price": self.price, "priceString": self.displayPrice, "currencyCode": self.priceFormatStyle.currencyCode, "isFamilyShareable": self.isFamilyShareable ] } } ------------------------------------------------------------------------------ File: ios/Sources/NativePurchasesPlugin/TransactionHelpers.swift (unchanged) ------------------------------------------------------------------------------ import Foundation import StoreKit internal class TransactionHelpers { static func buildTransactionResponse( from transaction: Transaction, jwsRepresentation: String? = nil, alwaysIncludeWillCancel: Bool = false ) async -> [String: Any] { var response: [String: Any] = ["transactionId": String(transaction.id)] if alwaysIncludeWillCancel { response["willCancel"] = NSNull() } addReceiptAndJws(to: &response, jws: jwsRepresentation) addTransactionDetails(to: &response, transaction: transaction) if transaction.productType == .autoRenewable { addSubscriptionInfo(to: &response, transaction: transaction) await addRenewalInfo(to: &response, transaction: transaction) } return response } private static func addReceiptAndJws(to response: inout [String: Any], jws: String?) { if let receiptBase64 = getReceiptData() { response["receipt"] = receiptBase64 } if let jws = jws { response["jwsRepresentation"] = jws } } private static func addTransactionDetails(to response: inout [String: Any], transaction: Transaction) { response["productIdentifier"] = transaction.productID response["purchaseDate"] = ISO8601DateFormatter().string(from: transaction.purchaseDate) response["productType"] = transaction.productType == .autoRenewable ? "subs" : "inapp" response["isUpgraded"] = transaction.isUpgraded response["ownershipType"] = transaction.ownershipType.descriptionString if let revocationDate = transaction.revocationDate { response["revocationDate"] = ISO8601DateFormatter().string(from: revocationDate) } if let revocationReason = transaction.revocationReason { response["revocationReason"] = revocationReason.descriptionString } if #available(iOS 17.0, *) { response["transactionReason"] = transaction.reason.descriptionString } if #available(iOS 16.0, *) { response["environment"] = transaction.environment.descriptionString } if let token = transaction.appAccountToken { response["appAccountToken"] = token.uuidString } } static func getReceiptData() -> String? { guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path), let receiptData = try? Data(contentsOf: appStoreReceiptURL) else { return nil } return receiptData.base64EncodedString() } static func addSubscriptionInfo(to response: inout [String: Any], transaction: Transaction) { response["originalPurchaseDate"] = ISO8601DateFormatter().string( from: transaction.originalPurchaseDate ) if let expirationDate = transaction.expirationDate { response["expirationDate"] = ISO8601DateFormatter().string(from: expirationDate) response["isActive"] = expirationDate > Date() } } static func addRenewalInfo(to response: inout [String: Any], transaction: Transaction) async { guard let subscriptionStatus = await transaction.subscriptionStatus else { response["willCancel"] = NSNull() return } response["subscriptionState"] = subscriptionStatus.state.descriptionString if subscriptionStatus.state == .subscribed { if case .verified(let value) = subscriptionStatus.renewalInfo { response["willCancel"] = !value.willAutoRenew } else { response["willCancel"] = NSNull() } } else { response["willCancel"] = NSNull() } } static func collectAllPurchases(appAccountTokenFilter: String?) async -> [[String: Any]] { var allPurchases: [[String: Any]] = [] var seenIds = Set() for await result in Transaction.currentEntitlements { guard case .verified(let transaction) = result else { continue } if let filter = appAccountTokenFilter, transaction.appAccountToken?.uuidString != filter { continue } let idStr = String(transaction.id) seenIds.insert(idStr) let data = await buildTransactionResponse( from: transaction, jwsRepresentation: result.jwsRepresentation ) allPurchases.append(data) } for await result in Transaction.all { guard case .verified(let transaction) = result else { continue } if let filter = appAccountTokenFilter, transaction.appAccountToken?.uuidString != filter { continue } let idStr = String(transaction.id) if seenIds.contains(idStr) { continue } let data = await buildTransactionResponse( from: transaction, jwsRepresentation: result.jwsRepresentation ) allPurchases.append(data) } return allPurchases } } private extension Transaction.RevocationReason { var descriptionString: String { switch self { case .developerIssue: return "developerIssue" case .other: return "other" default: return "unknown" } } } @available(iOS 17.0, *) private extension Transaction.Reason { var descriptionString: String { switch self { case .purchase: return "purchase" case .renewal: return "renewal" default: return "unknown" } } } private extension Transaction.OwnershipType { var descriptionString: String { switch self { case .purchased: return "purchased" case .familyShared: return "familyShared" default: return "purchased" } } } @available(iOS 16.0, *) private extension AppStore.Environment { var descriptionString: String { switch self { case .sandbox: return "Sandbox" case .production: return "Production" case .xcode: return "Xcode" default: return "Production" } } } private extension Product.SubscriptionInfo.RenewalState { var descriptionString: String { switch self { case .subscribed: return "subscribed" case .expired: return "expired" case .revoked: return "revoked" case .inGracePeriod: return "inGracePeriod" case .inBillingRetryPeriod: return "inBillingRetryPeriod" default: return "unknown" } } }