ViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. //
  2. // ViewController.swift
  3. // SwiftStoreOSXDemo
  4. //
  5. // Created by phimage on 22/12/15.
  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 Cocoa
  25. import StoreKit
  26. import SwiftyStoreKit
  27. enum RegisteredPurchase: String {
  28. case purchase1
  29. case purchase2
  30. case nonConsumablePurchase
  31. case consumablePurchase
  32. case autoRenewablePurchase
  33. case nonRenewingPurchase
  34. }
  35. class ViewController: NSViewController {
  36. let appBundleId = "com.musevisions.MacOS.SwiftyStoreKitDemo"
  37. let purchase1Suffix = RegisteredPurchase.purchase1
  38. let purchase2Suffix = RegisteredPurchase.autoRenewablePurchase
  39. // MARK: actions
  40. @IBAction func getInfo1(_ sender: Any?) {
  41. getInfo(purchase1Suffix)
  42. }
  43. @IBAction func purchase1(_ sender: Any?) {
  44. purchase(purchase1Suffix)
  45. }
  46. @IBAction func verifyPurchase1(_ sender: Any?) {
  47. verifyPurchase(purchase1Suffix)
  48. }
  49. @IBAction func getInfo2(_ sender: Any?) {
  50. getInfo(purchase2Suffix)
  51. }
  52. @IBAction func purchase2(_ sender: Any?) {
  53. purchase(purchase2Suffix)
  54. }
  55. @IBAction func verifyPurchase2(_ sender: Any?) {
  56. verifyPurchase(purchase2Suffix)
  57. }
  58. func getInfo(_ purchase: RegisteredPurchase) {
  59. SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in
  60. self.showAlert(self.alertForProductRetrievalInfo(result))
  61. }
  62. }
  63. func purchase(_ purchase: RegisteredPurchase) {
  64. SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: true) { result in
  65. if case .success(let purchase) = result {
  66. // Deliver content from server, then:
  67. if purchase.needsFinishTransaction {
  68. SwiftyStoreKit.finishTransaction(purchase.transaction)
  69. }
  70. }
  71. if let errorAlert = self.alertForPurchaseResult(result) {
  72. self.showAlert(errorAlert)
  73. }
  74. }
  75. }
  76. @IBAction func restorePurchases(_ sender: Any?) {
  77. SwiftyStoreKit.restorePurchases(atomically: true) { results in
  78. for purchase in results.restoredPurchases where purchase.needsFinishTransaction {
  79. // Deliver content from server, then:
  80. SwiftyStoreKit.finishTransaction(purchase.transaction)
  81. }
  82. self.showAlert(self.alertForRestorePurchases(results))
  83. }
  84. }
  85. @IBAction func verifyReceipt(_ sender: Any?) {
  86. verifyReceipt(completion: { result in
  87. self.showAlert(self.alertForVerifyReceipt(result))
  88. })
  89. }
  90. func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) {
  91. let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
  92. SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: completion)
  93. }
  94. func verifyPurchase(_ purchase: RegisteredPurchase) {
  95. verifyReceipt { result in
  96. switch result {
  97. case .success(let receipt):
  98. let productId = self.appBundleId + "." + purchase.rawValue
  99. switch purchase {
  100. case .autoRenewablePurchase:
  101. let purchaseResult = SwiftyStoreKit.verifySubscription(
  102. ofType: .autoRenewable,
  103. productId: productId,
  104. inReceipt: receipt)
  105. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  106. case .nonRenewingPurchase:
  107. let purchaseResult = SwiftyStoreKit.verifySubscription(
  108. ofType: .nonRenewing(validDuration: 60),
  109. productId: productId,
  110. inReceipt: receipt)
  111. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  112. default:
  113. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  114. productId: productId,
  115. inReceipt: receipt)
  116. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  117. }
  118. case .error:
  119. self.showAlert(self.alertForVerifyReceipt(result))
  120. }
  121. }
  122. }
  123. }
  124. // MARK: User facing alerts
  125. extension ViewController {
  126. func alertWithTitle(_ title: String, message: String) -> NSAlert {
  127. let alert: NSAlert = NSAlert()
  128. alert.messageText = title
  129. alert.informativeText = message
  130. alert.alertStyle = .informational
  131. return alert
  132. }
  133. func showAlert(_ alert: NSAlert, handler: ((NSApplication.ModalResponse) -> Void)? = nil) {
  134. if let window = NSApplication.shared.keyWindow {
  135. alert.beginSheetModal(for: window) { (response: NSApplication.ModalResponse) in
  136. handler?(response)
  137. }
  138. } else {
  139. let response = alert.runModal()
  140. handler?(response)
  141. }
  142. }
  143. func alertForProductRetrievalInfo(_ result: RetrieveResults) -> NSAlert {
  144. if let product = result.retrievedProducts.first {
  145. let priceString = product.localizedPrice!
  146. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  147. } else if let invalidProductId = result.invalidProductIDs.first {
  148. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  149. } else {
  150. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  151. return alertWithTitle("Could not retrieve product info", message: errorString)
  152. }
  153. }
  154. func alertForPurchaseResult(_ result: PurchaseResult) -> NSAlert? {
  155. switch result {
  156. case .success(let purchase):
  157. print("Purchase Success: \(purchase.productId)")
  158. return alertWithTitle("Thank You", message: "Purchase completed")
  159. case .error(let error):
  160. print("Purchase Failed: \(error)")
  161. switch error.code {
  162. case .unknown: return alertWithTitle("Purchase failed", message: error.localizedDescription)
  163. case .clientInvalid: // client is not allowed to issue the request, etc.
  164. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
  165. case .paymentCancelled: // user cancelled the request, etc.
  166. return nil
  167. case .paymentInvalid: // purchase identifier was invalid, etc.
  168. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
  169. case .paymentNotAllowed: // this device is not allowed to make the payment
  170. return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
  171. default:
  172. return alertWithTitle("Purchase failed", message: (error as NSError).localizedDescription)
  173. }
  174. }
  175. }
  176. func alertForRestorePurchases(_ results: RestoreResults) -> NSAlert {
  177. if results.restoreFailedPurchases.count > 0 {
  178. print("Restore Failed: \(results.restoreFailedPurchases)")
  179. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  180. } else if results.restoredPurchases.count > 0 {
  181. print("Restore Success: \(results.restoredPurchases)")
  182. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  183. } else {
  184. print("Nothing to Restore")
  185. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  186. }
  187. }
  188. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> NSAlert {
  189. switch result {
  190. case .success(let receipt):
  191. print("Verify receipt Success: \(receipt)")
  192. return self.alertWithTitle("Receipt verified", message: "Receipt verified remotely")
  193. case .error(let error):
  194. print("Verify receipt Failed: \(error)")
  195. switch error {
  196. case .noReceiptData:
  197. return alertWithTitle("Receipt verification", message: "No receipt data. Try again.")
  198. case .networkError(let error):
  199. return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)")
  200. default:
  201. return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)")
  202. }
  203. }
  204. }
  205. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> NSAlert {
  206. switch result {
  207. case .purchased(let expiryDate):
  208. print("Product is valid until \(expiryDate)")
  209. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)")
  210. case .expired(let expiryDate):
  211. print("Product is expired since \(expiryDate)")
  212. return alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)")
  213. case .notPurchased:
  214. print("This product has never been purchased")
  215. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  216. }
  217. }
  218. func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> NSAlert {
  219. switch result {
  220. case .purchased:
  221. print("Product is purchased")
  222. return alertWithTitle("Product is purchased", message: "Product will not expire")
  223. case .notPurchased:
  224. print("This product has never been purchased")
  225. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  226. }
  227. }
  228. }