ViewController.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 = "purchase1"
  29. case purchase2 = "purchase2"
  30. case nonConsumablePurchase = "nonConsumablePurchase"
  31. case consumablePurchase = "consumablePurchase"
  32. case autoRenewablePurchase = "autoRenewablePurchase"
  33. case nonRenewingPurchase = "nonRenewingPurchase"
  34. }
  35. class ViewController: NSViewController {
  36. let AppBundleId = "com.musevisions.MacOS.SwiftyStoreKitDemo"
  37. let Purchase1 = RegisteredPurchase.purchase1
  38. let Purchase2 = RegisteredPurchase.autoRenewablePurchase
  39. // MARK: actions
  40. @IBAction func getInfo1(_ sender: AnyObject?) {
  41. getInfo(Purchase1)
  42. }
  43. @IBAction func purchase1(_ sender: AnyObject?) {
  44. purchase(Purchase1)
  45. }
  46. @IBAction func verifyPurchase1(_ sender: AnyObject?) {
  47. verifyPurchase(Purchase1)
  48. }
  49. @IBAction func getInfo2(_ sender: AnyObject?) {
  50. getInfo(Purchase2)
  51. }
  52. @IBAction func purchase2(_ sender: AnyObject?) {
  53. purchase(Purchase2)
  54. }
  55. @IBAction func verifyPurchase2(_ sender: AnyObject?) {
  56. verifyPurchase(Purchase2)
  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) { result in
  65. self.showAlert(self.alertForPurchaseResult(result))
  66. }
  67. }
  68. @IBAction func restorePurchases(_ sender: AnyObject?) {
  69. SwiftyStoreKit.restorePurchases() { results in
  70. self.showAlert(self.alertForRestorePurchases(results))
  71. }
  72. }
  73. @IBAction func verifyReceipt(_ sender: AnyObject?) {
  74. SwiftyStoreKit.verifyReceipt(password: "your-shared-secret") { result in
  75. self.showAlert(self.alertForVerifyReceipt(result)) { response in
  76. self.refreshReceipt()
  77. }
  78. }
  79. }
  80. func verifyPurchase(_ purchase: RegisteredPurchase) {
  81. SwiftyStoreKit.verifyReceipt(password: "your-shared-secret") { result in
  82. switch result {
  83. case .success(let receipt):
  84. let productId = self.AppBundleId + "." + purchase.rawValue
  85. // Specific behaviour for AutoRenewablePurchase
  86. if purchase == .autoRenewablePurchase {
  87. let purchaseResult = SwiftyStoreKit.verifySubscription(
  88. productId: productId,
  89. inReceipt: receipt,
  90. validUntil: Date()
  91. )
  92. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  93. }
  94. else {
  95. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  96. productId: productId,
  97. inReceipt: receipt
  98. )
  99. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  100. }
  101. case .error(_):
  102. self.showAlert(self.alertForVerifyReceipt(result))
  103. }
  104. }
  105. }
  106. func refreshReceipt() {
  107. SwiftyStoreKit.refreshReceipt()
  108. }
  109. }
  110. // MARK: User facing alerts
  111. extension ViewController {
  112. func alertWithTitle(_ title: String, message: String) -> NSAlert {
  113. let alert: NSAlert = NSAlert()
  114. alert.messageText = title
  115. alert.informativeText = message
  116. alert.alertStyle = NSAlertStyle.informational
  117. return alert
  118. }
  119. func showAlert(_ alert: NSAlert, handler: ((NSModalResponse) -> Void)? = nil) {
  120. if let window = NSApplication.shared().keyWindow {
  121. alert.beginSheetModal(for: window) { (response: NSModalResponse) in
  122. handler?(response)
  123. }
  124. } else {
  125. let response = alert.runModal()
  126. handler?(response)
  127. }
  128. }
  129. func alertForProductRetrievalInfo(_ result: SwiftyStoreKit.RetrieveResults) -> NSAlert {
  130. if let product = result.retrievedProducts.first {
  131. let priceString = product.localizedPrice!
  132. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  133. }
  134. else if let invalidProductId = result.invalidProductIDs.first {
  135. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  136. }
  137. else {
  138. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  139. return alertWithTitle("Could not retrieve product info", message: errorString)
  140. }
  141. }
  142. func alertForPurchaseResult(_ result: SwiftyStoreKit.PurchaseResult) -> NSAlert {
  143. switch result {
  144. case .success(let productId):
  145. print("Purchase Success: \(productId)")
  146. return alertWithTitle("Thank You", message: "Purchase completed")
  147. case .error(let error):
  148. print("Purchase Failed: \(error)")
  149. switch error {
  150. case .failed(let error):
  151. if (error as NSError).domain == SKErrorDomain {
  152. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  153. }
  154. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  155. case .invalidProductId(let productId):
  156. return alertWithTitle("Purchase failed", message: "\(productId) is not a valid product identifier")
  157. case .noProductIdentifier:
  158. return alertWithTitle("Purchase failed", message: "Product not found")
  159. case .paymentNotAllowed:
  160. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  161. }
  162. }
  163. }
  164. func alertForRestorePurchases(_ results: SwiftyStoreKit.RestoreResults) -> NSAlert {
  165. if results.restoreFailedProducts.count > 0 {
  166. print("Restore Failed: \(results.restoreFailedProducts)")
  167. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  168. }
  169. else if results.restoredProductIds.count > 0 {
  170. print("Restore Success: \(results.restoredProductIds)")
  171. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  172. }
  173. else {
  174. print("Nothing to Restore")
  175. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  176. }
  177. }
  178. func alertForVerifyReceipt(_ result: SwiftyStoreKit.VerifyReceiptResult) -> NSAlert {
  179. switch result {
  180. case .success(let receipt):
  181. print("Verify receipt Success: \(receipt)")
  182. return self.alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  183. case .error(let error):
  184. print("Verify receipt Failed: \(error)")
  185. return self.alertWithTitle("Receipt verification failed", message: "The application will exit to create receipt data. You must have signed the application with your developer id to test and be outside of XCode")
  186. }
  187. }
  188. func alertForVerifySubscription(_ result: SwiftyStoreKit.VerifySubscriptionResult) -> NSAlert {
  189. switch result {
  190. case .purchased(let expiresDate):
  191. print("Product is valid until \(expiresDate)")
  192. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  193. case .expired(let expiresDate):
  194. print("Product is expired since \(expiresDate)")
  195. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  196. case .notPurchased:
  197. print("This product has never been purchased")
  198. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  199. }
  200. }
  201. func alertForVerifyPurchase(_ result: SwiftyStoreKit.VerifyPurchaseResult) -> NSAlert {
  202. switch result {
  203. case .purchased:
  204. print("Product is purchased")
  205. return alertWithTitle("Product is purchased", message: "Product will not expire")
  206. case .notPurchased:
  207. print("This product has never been purchased")
  208. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  209. }
  210. }
  211. func alertForRefreshReceipt(_ result: SwiftyStoreKit.RefreshReceiptResult) -> NSAlert {
  212. switch result {
  213. case .success(let receiptData):
  214. print("Receipt refresh Success: \(receiptData.base64EncodedString)")
  215. return alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  216. case .error(let error):
  217. print("Receipt refresh Failed: \(error)")
  218. return alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  219. }
  220. }
  221. }