SwiftyStoreKit.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // SwiftyStoreKit.swift
  3. // SwiftyStoreKit
  4. //
  5. // Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import StoreKit
  25. public class SwiftyStoreKit {
  26. private let productsInfoController: ProductsInfoController
  27. fileprivate let paymentQueueController: PaymentQueueController
  28. fileprivate let receiptVerificator: InAppReceiptVerificator
  29. init(productsInfoController: ProductsInfoController = ProductsInfoController(),
  30. paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default()),
  31. receiptVerificator: InAppReceiptVerificator = InAppReceiptVerificator()) {
  32. self.productsInfoController = productsInfoController
  33. self.paymentQueueController = paymentQueueController
  34. self.receiptVerificator = receiptVerificator
  35. }
  36. // MARK: private methods
  37. fileprivate func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
  38. return productsInfoController.retrieveProductsInfo(productIds, completion: completion)
  39. }
  40. fileprivate func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) -> InAppProductRequest {
  41. return retrieveProductsInfo(Set([productId])) { result -> Void in
  42. if let product = result.retrievedProducts.first {
  43. self.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
  44. } else if let error = result.error {
  45. completion(.error(error: SKError(_nsError: error as NSError)))
  46. } else if let invalidProductId = result.invalidProductIDs.first {
  47. let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ]
  48. let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo)
  49. completion(.error(error: SKError(_nsError: error)))
  50. } else {
  51. let error = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: nil)
  52. completion(.error(error: SKError(_nsError: error)))
  53. }
  54. }
  55. }
  56. fileprivate func purchase(product: SKProduct, quantity: Int, atomically: Bool, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping (PurchaseResult) -> Void) {
  57. paymentQueueController.startPayment(Payment(product: product, paymentDiscount: paymentDiscount, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox) { result in
  58. completion(self.processPurchaseResult(result))
  59. })
  60. }
  61. fileprivate func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
  62. paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in
  63. let results = self.processRestoreResults(results)
  64. completion(results)
  65. })
  66. }
  67. fileprivate func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
  68. paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion))
  69. }
  70. fileprivate func finishTransaction(_ transaction: PaymentTransaction) {
  71. paymentQueueController.finishTransaction(transaction)
  72. }
  73. private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult {
  74. switch result {
  75. case .purchased(let purchase):
  76. return .success(purchase: purchase)
  77. case .failed(let error):
  78. return .error(error: error)
  79. case .restored(let purchase):
  80. return .error(error: storeInternalError(description: "Cannot restore product \(purchase.productId) from purchase path"))
  81. }
  82. }
  83. private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults {
  84. var restoredPurchases: [Purchase] = []
  85. var restoreFailedPurchases: [(SKError, String?)] = []
  86. for result in results {
  87. switch result {
  88. case .purchased(let purchase):
  89. let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
  90. restoreFailedPurchases.append((error, purchase.productId))
  91. case .failed(let error):
  92. restoreFailedPurchases.append((error, nil))
  93. case .restored(let purchase):
  94. restoredPurchases.append(purchase)
  95. }
  96. }
  97. return RestoreResults(restoredPurchases: restoredPurchases, restoreFailedPurchases: restoreFailedPurchases)
  98. }
  99. private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError {
  100. let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ])
  101. return SKError(_nsError: error)
  102. }
  103. }
  104. extension SwiftyStoreKit {
  105. // MARK: Singleton
  106. fileprivate static let sharedInstance = SwiftyStoreKit()
  107. // MARK: Public methods - Purchases
  108. /// Check if the current device can make payments.
  109. /// - returns: `false` if this device is not able or allowed to make payments
  110. public class var canMakePayments: Bool {
  111. return SKPaymentQueue.canMakePayments()
  112. }
  113. /// Retrieve products information
  114. /// - Parameter productIds: The set of product identifiers to retrieve corresponding products for
  115. /// - Parameter completion: handler for result
  116. /// - returns: A cancellable `InAppRequest` object
  117. @discardableResult
  118. public class func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppRequest {
  119. return sharedInstance.retrieveProductsInfo(productIds, completion: completion)
  120. }
  121. /// Purchase a product
  122. /// - Parameter productId: productId as specified in App Store Connect
  123. /// - Parameter quantity: quantity of the product to be purchased
  124. /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
  125. /// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
  126. /// - Parameter completion: handler for result
  127. /// - returns: A cancellable `InAppRequest` object
  128. @discardableResult
  129. public class func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) -> InAppRequest {
  130. return sharedInstance.purchaseProduct(productId, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
  131. }
  132. /// Purchase a product
  133. /// - Parameter product: product to be purchased
  134. /// - Parameter quantity: quantity of the product to be purchased
  135. /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
  136. /// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
  137. /// - Parameter product: optional discount to be applied. Must be of `SKProductPayment` type
  138. /// - Parameter completion: handler for result
  139. public class func purchaseProduct(_ product: SKProduct, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping ( PurchaseResult) -> Void) {
  140. sharedInstance.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, paymentDiscount: paymentDiscount, completion: completion)
  141. }
  142. /// Restore purchases
  143. /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
  144. /// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
  145. /// - Parameter completion: handler for result
  146. public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
  147. sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion)
  148. }
  149. /// Complete transactions
  150. /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
  151. /// - Parameter completion: handler for result
  152. public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
  153. sharedInstance.completeTransactions(atomically: atomically, completion: completion)
  154. }
  155. /// Finish a transaction
  156. ///
  157. /// Once the content has been delivered, call this method to finish a transaction that was performed non-atomically
  158. /// - Parameter transaction: transaction to finish
  159. public class func finishTransaction(_ transaction: PaymentTransaction) {
  160. sharedInstance.finishTransaction(transaction)
  161. }
  162. /// Register a handler for `SKPaymentQueue.shouldAddStorePayment` delegate method.
  163. /// - requires: iOS 11.0+
  164. public static var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler? {
  165. didSet {
  166. sharedInstance.paymentQueueController.shouldAddStorePaymentHandler = shouldAddStorePaymentHandler
  167. }
  168. }
  169. /// Register a handler for `paymentQueue(_:updatedDownloads:)`
  170. /// - seealso: `paymentQueue(_:updatedDownloads:)`
  171. public static var updatedDownloadsHandler: UpdatedDownloadsHandler? {
  172. didSet {
  173. sharedInstance.paymentQueueController.updatedDownloadsHandler = updatedDownloadsHandler
  174. }
  175. }
  176. public class func start(_ downloads: [SKDownload]) {
  177. sharedInstance.paymentQueueController.start(downloads)
  178. }
  179. public class func pause(_ downloads: [SKDownload]) {
  180. sharedInstance.paymentQueueController.pause(downloads)
  181. }
  182. public class func resume(_ downloads: [SKDownload]) {
  183. sharedInstance.paymentQueueController.resume(downloads)
  184. }
  185. public class func cancel(_ downloads: [SKDownload]) {
  186. sharedInstance.paymentQueueController.cancel(downloads)
  187. }
  188. }
  189. extension SwiftyStoreKit {
  190. // MARK: Public methods - Receipt verification
  191. /// Return receipt data from the application bundle. This is read from `Bundle.main.appStoreReceiptURL`.
  192. public static var localReceiptData: Data? {
  193. return sharedInstance.receiptVerificator.appStoreReceiptData
  194. }
  195. /// Verify application receipt
  196. /// - Parameter validator: receipt validator to use
  197. /// - Parameter forceRefresh: If `true`, refreshes the receipt even if one already exists.
  198. /// - Parameter completion: handler for result
  199. /// - returns: A cancellable `InAppRequest` object
  200. @discardableResult
  201. public class func verifyReceipt(using validator: ReceiptValidator, forceRefresh: Bool = false, completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? {
  202. return sharedInstance.receiptVerificator.verifyReceipt(using: validator, forceRefresh: forceRefresh, completion: completion)
  203. }
  204. /// Fetch application receipt
  205. /// - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
  206. /// - Parameter completion: handler for result
  207. /// - returns: A cancellable `InAppRequest` object
  208. @discardableResult
  209. public class func fetchReceipt(forceRefresh: Bool, completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? {
  210. return sharedInstance.receiptVerificator.fetchReceipt(forceRefresh: forceRefresh, completion: completion)
  211. }
  212. /// Verify the purchase of a Consumable or NonConsumable product in a receipt
  213. /// - Parameter productId: the product id of the purchase to verify
  214. /// - Parameter inReceipt: the receipt to use for looking up the purchase
  215. /// - returns: A `VerifyPurchaseResult`, which may be either `notPurchased` or `purchased`.
  216. public class func verifyPurchase(productId: String, inReceipt receipt: ReceiptInfo) -> VerifyPurchaseResult {
  217. return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt)
  218. }
  219. /**
  220. * Verify the validity of a subscription (auto-renewable, free or non-renewing) in a receipt.
  221. *
  222. * This method extracts all transactions matching the given productId and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date to determine its validity.
  223. * - Parameter type: `.autoRenewable` or `.nonRenewing`.
  224. * - Parameter productId: The product id of the subscription to verify.
  225. * - Parameter receipt: The receipt to use for looking up the subscription.
  226. * - Parameter validUntil: Date to check against the expiry date of the subscription. This is only used if a date is not found in the receipt.
  227. * - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
  228. */
  229. public class func verifySubscription(ofType type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
  230. return InAppReceipt.verifySubscriptions(ofType: type, productIds: [productId], inReceipt: receipt, validUntil: date)
  231. }
  232. /**
  233. * Verify the validity of a set of subscriptions in a receipt.
  234. *
  235. * This method extracts all transactions matching the given productIds and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date, to determine its validity.
  236. * - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group.
  237. * - Remark: The type parameter determines how the expiration dates are calculated for all subscriptions. Make sure all productIds match the specified subscription type to avoid incorrect results.
  238. * - Parameter type: `.autoRenewable` or `.nonRenewing`.
  239. * - Parameter productIds: The product IDs of the subscriptions to verify.
  240. * - Parameter receipt: The receipt to use for looking up the subscriptions
  241. * - Parameter validUntil: Date to check against the expiry date of the subscriptions. This is only used if a date is not found in the receipt.
  242. * - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
  243. */
  244. public class func verifySubscriptions(ofType type: SubscriptionType = .autoRenewable, productIds: Set<String>, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
  245. return InAppReceipt.verifySubscriptions(ofType: type, productIds: productIds, inReceipt: receipt, validUntil: date)
  246. }
  247. /// Get the distinct product identifiers from receipt.
  248. ///
  249. /// This Method extracts all product identifiers. (Including cancelled ones).
  250. /// - Note: You can use this method to get all unique product identifiers from receipt.
  251. /// - Parameter type: `.autoRenewable` or `.nonRenewing`.
  252. /// - Parameter receipt: The receipt to use for looking up product identifiers.
  253. /// - returns: Either `Set<String>` or `nil`.
  254. public class func getDistinctPurchaseIds(ofType type: SubscriptionType = .autoRenewable, inReceipt receipt: ReceiptInfo) -> Set<String>? {
  255. return InAppReceipt.getDistinctPurchaseIds(ofType: type, inReceipt: receipt)
  256. }
  257. }