ViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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: Any?) {
  41. getInfo(purchase1)
  42. }
  43. @IBAction func purchase1(_ sender: Any?) {
  44. purchase(purchase1)
  45. }
  46. @IBAction func verifyPurchase1(_ sender: Any?) {
  47. verifyPurchase(purchase1)
  48. }
  49. @IBAction func getInfo2(_ sender: Any?) {
  50. getInfo(purchase2)
  51. }
  52. @IBAction func purchase2(_ sender: Any?) {
  53. purchase(purchase2)
  54. }
  55. @IBAction func verifyPurchase2(_ sender: Any?) {
  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, atomically: true) { result in
  65. if case .success(let product) = result {
  66. // Deliver content from server, then:
  67. if product.needsFinishTransaction {
  68. SwiftyStoreKit.finishTransaction(product.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 product in results.restoredProducts {
  79. // Deliver content from server, then:
  80. if product.needsFinishTransaction {
  81. SwiftyStoreKit.finishTransaction(product.transaction)
  82. }
  83. }
  84. self.showAlert(self.alertForRestorePurchases(results))
  85. }
  86. }
  87. @IBAction func verifyReceipt(_ sender: Any?) {
  88. let appleValidator = AppleReceiptValidator(service: .production)
  89. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  90. self.showAlert(self.alertForVerifyReceipt(result)) { response in
  91. if case .error(let error) = result {
  92. if case .noReceiptData = error {
  93. self.refreshReceipt()
  94. }
  95. }
  96. }
  97. }
  98. }
  99. func verifyPurchase(_ purchase: RegisteredPurchase) {
  100. let appleValidator = AppleReceiptValidator(service: .production)
  101. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  102. switch result {
  103. case .success(let receipt):
  104. let productId = self.AppBundleId + "." + purchase.rawValue
  105. // Specific behaviour for AutoRenewablePurchase
  106. if purchase == .autoRenewablePurchase {
  107. let purchaseResult = SwiftyStoreKit.verifySubscription(
  108. productId: productId,
  109. inReceipt: receipt,
  110. validUntil: Date()
  111. )
  112. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  113. } else {
  114. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  115. productId: productId,
  116. inReceipt: receipt
  117. )
  118. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  119. }
  120. case .error(_):
  121. self.showAlert(self.alertForVerifyReceipt(result))
  122. }
  123. }
  124. }
  125. func refreshReceipt() {
  126. SwiftyStoreKit.refreshReceipt() { result in
  127. self.showAlert(self.alertForRefreshReceipt(result))
  128. }
  129. }
  130. }
  131. // MARK: User facing alerts
  132. extension ViewController {
  133. func alertWithTitle(_ title: String, message: String) -> NSAlert {
  134. let alert: NSAlert = NSAlert()
  135. alert.messageText = title
  136. alert.informativeText = message
  137. alert.alertStyle = NSAlertStyle.informational
  138. return alert
  139. }
  140. func showAlert(_ alert: NSAlert, handler: ((NSModalResponse) -> Void)? = nil) {
  141. if let window = NSApplication.shared().keyWindow {
  142. alert.beginSheetModal(for: window) { (response: NSModalResponse) in
  143. handler?(response)
  144. }
  145. } else {
  146. let response = alert.runModal()
  147. handler?(response)
  148. }
  149. }
  150. func alertForProductRetrievalInfo(_ result: RetrieveResults) -> NSAlert {
  151. if let product = result.retrievedProducts.first {
  152. let priceString = product.localizedPrice!
  153. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  154. } else if let invalidProductId = result.invalidProductIDs.first {
  155. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  156. } else {
  157. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  158. return alertWithTitle("Could not retrieve product info", message: errorString)
  159. }
  160. }
  161. func alertForPurchaseResult(_ result: PurchaseResult) -> NSAlert? {
  162. switch result {
  163. case .success(let product):
  164. print("Purchase Success: \(product.productId)")
  165. return alertWithTitle("Thank You", message: "Purchase completed")
  166. case .error(let error):
  167. print("Purchase Failed: \(error)")
  168. switch error.code {
  169. case .unknown: return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  170. case .clientInvalid: // client is not allowed to issue the request, etc.
  171. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
  172. case .paymentCancelled: // user cancelled the request, etc.
  173. return nil
  174. case .paymentInvalid: // purchase identifier was invalid, etc.
  175. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
  176. case .paymentNotAllowed: // this device is not allowed to make the payment
  177. return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
  178. }
  179. }
  180. }
  181. func alertForRestorePurchases(_ results: RestoreResults) -> NSAlert {
  182. if results.restoreFailedProducts.count > 0 {
  183. print("Restore Failed: \(results.restoreFailedProducts)")
  184. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  185. } else if results.restoredProducts.count > 0 {
  186. print("Restore Success: \(results.restoredProducts)")
  187. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  188. } else {
  189. print("Nothing to Restore")
  190. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  191. }
  192. }
  193. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> NSAlert {
  194. switch result {
  195. case .success(let receipt):
  196. print("Verify receipt Success: \(receipt)")
  197. return self.alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  198. case .error(let error):
  199. print("Verify receipt Failed: \(error)")
  200. 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")
  201. }
  202. }
  203. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> NSAlert {
  204. switch result {
  205. case .purchased(let expiresDate):
  206. print("Product is valid until \(expiresDate)")
  207. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  208. case .expired(let expiresDate):
  209. print("Product is expired since \(expiresDate)")
  210. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  211. case .notPurchased:
  212. print("This product has never been purchased")
  213. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  214. }
  215. }
  216. func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> NSAlert {
  217. switch result {
  218. case .purchased:
  219. print("Product is purchased")
  220. return alertWithTitle("Product is purchased", message: "Product will not expire")
  221. case .notPurchased:
  222. print("This product has never been purchased")
  223. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  224. }
  225. }
  226. func alertForRefreshReceipt(_ result: RefreshReceiptResult) -> NSAlert {
  227. switch result {
  228. case .success(let receiptData):
  229. print("Receipt refresh Success: \(receiptData.base64EncodedString)")
  230. return alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  231. case .error(let error):
  232. print("Receipt refresh Failed: \(error)")
  233. return alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  234. }
  235. }
  236. }