forked from nickthedude/SwiftyStoreKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InAppReceipt.swift
244 lines (213 loc) · 10.8 KB
/
InAppReceipt.swift
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
//
// InAppReceipt.swift
// SwiftyStoreKit
//
// Created by phimage on 22/12/15.
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Date {
init?(millisecondsSince1970: String) {
guard let millisecondsNumber = Double(millisecondsSince1970) else {
return nil
}
self = Date(timeIntervalSince1970: millisecondsNumber / 1000)
}
}
extension ReceiptItem {
public init?(receiptInfo: ReceiptInfo) {
guard
let productId = receiptInfo["product_id"] as? String,
let quantityString = receiptInfo["quantity"] as? String,
let quantity = Int(quantityString),
let transactionId = receiptInfo["transaction_id"] as? String,
let originalTransactionId = receiptInfo["original_transaction_id"] as? String,
let purchaseDate = ReceiptItem.parseDate(from: receiptInfo, key: "purchase_date_ms"),
let originalPurchaseDate = ReceiptItem.parseDate(from: receiptInfo, key: "original_purchase_date_ms")
else {
print("could not parse receipt item: \(receiptInfo). Skipping...")
return nil
}
self.productId = productId
self.quantity = quantity
self.transactionId = transactionId
self.originalTransactionId = originalTransactionId
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.webOrderLineItemId = receiptInfo["web_order_line_item_id"] as? String
self.subscriptionExpirationDate = ReceiptItem.parseDate(from: receiptInfo, key: "expires_date_ms")
self.cancellationDate = ReceiptItem.parseDate(from: receiptInfo, key: "cancellation_date_ms")
if let isTrialPeriod = receiptInfo["is_trial_period"] as? String {
self.isTrialPeriod = Bool(isTrialPeriod) ?? false
} else {
self.isTrialPeriod = false
}
if let isInIntroOfferPeriod = receiptInfo["is_in_intro_offer_period"] as? String {
self.isInIntroOfferPeriod = Bool(isInIntroOfferPeriod) ?? false
} else {
self.isInIntroOfferPeriod = false
}
}
private static func parseDate(from receiptInfo: ReceiptInfo, key: String) -> Date? {
guard
let requestDateString = receiptInfo[key] as? String,
let requestDateMs = Double(requestDateString) else {
return nil
}
return Date(timeIntervalSince1970: requestDateMs / 1000)
}
}
// MARK: - receipt mangement
internal class InAppReceipt {
/**
* Verify the purchase of a Consumable or NonConsumable product in a receipt
* - Parameter productId: the product id of the purchase to verify
* - Parameter inReceipt: the receipt to use for looking up the purchase
* - return: either notPurchased or purchased
*/
class func verifyPurchase(
productId: String,
inReceipt receipt: ReceiptInfo
) -> VerifyPurchaseResult {
// Get receipts info for the product
let receipts = getInAppReceipts(receipt: receipt)
let filteredReceiptsInfo = filterReceiptsInfo(receipts: receipts, withProductIds: [productId])
let nonCancelledReceiptsInfo = filteredReceiptsInfo.filter { receipt in receipt["cancellation_date"] == nil }
#if swift(>=4.1)
let receiptItems = nonCancelledReceiptsInfo.compactMap { ReceiptItem(receiptInfo: $0) }
#else
let receiptItems = nonCancelledReceiptsInfo.flatMap { ReceiptItem(receiptInfo: $0) }
#endif
// Verify that at least one receipt has the right product id
if let firstItem = receiptItems.first {
return .purchased(item: firstItem)
}
return .notPurchased
}
/**
* Verify the validity of a set of subscriptions in a receipt.
*
* 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.
* - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group.
* - 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.
* - Parameter type: .autoRenewable or .nonRenewing.
* - Parameter productIds: The product ids of the subscriptions to verify.
* - Parameter receipt: The receipt to use for looking up the subscriptions
* - 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.
* - return: Either .notPurchased or .purchased / .expired with the expiry date found in the receipt.
*/
class func verifySubscriptions(
ofType type: SubscriptionType,
productIds: Set<String>,
inReceipt receipt: ReceiptInfo,
validUntil date: Date = Date()
) -> VerifySubscriptionResult {
// The values of the latest_receipt and latest_receipt_info keys are useful when checking whether an auto-renewable subscription is currently active. By providing any transaction receipt for the subscription and checking these values, you can get information about the currently-active subscription period. If the receipt being validated is for the latest renewal, the value for latest_receipt is the same as receipt-data (in the request) and the value for latest_receipt_info is the same as receipt.
let (receipts, duration) = getReceiptsAndDuration(for: type, inReceipt: receipt)
let receiptsInfo = filterReceiptsInfo(receipts: receipts, withProductIds: productIds)
let nonCancelledReceiptsInfo = receiptsInfo.filter { receipt in receipt["cancellation_date"] == nil }
if nonCancelledReceiptsInfo.count == 0 {
return .notPurchased
}
let receiptDate = getReceiptRequestDate(inReceipt: receipt) ?? date
#if swift(>=4.1)
let receiptItems = nonCancelledReceiptsInfo.compactMap { ReceiptItem(receiptInfo: $0) }
#else
let receiptItems = nonCancelledReceiptsInfo.flatMap { ReceiptItem(receiptInfo: $0) }
#endif
if nonCancelledReceiptsInfo.count > receiptItems.count {
print("receipt has \(nonCancelledReceiptsInfo.count) items, but only \(receiptItems.count) were parsed")
}
let sortedExpiryDatesAndItems = expiryDatesAndItems(receiptItems: receiptItems, duration: duration).sorted { a, b in
return a.0 > b.0
}
guard let firstExpiryDateItemPair = sortedExpiryDatesAndItems.first else {
return .notPurchased
}
let sortedReceiptItems = sortedExpiryDatesAndItems.map { $0.1 }
if firstExpiryDateItemPair.0 > receiptDate {
return .purchased(expiryDate: firstExpiryDateItemPair.0, items: sortedReceiptItems)
} else {
return .expired(expiryDate: firstExpiryDateItemPair.0, items: sortedReceiptItems)
}
}
private class func expiryDatesAndItems(receiptItems: [ReceiptItem], duration: TimeInterval?) -> [(Date, ReceiptItem)] {
if let duration = duration {
return receiptItems.map {
let expirationDate = Date(timeIntervalSince1970: $0.originalPurchaseDate.timeIntervalSince1970 + duration)
return (expirationDate, $0)
}
} else {
#if swift(>=4.1)
return receiptItems.compactMap {
if let expirationDate = $0.subscriptionExpirationDate {
return (expirationDate, $0)
}
return nil
}
#else
return receiptItems.flatMap {
if let expirationDate = $0.subscriptionExpirationDate {
return (expirationDate, $0)
}
return nil
}
#endif
}
}
private class func getReceiptsAndDuration(for subscriptionType: SubscriptionType, inReceipt receipt: ReceiptInfo) -> ([ReceiptInfo]?, TimeInterval?) {
switch subscriptionType {
case .autoRenewable:
return (receipt["latest_receipt_info"] as? [ReceiptInfo], nil)
case .nonRenewing(let duration):
return (getInAppReceipts(receipt: receipt), duration)
}
}
private class func getReceiptRequestDate(inReceipt receipt: ReceiptInfo) -> Date? {
guard let receiptInfo = receipt["receipt"] as? ReceiptInfo,
let requestDateString = receiptInfo["request_date_ms"] as? String else {
return nil
}
return Date(millisecondsSince1970: requestDateString)
}
private class func getInAppReceipts(receipt: ReceiptInfo) -> [ReceiptInfo]? {
let appReceipt = receipt["receipt"] as? ReceiptInfo
return appReceipt?["in_app"] as? [ReceiptInfo]
}
/**
* Get all the receipts info for a specific product
* - Parameter receipts: the receipts array to grab info from
* - Parameter productId: the product id
*/
private class func filterReceiptsInfo(receipts: [ReceiptInfo]?, withProductIds productIds: Set<String>) -> [ReceiptInfo] {
guard let receipts = receipts else {
return []
}
// Filter receipts with matching product ids
let receiptsMatchingProductIds = receipts
.filter { (receipt) -> Bool in
if let productId = receipt["product_id"] as? String {
return productIds.contains(productId)
}
return false
}
return receiptsMatchingProductIds
}
}