-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathIAPManager.swift
More file actions
executable file
·246 lines (207 loc) · 8.93 KB
/
IAPManager.swift
File metadata and controls
executable file
·246 lines (207 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//
// IAPManager.swift
// Apphud
//
// Created by Apphud on 04/01/2019.
// Copyright © 2019 Apphud. All rights reserved.
//
import UIKit
import StoreKit
public typealias SuccessBlock = () -> Void
public typealias FailureBlock = (Error?) -> Void
public typealias ProductsBlock = ([SKProduct]) -> Void
let IAP_PRODUCTS_DID_LOAD_NOTIFICATION = Notification.Name("IAP_PRODUCTS_DID_LOAD_NOTIFICATION")
class IAPManager : NSObject{
private var sharedSecret = ""
@objc static let shared = IAPManager()
@objc private(set) var products = [SKProduct]()
private override init(){}
private var productIds : Set<String> = []
private var didLoadsProducts : ProductsBlock?
private var successBlock : SuccessBlock?
private var failureBlock : FailureBlock?
private var refreshSubscriptionSuccessBlock : SuccessBlock?
private var refreshSubscriptionFailureBlock : FailureBlock?
// MARK:- Main methods
@objc func startWith(arrayOfIds : Set<String>!, sharedSecret : String, callback : @escaping ProductsBlock){
SKPaymentQueue.default().add(self)
self.didLoadsProducts = callback
self.sharedSecret = sharedSecret
self.productIds = arrayOfIds
loadProducts()
}
func expirationDateFor(_ identifier : String) -> Date?{
return UserDefaults.standard.object(forKey: identifier) as? Date
}
func isActive(product : SKProduct) -> Bool {
if let date = expirationDateFor(product.productIdentifier), Date() < date {
return true
} else {
return false
}
}
func purchaseProduct(product : SKProduct, success: @escaping SuccessBlock, failure: @escaping FailureBlock){
guard SKPaymentQueue.canMakePayments() else {
return
}
guard SKPaymentQueue.default().transactions.last?.transactionState != .purchasing else {
return
}
self.successBlock = success
self.failureBlock = failure
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
func restorePurchases(success: @escaping SuccessBlock, failure: @escaping FailureBlock){
self.successBlock = success
self.failureBlock = failure
SKPaymentQueue.default().restoreCompletedTransactions()
}
/* It's the most simple way to send verify receipt request. Consider this code as for learning purposes. You shouldn't use current code in production apps.
This code doesn't handle errors.
*/
func refreshSubscriptionsStatus(callback : @escaping SuccessBlock, failure : @escaping FailureBlock){
self.refreshSubscriptionSuccessBlock = callback
self.refreshSubscriptionFailureBlock = failure
guard let receiptUrl = Bundle.main.appStoreReceiptURL else {
refreshReceipt()
// do not call block in this case. It will be called inside after receipt refreshing finishes.
return
}
#if DEBUG
let urlString = "https://sandbox.itunes.apple.com/verifyReceipt"
#else
let urlString = "https://buy.itunes.apple.com/verifyReceipt"
#endif
let receiptData = try? Data(contentsOf: receiptUrl).base64EncodedString()
let requestData = ["receipt-data" : receiptData ?? "", "password" : self.sharedSecret, "exclude-old-transactions" : true] as [String : Any]
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
let httpBody = try? JSONSerialization.data(withJSONObject: requestData, options: [])
request.httpBody = httpBody
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if data != nil {
if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments){
self.parseReceipt(json as! Dictionary<String, Any>)
return
}
} else {
print("error validating receipt: \(error?.localizedDescription ?? "")")
}
self.refreshSubscriptionFailureBlock?(error)
self.cleanUpRefeshReceiptBlocks()
}
}.resume()
}
/* It's the most simple way to get latest expiration date. Consider this code as for learning purposes. You shouldn't use current code in production apps.
This code doesn't handle errors or some situations like cancellation date.
*/
private func parseReceipt(_ json : Dictionary<String, Any>) {
guard let receipts_array = json["latest_receipt_info"] as? [Dictionary<String, Any>] else {
self.refreshSubscriptionFailureBlock?(nil)
self.cleanUpRefeshReceiptBlocks()
return
}
for receipt in receipts_array {
let productID = receipt["product_id"] as! String
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
if let date = formatter.date(from: receipt["expires_date"] as! String) {
if date > Date() || UserDefaults.standard.object(forKey: productID) == nil{
// do not save expired date to user defaults to avoid overwriting with expired date
UserDefaults.standard.set(date, forKey: productID)
}
}
}
self.refreshSubscriptionSuccessBlock?()
self.cleanUpRefeshReceiptBlocks()
}
/*
Private method. Should not be called directly. Call refreshSubscriptionsStatus instead.
*/
private func refreshReceipt(){
let request = SKReceiptRefreshRequest(receiptProperties: nil)
request.delegate = self
request.start()
}
private func loadProducts(){
let request = SKProductsRequest.init(productIdentifiers: productIds)
request.delegate = self
request.start()
}
private func cleanUpRefeshReceiptBlocks(){
self.refreshSubscriptionSuccessBlock = nil
self.refreshSubscriptionFailureBlock = nil
}
}
// MARK:- SKReceipt Refresh Request Delegate
extension IAPManager : SKRequestDelegate {
func requestDidFinish(_ request: SKRequest) {
if request is SKReceiptRefreshRequest {
refreshSubscriptionsStatus(callback: self.successBlock ?? {}, failure: self.failureBlock ?? {_ in})
}
}
func request(_ request: SKRequest, didFailWithError error: Error){
if request is SKReceiptRefreshRequest {
self.refreshSubscriptionFailureBlock?(error)
self.cleanUpRefeshReceiptBlocks()
}
print("error: \(error.localizedDescription)")
}
}
// MARK:- SKProducts Request Delegate
extension IAPManager: SKProductsRequestDelegate {
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
products = response.products
DispatchQueue.main.async {
NotificationCenter.default.post(name: IAP_PRODUCTS_DID_LOAD_NOTIFICATION, object: nil)
if response.products.count > 0 {
self.didLoadsProducts?(self.products)
self.didLoadsProducts = nil
}
}
}
}
// MARK:- SKPayment Transaction Observer
extension IAPManager: SKPaymentTransactionObserver {
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch (transaction.transactionState) {
case .purchased:
SKPaymentQueue.default().finishTransaction(transaction)
notifyIsPurchased(transaction: transaction)
break
case .failed:
SKPaymentQueue.default().finishTransaction(transaction)
print("purchase error : \(transaction.error?.localizedDescription ?? "")")
self.failureBlock?(transaction.error)
cleanUp()
break
case .restored:
SKPaymentQueue.default().finishTransaction(transaction)
notifyIsPurchased(transaction: transaction)
break
case .deferred, .purchasing:
break
default:
break
}
}
}
private func notifyIsPurchased(transaction: SKPaymentTransaction) {
refreshSubscriptionsStatus(callback: {
self.successBlock?()
self.cleanUp()
}) { (error) in
// couldn't verify receipt
self.failureBlock?(error)
self.cleanUp()
}
}
func cleanUp(){
self.successBlock = nil
self.failureBlock = nil
}
}