Commit cb99e28a authored by Mazy's avatar Mazy

mrege

parent 2bdc4370
File added
PODS:
- AFNetworking (4.0.1):
- AFNetworking/NSURLSession (= 4.0.1)
- AFNetworking/Reachability (= 4.0.1)
- AFNetworking/Security (= 4.0.1)
- AFNetworking/Serialization (= 4.0.1)
- AFNetworking/UIKit (= 4.0.1)
- AFNetworking/NSURLSession (4.0.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/Reachability (4.0.1)
- AFNetworking/Security (4.0.1)
- AFNetworking/Serialization (4.0.1)
- AFNetworking/UIKit (4.0.1):
- AFNetworking/NSURLSession
- Masonry (1.1.0)
- MBProgressHUD (1.2.0)
- SwiftyStoreKit (0.16.1)
- UMCCommon (7.1.1)
DEPENDENCIES:
- AFNetworking
- Masonry
- MBProgressHUD
- SwiftyStoreKit
- UMCCommon
SPEC REPOS:
trunk:
- AFNetworking
- Masonry
- MBProgressHUD
- SwiftyStoreKit
- UMCCommon
SPEC CHECKSUMS:
AFNetworking: 7864c38297c79aaca1500c33288e429c3451fdce
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
MBProgressHUD: 3ee5efcc380f6a79a7cc9b363dd669c5e1ae7406
SwiftyStoreKit: 6b9c08810269f030586dac1fae8e75871a82e84a
UMCCommon: f455f92c125342e360d6ad9eafe484945351eeb5
PODFILE CHECKSUM: 4f2749c25022ff63f90562fa6a7ba216444b845e
COCOAPODS: 1.9.3
PODS:
- AFNetworking (4.0.1):
- AFNetworking/NSURLSession (= 4.0.1)
- AFNetworking/Reachability (= 4.0.1)
- AFNetworking/Security (= 4.0.1)
- AFNetworking/Serialization (= 4.0.1)
- AFNetworking/UIKit (= 4.0.1)
- AFNetworking/NSURLSession (4.0.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/Reachability (4.0.1)
- AFNetworking/Security (4.0.1)
- AFNetworking/Serialization (4.0.1)
- AFNetworking/UIKit (4.0.1):
- AFNetworking/NSURLSession
- Masonry (1.1.0)
- MBProgressHUD (1.2.0)
- SwiftyStoreKit (0.16.1)
- UMCCommon (7.1.1)
DEPENDENCIES:
- AFNetworking
- Masonry
- MBProgressHUD
- SwiftyStoreKit
- UMCCommon
SPEC REPOS:
trunk:
- AFNetworking
- Masonry
- MBProgressHUD
- SwiftyStoreKit
- UMCCommon
SPEC CHECKSUMS:
AFNetworking: 7864c38297c79aaca1500c33288e429c3451fdce
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
MBProgressHUD: 3ee5efcc380f6a79a7cc9b363dd669c5e1ae7406
SwiftyStoreKit: 6b9c08810269f030586dac1fae8e75871a82e84a
UMCCommon: f455f92c125342e360d6ad9eafe484945351eeb5
PODFILE CHECKSUM: 4f2749c25022ff63f90562fa6a7ba216444b845e
COCOAPODS: 1.9.3
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "0130B3724283586C0E9D2A112D4F2AA1"
BuildableName = "AFNetworking.framework"
BlueprintName = "AFNetworking"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "82B0A41D3031FF27D78E17B0A9A46FB0"
BuildableName = "MBProgressHUD.framework"
BlueprintName = "MBProgressHUD"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "55AF53E6C77A10ED4985E04D74A8878E"
BuildableName = "Masonry.framework"
BlueprintName = "Masonry"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "596A560B22E98CCD9E2F4E063F10C485"
BuildableName = "Pods_superCleaner.framework"
BlueprintName = "Pods-superCleaner"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "FCD4F1901DD86FEB184BFDD6673F4A7B"
BuildableName = "SwiftyStoreKit.framework"
BlueprintName = "SwiftyStoreKit"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6F6B630FA5213AB083E7CEF1F986FE44"
BuildableName = "UMCCommon"
BlueprintName = "UMCCommon"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>AFNetworking.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
<key>MBProgressHUD.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
<key>Masonry.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
<key>Pods-superCleaner.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
<key>SwiftyStoreKit.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
<key>UMCCommon.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict/>
</dict>
</plist>
//
// InAppReceipt.swift
// SwiftyStoreKit
//
// Created by phimage on 22/12/15.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
// https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html
public class AppleReceiptValidator: ReceiptValidator {
public enum VerifyReceiptURLType: String {
case production = "https://buy.itunes.apple.com/verifyReceipt"
case sandbox = "https://sandbox.itunes.apple.com/verifyReceipt"
}
/// You should always verify your receipt first with the `production` service
/// Note: will auto change to `.sandbox` and validate again if received a 21007 status code from Apple
public var service: VerifyReceiptURLType
private let sharedSecret: String?
/**
* Reference Apple Receipt Validator
* - Parameter service: Either .production or .sandbox
* - Parameter sharedSecret: Only used for receipts that contain auto-renewable subscriptions. Your app’s shared secret (a hexadecimal string).
*/
public init(service: VerifyReceiptURLType = .production, sharedSecret: String? = nil) {
self.service = service
self.sharedSecret = sharedSecret
}
public func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void) {
let storeURL = URL(string: service.rawValue)! // safe (until no more)
let storeRequest = NSMutableURLRequest(url: storeURL)
storeRequest.httpMethod = "POST"
let receipt = receiptData.base64EncodedString(options: [])
let requestContents: NSMutableDictionary = [ "receipt-data": receipt ]
// password if defined
if let password = sharedSecret {
requestContents.setValue(password, forKey: "password")
}
// Encore request body
do {
storeRequest.httpBody = try JSONSerialization.data(withJSONObject: requestContents, options: [])
} catch let e {
completion(.error(error: .requestBodyEncodeError(error: e)))
return
}
// Remote task
let task = URLSession.shared.dataTask(with: storeRequest as URLRequest) { data, _, error -> Void in
// there is an error
if let networkError = error {
completion(.error(error: .networkError(error: networkError)))
return
}
// there is no data
guard let safeData = data else {
completion(.error(error: .noRemoteData))
return
}
// cannot decode data
guard let receiptInfo = try? JSONSerialization.jsonObject(with: safeData, options: .mutableLeaves) as? ReceiptInfo ?? [:] else {
let jsonStr = String(data: safeData, encoding: String.Encoding.utf8)
completion(.error(error: .jsonDecodeError(string: jsonStr)))
return
}
// get status from info
if let status = receiptInfo["status"] as? Int {
/*
* http://stackoverflow.com/questions/16187231/how-do-i-know-if-an-in-app-purchase-receipt-comes-from-the-sandbox
* How do I verify my receipt (iOS)?
* Always verify your receipt first with the production URL; proceed to verify
* with the sandbox URL if you receive a 21007 status code. Following this
* approach ensures that you do not have to switch between URLs while your
* application is being tested or reviewed in the sandbox or is live in the
* App Store.
* Note: The 21007 status code indicates that this receipt is a sandbox receipt,
* but it was sent to the production service for verification.
*/
let receiptStatus = ReceiptStatus(rawValue: status) ?? ReceiptStatus.unknown
if case .testReceipt = receiptStatus {
self.service = .sandbox
self.validate(receiptData: receiptData, completion: completion)
} else {
if receiptStatus.isValid {
completion(.success(receipt: receiptInfo))
} else {
completion(.error(error: .receiptInvalid(receipt: receiptInfo, status: receiptStatus)))
}
}
} else {
completion(.error(error: .receiptInvalid(receipt: receiptInfo, status: ReceiptStatus.none)))
}
}
task.resume()
}
}
//
// CompleteTransactionsController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
import StoreKit
struct CompleteTransactions {
let atomically: Bool
let callback: ([Purchase]) -> Void
init(atomically: Bool, callback: @escaping ([Purchase]) -> Void) {
self.atomically = atomically
self.callback = callback
}
}
class CompleteTransactionsController: TransactionController {
var completeTransactions: CompleteTransactions?
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] {
guard let completeTransactions = completeTransactions else {
print("SwiftyStoreKit.completeTransactions() should be called once when the app launches.")
return transactions
}
var unhandledTransactions: [SKPaymentTransaction] = []
var purchases: [Purchase] = []
for transaction in transactions {
let transactionState = transaction.transactionState
if transactionState != .purchasing {
let willFinishTransaction = completeTransactions.atomically || transactionState == .failed
let purchase = Purchase(productId: transaction.payment.productIdentifier, quantity: transaction.payment.quantity, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !willFinishTransaction)
purchases.append(purchase)
if willFinishTransaction {
print("Finishing transaction for payment \"\(transaction.payment.productIdentifier)\" with state: \(transactionState.debugDescription)")
paymentQueue.finishTransaction(transaction)
}
} else {
unhandledTransactions.append(transaction)
}
}
if purchases.count > 0 {
completeTransactions.callback(purchases)
}
return unhandledTransactions
}
}
//
// InAppPurchaseProductRequest.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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 StoreKit
typealias InAppProductRequestCallback = (RetrieveResults) -> Void
public protocol InAppRequest: class {
func start()
func cancel()
}
protocol InAppProductRequest: InAppRequest { }
class InAppProductQueryRequest: NSObject, InAppProductRequest, SKProductsRequestDelegate {
private let callback: InAppProductRequestCallback
private let request: SKProductsRequest
deinit {
request.delegate = nil
}
init(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) {
self.callback = callback
request = SKProductsRequest(productIdentifiers: productIds)
super.init()
request.delegate = self
}
func start() {
request.start()
}
func cancel() {
request.cancel()
}
// MARK: SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let retrievedProducts = Set<SKProduct>(response.products)
let invalidProductIDs = Set<String>(response.invalidProductIdentifiers)
performCallback(RetrieveResults(retrievedProducts: retrievedProducts,
invalidProductIDs: invalidProductIDs, error: nil))
}
func requestDidFinish(_ request: SKRequest) {
}
func request(_ request: SKRequest, didFailWithError error: Error) {
performCallback(RetrieveResults(retrievedProducts: Set<SKProduct>(), invalidProductIDs: Set<String>(), error: error))
}
private func performCallback(_ results: RetrieveResults) {
DispatchQueue.main.async {
self.callback(results)
}
}
}
//
// InAppReceipt.swift
// SwiftyStoreKit
//
// Created by phimage on 22/12/15.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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)
}
}
/**
* Get the distinct product identifiers from receipt.
*
* This Method extracts all product identifiers. (Including cancelled ones).
* - Note: You can use this method to get all unique product identifiers from receipt.
* - Parameter type: .autoRenewable or .nonRenewing.
* - Parameter receipt: The receipt to use for looking up the product identifiers.
* - return: Either Set<String> or nil.
*/
class func getDistinctPurchaseIds(
ofType type: SubscriptionType,
inReceipt receipt: ReceiptInfo
) -> Set<String>? {
// Get receipts array from receipt
guard let receipts = getReceipts(for: type, inReceipt: receipt) else {
return nil
}
#if swift(>=4.1)
let receiptIds = receipts.compactMap { ReceiptItem(receiptInfo: $0)?.productId }
#else
let receiptIds = receipts.flatMap { ReceiptItem(receiptInfo: $0)?.productId }
#endif
if receiptIds.isEmpty {
return nil
}
return Set(receiptIds)
}
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 getReceipts(for subscriptionType: SubscriptionType, inReceipt receipt: ReceiptInfo) -> [ReceiptInfo]? {
switch subscriptionType {
case .autoRenewable:
return receipt["latest_receipt_info"] as? [ReceiptInfo]
case .nonRenewing:
return getInAppReceipts(receipt: receipt)
}
}
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
}
}
//
// InAppReceiptRefreshRequest.swift
// SwiftyStoreKit
//
// Created by phimage on 23/12/15.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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 StoreKit
import Foundation
class InAppReceiptRefreshRequest: NSObject, SKRequestDelegate, InAppRequest {
enum ResultType {
case success
case error(e: Error)
}
typealias RequestCallback = (ResultType) -> Void
typealias ReceiptRefresh = (_ receiptProperties: [String: Any]?, _ callback: @escaping RequestCallback) -> InAppReceiptRefreshRequest
class func refresh(_ receiptProperties: [String: Any]? = nil, callback: @escaping RequestCallback) -> InAppReceiptRefreshRequest {
let request = InAppReceiptRefreshRequest(receiptProperties: receiptProperties, callback: callback)
request.start()
return request
}
let refreshReceiptRequest: SKReceiptRefreshRequest
let callback: RequestCallback
deinit {
refreshReceiptRequest.delegate = nil
}
init(receiptProperties: [String: Any]? = nil, callback: @escaping RequestCallback) {
self.callback = callback
self.refreshReceiptRequest = SKReceiptRefreshRequest(receiptProperties: receiptProperties)
super.init()
self.refreshReceiptRequest.delegate = self
}
func start() {
self.refreshReceiptRequest.start()
}
func cancel() {
self.refreshReceiptRequest.cancel()
}
func requestDidFinish(_ request: SKRequest) {
/*if let resoreRequest = request as? SKReceiptRefreshRequest {
let receiptProperties = resoreRequest.receiptProperties ?? [:]
for (k, v) in receiptProperties {
print("\(k): \(v)")
}
}*/
performCallback(.success)
}
func request(_ request: SKRequest, didFailWithError error: Error) {
// XXX could here check domain and error code to return typed exception
performCallback(.error(e: error))
}
private func performCallback(_ result: ResultType) {
DispatchQueue.main.async {
self.callback(result)
}
}
}
//
// InAppReceiptVerificator.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 16/05/2017.
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
class InAppReceiptVerificator: NSObject {
let appStoreReceiptURL: URL?
init(appStoreReceiptURL: URL? = Bundle.main.appStoreReceiptURL) {
self.appStoreReceiptURL = appStoreReceiptURL
}
var appStoreReceiptData: Data? {
guard let receiptDataURL = appStoreReceiptURL,
let data = try? Data(contentsOf: receiptDataURL) else {
return nil
}
return data
}
private var receiptRefreshRequest: InAppReceiptRefreshRequest?
/**
* Verify application receipt.
* - Parameter validator: Validator to check the encrypted receipt and return the receipt in readable format
* - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
* - Parameter refresh: closure to perform receipt refresh (this is made explicit for testability)
* - Parameter completion: handler for result
*/
@discardableResult
public func verifyReceipt(using validator: ReceiptValidator,
forceRefresh: Bool,
refresh: InAppReceiptRefreshRequest.ReceiptRefresh = InAppReceiptRefreshRequest.refresh,
completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? {
return fetchReceipt(forceRefresh: forceRefresh, refresh: refresh) { result in
switch result {
case .success(let receiptData):
self.verify(receiptData: receiptData, using: validator, completion: completion)
case .error(let error):
completion(.error(error: error))
}
}
}
/**
* Fetch application receipt. This method does two things:
* * If the receipt is missing, refresh it
* * If the receipt is available or is refreshed, validate it
* - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
* - Parameter refresh: closure to perform receipt refresh (this is made explicit for testability)
* - Parameter completion: handler for result
*/
@discardableResult
public func fetchReceipt(forceRefresh: Bool,
refresh: InAppReceiptRefreshRequest.ReceiptRefresh = InAppReceiptRefreshRequest.refresh,
completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? {
if let receiptData = appStoreReceiptData, forceRefresh == false {
completion(.success(receiptData: receiptData))
return nil
} else {
receiptRefreshRequest = refresh(nil) { result in
self.receiptRefreshRequest = nil
switch result {
case .success:
if let receiptData = self.appStoreReceiptData {
completion(.success(receiptData: receiptData))
} else {
completion(.error(error: .noReceiptData))
}
case .error(let e):
completion(.error(error: .networkError(error: e)))
}
}
return receiptRefreshRequest
}
}
/**
* - Parameter receiptData: encrypted receipt data
* - Parameter validator: Validator to check the encrypted receipt and return the receipt in readable format
* - Parameter completion: handler for result
*/
private func verify(receiptData: Data, using validator: ReceiptValidator, completion: @escaping (VerifyReceiptResult) -> Void) {
validator.validate(receiptData: receiptData) { result in
DispatchQueue.main.async {
completion(result)
}
}
}
}
//
// OS.swift
// SwiftyStoreKit
//
// Copyright (c) 2020 Andrea Bizzotto (bizz84@gmail.com)
//
// 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 StoreKit
// MARK: - Missing SKMutablePayment init with product on macOS
#if os(OSX)
extension SKMutablePayment {
convenience init(product: SKProduct) {
self.init()
self.productIdentifier = product.productIdentifier
}
}
#endif
// MARK: - Missing SKError on watchOS
#if os(watchOS) && swift(<5.3)
public struct SKError: Error {
public typealias Code = SKErrorCode
let _nsError: NSError
init(_nsError: NSError) {
self._nsError = _nsError
}
var code: Code {
return Code(rawValue: _nsError.code) ?? .unknown
}
static var unknown: Code = .unknown
static var paymentInvalid: Code = .paymentInvalid
}
#endif
//
// PaymentQueueController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
import StoreKit
protocol TransactionController {
/// Process the supplied transactions on a given queue.
/// - parameter transactions: transactions to process
/// - parameter paymentQueue: payment queue for finishing transactions
/// - returns: array of unhandled transactions
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction]
}
public enum TransactionResult {
case purchased(purchase: PurchaseDetails)
case restored(purchase: Purchase)
case failed(error: SKError)
}
public protocol PaymentQueue: class {
func add(_ observer: SKPaymentTransactionObserver)
func remove(_ observer: SKPaymentTransactionObserver)
func add(_ payment: SKPayment)
func start(_ downloads: [SKDownload])
func pause(_ downloads: [SKDownload])
func resume(_ downloads: [SKDownload])
func cancel(_ downloads: [SKDownload])
func restoreCompletedTransactions(withApplicationUsername username: String?)
func finishTransaction(_ transaction: SKPaymentTransaction)
}
extension SKPaymentQueue: PaymentQueue {
#if os(watchOS) && swift(<5.3)
public func resume(_ downloads: [SKDownload]) {
resumeDownloads(downloads)
}
#endif
}
extension SKPaymentTransaction {
open override var debugDescription: String {
let transactionId = transactionIdentifier ?? "null"
return "productId: \(payment.productIdentifier), transactionId: \(transactionId), state: \(transactionState), date: \(String(describing: transactionDate))"
}
}
extension SKPaymentTransactionState: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .purchasing: return "purchasing"
case .purchased: return "purchased"
case .failed: return "failed"
case .restored: return "restored"
case .deferred: return "deferred"
@unknown default: return "default"
}
}
}
class PaymentQueueController: NSObject, SKPaymentTransactionObserver {
private let paymentsController: PaymentsController
private let restorePurchasesController: RestorePurchasesController
private let completeTransactionsController: CompleteTransactionsController
unowned let paymentQueue: PaymentQueue
deinit {
paymentQueue.remove(self)
}
init(paymentQueue: PaymentQueue = SKPaymentQueue.default(),
paymentsController: PaymentsController = PaymentsController(),
restorePurchasesController: RestorePurchasesController = RestorePurchasesController(),
completeTransactionsController: CompleteTransactionsController = CompleteTransactionsController()) {
self.paymentQueue = paymentQueue
self.paymentsController = paymentsController
self.restorePurchasesController = restorePurchasesController
self.completeTransactionsController = completeTransactionsController
super.init()
paymentQueue.add(self)
}
private func assertCompleteTransactionsWasCalled() {
let message = "SwiftyStoreKit.completeTransactions() must be called when the app launches."
assert(completeTransactionsController.completeTransactions != nil, message)
}
func startPayment(_ payment: Payment) {
assertCompleteTransactionsWasCalled()
let skPayment = SKMutablePayment(product: payment.product)
skPayment.applicationUsername = payment.applicationUsername
skPayment.quantity = payment.quantity
if #available(iOS 12.2, tvOS 12.2, OSX 10.14.4, watchOS 6.2, *) {
if let discount = payment.paymentDiscount?.discount as? SKPaymentDiscount {
skPayment.paymentDiscount = discount
}
}
#if os(iOS) || os(tvOS) || os(watchOS)
if #available(iOS 8.3, watchOS 6.2, *) {
skPayment.simulatesAskToBuyInSandbox = payment.simulatesAskToBuyInSandbox
}
#endif
paymentQueue.add(skPayment)
paymentsController.append(payment)
}
func restorePurchases(_ restorePurchases: RestorePurchases) {
assertCompleteTransactionsWasCalled()
if restorePurchasesController.restorePurchases != nil {
return
}
paymentQueue.restoreCompletedTransactions(withApplicationUsername: restorePurchases.applicationUsername)
restorePurchasesController.restorePurchases = restorePurchases
}
func completeTransactions(_ completeTransactions: CompleteTransactions) {
guard completeTransactionsController.completeTransactions == nil else {
print("SwiftyStoreKit.completeTransactions() should only be called once when the app launches. Ignoring this call")
return
}
completeTransactionsController.completeTransactions = completeTransactions
}
func finishTransaction(_ transaction: PaymentTransaction) {
guard let skTransaction = transaction as? SKPaymentTransaction else {
print("Object is not a SKPaymentTransaction: \(transaction)")
return
}
paymentQueue.finishTransaction(skTransaction)
}
func start(_ downloads: [SKDownload]) {
paymentQueue.start(downloads)
}
func pause(_ downloads: [SKDownload]) {
paymentQueue.pause(downloads)
}
func resume(_ downloads: [SKDownload]) {
paymentQueue.resume(downloads)
}
func cancel(_ downloads: [SKDownload]) {
paymentQueue.cancel(downloads)
}
var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler?
var updatedDownloadsHandler: UpdatedDownloadsHandler?
// MARK: SKPaymentTransactionObserver
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
/*
* Some notes about how requests are processed by SKPaymentQueue:
*
* SKPaymentQueue is used to queue payments or restore purchases requests.
* Payments are processed serially and in-order and require user interaction.
* Restore purchases requests don't require user interaction and can jump ahead of the queue.
* SKPaymentQueue rejects multiple restore purchases calls.
* Having one payment queue observer for each request causes extra processing
* Failed transactions only ever belong to queued payment requests.
* restoreCompletedTransactionsFailedWithError is always called when a restore purchases request fails.
* paymentQueueRestoreCompletedTransactionsFinished is always called following 0 or more update transactions when a restore purchases request succeeds.
* A complete transactions handler is require to catch any transactions that are updated when the app is not running.
* Registering a complete transactions handler when the app launches ensures that any pending transactions can be cleared.
* If a complete transactions handler is missing, pending transactions can be mis-attributed to any new incoming payments or restore purchases.
*
* The order in which transaction updates are processed is:
* 1. payments (transactionState: .purchased and .failed for matching product identifiers)
* 2. restore purchases (transactionState: .restored, or restoreCompletedTransactionsFailedWithError, or paymentQueueRestoreCompletedTransactionsFinished)
* 3. complete transactions (transactionState: .purchased, .failed, .restored, .deferred)
* Any transactions where state == .purchasing are ignored.
*/
var unhandledTransactions = transactions.filter { $0.transactionState != .purchasing }
if unhandledTransactions.count > 0 {
unhandledTransactions = paymentsController.processTransactions(transactions, on: paymentQueue)
unhandledTransactions = restorePurchasesController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = completeTransactionsController.processTransactions(unhandledTransactions, on: paymentQueue)
if unhandledTransactions.count > 0 {
let strings = unhandledTransactions.map { $0.debugDescription }.joined(separator: "\n")
print("unhandledTransactions:\n\(strings)")
}
}
}
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
}
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
restorePurchasesController.restoreCompletedTransactionsFailed(withError: error)
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
restorePurchasesController.restoreCompletedTransactionsFinished()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
updatedDownloadsHandler?(downloads)
}
#if os(iOS) && !targetEnvironment(macCatalyst)
func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
return shouldAddStorePaymentHandler?(payment, product) ?? false
}
#endif
}
//
// PaymentsController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
import StoreKit
struct Payment: Hashable {
let product: SKProduct
let paymentDiscount: PaymentDiscount?
let quantity: Int
let atomically: Bool
let applicationUsername: String
let simulatesAskToBuyInSandbox: Bool
let callback: (TransactionResult) -> Void
func hash(into hasher: inout Hasher) {
hasher.combine(product)
hasher.combine(quantity)
hasher.combine(atomically)
hasher.combine(applicationUsername)
hasher.combine(simulatesAskToBuyInSandbox)
}
static func == (lhs: Payment, rhs: Payment) -> Bool {
return lhs.product.productIdentifier == rhs.product.productIdentifier
}
}
public struct PaymentDiscount {
let discount: AnyObject?
@available(iOS 12.2, tvOS 12.2, OSX 10.14.4, watchOS 6.2, macCatalyst 13.0, *)
public init(discount: SKPaymentDiscount) {
self.discount = discount
}
private init() {
self.discount = nil
}
}
class PaymentsController: TransactionController {
private var payments: [Payment] = []
private func findPaymentIndex(withProductIdentifier identifier: String) -> Int? {
for payment in payments where payment.product.productIdentifier == identifier {
return payments.firstIndex(of: payment)
}
return nil
}
func hasPayment(_ payment: Payment) -> Bool {
return findPaymentIndex(withProductIdentifier: payment.product.productIdentifier) != nil
}
func append(_ payment: Payment) {
payments.append(payment)
}
func processTransaction(_ transaction: SKPaymentTransaction, on paymentQueue: PaymentQueue) -> Bool {
let transactionProductIdentifier = transaction.payment.productIdentifier
guard let paymentIndex = findPaymentIndex(withProductIdentifier: transactionProductIdentifier) else {
return false
}
let payment = payments[paymentIndex]
let transactionState = transaction.transactionState
if transactionState == .purchased {
let purchase = PurchaseDetails(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, product: payment.product, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !payment.atomically)
payment.callback(.purchased(purchase: purchase))
if payment.atomically {
paymentQueue.finishTransaction(transaction)
}
payments.remove(at: paymentIndex)
return true
}
if transactionState == .restored {
print("Unexpected restored transaction for payment \(transactionProductIdentifier)")
let purchase = PurchaseDetails(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, product: payment.product, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !payment.atomically)
payment.callback(.purchased(purchase: purchase))
if payment.atomically {
paymentQueue.finishTransaction(transaction)
}
payments.remove(at: paymentIndex)
return true
}
if transactionState == .failed {
payment.callback(.failed(error: transactionError(for: transaction.error as NSError?)))
paymentQueue.finishTransaction(transaction)
payments.remove(at: paymentIndex)
return true
}
return false
}
func transactionError(for error: NSError?) -> SKError {
let message = "Unknown error"
let altError = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: [ NSLocalizedDescriptionKey: message ])
let nsError = error ?? altError
return SKError(_nsError: nsError)
}
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] {
return transactions.filter { !processTransaction($0, on: paymentQueue) }
}
}
//
// ProductsInfoController.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
import StoreKit
protocol InAppProductRequestBuilder: class {
func request(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest
}
class InAppProductQueryRequestBuilder: InAppProductRequestBuilder {
func request(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest {
return InAppProductQueryRequest(productIds: productIds, callback: callback)
}
}
class ProductsInfoController: NSObject {
struct InAppProductQuery {
let request: InAppProductRequest
var completionHandlers: [InAppProductRequestCallback]
}
let inAppProductRequestBuilder: InAppProductRequestBuilder
init(inAppProductRequestBuilder: InAppProductRequestBuilder = InAppProductQueryRequestBuilder()) {
self.inAppProductRequestBuilder = inAppProductRequestBuilder
}
// As we can have multiple inflight requests, we store them in a dictionary by product ids
private var inflightRequests: [Set<String>: InAppProductQuery] = [:]
@discardableResult
func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
if inflightRequests[productIds] == nil {
let request = inAppProductRequestBuilder.request(productIds: productIds) { results in
if let query = self.inflightRequests[productIds] {
for completion in query.completionHandlers {
completion(results)
}
self.inflightRequests[productIds] = nil
} else {
// should not get here, but if it does it seems reasonable to call the outer completion block
completion(results)
}
}
inflightRequests[productIds] = InAppProductQuery(request: request, completionHandlers: [completion])
request.start()
return request
} else {
inflightRequests[productIds]!.completionHandlers.append(completion)
return inflightRequests[productIds]!.request
}
}
}
//
// RestorePurchasesController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// 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
import StoreKit
struct RestorePurchases {
let atomically: Bool
let applicationUsername: String?
let callback: ([TransactionResult]) -> Void
init(atomically: Bool, applicationUsername: String? = nil, callback: @escaping ([TransactionResult]) -> Void) {
self.atomically = atomically
self.applicationUsername = applicationUsername
self.callback = callback
}
}
class RestorePurchasesController: TransactionController {
public var restorePurchases: RestorePurchases?
private var restoredPurchases: [TransactionResult] = []
func processTransaction(_ transaction: SKPaymentTransaction, atomically: Bool, on paymentQueue: PaymentQueue) -> Purchase? {
let transactionState = transaction.transactionState
if transactionState == .restored {
let transactionProductIdentifier = transaction.payment.productIdentifier
let purchase = Purchase(productId: transactionProductIdentifier, quantity: transaction.payment.quantity, transaction: transaction, originalTransaction: transaction.original, needsFinishTransaction: !atomically)
if atomically {
paymentQueue.finishTransaction(transaction)
}
return purchase
}
return nil
}
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction] {
guard let restorePurchases = restorePurchases else {
return transactions
}
var unhandledTransactions: [SKPaymentTransaction] = []
for transaction in transactions {
if let restoredPurchase = processTransaction(transaction, atomically: restorePurchases.atomically, on: paymentQueue) {
restoredPurchases.append(.restored(purchase: restoredPurchase))
} else {
unhandledTransactions.append(transaction)
}
}
return unhandledTransactions
}
func restoreCompletedTransactionsFailed(withError error: Error) {
guard let restorePurchases = restorePurchases else {
print("Callback already called. Returning")
return
}
restoredPurchases.append(.failed(error: SKError(_nsError: error as NSError)))
restorePurchases.callback(restoredPurchases)
// Reset state after error received
restoredPurchases = []
self.restorePurchases = nil
}
func restoreCompletedTransactionsFinished() {
guard let restorePurchases = restorePurchases else {
print("Callback already called. Returning")
return
}
restorePurchases.callback(restoredPurchases)
// Reset state after error transactions finished
restoredPurchases = []
self.restorePurchases = nil
}
}
//
// SKProduct+LocalizedPrice.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 19/10/2016.
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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 StoreKit
public extension SKProduct {
var localizedPrice: String? {
return priceFormatter(locale: priceLocale).string(from: price)
}
private func priceFormatter(locale: Locale) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
return formatter
}
@available(iOSApplicationExtension 11.2, iOS 11.2, OSX 10.13.2, tvOS 11.2, watchOS 6.2, macCatalyst 13.0, *)
var localizedSubscriptionPeriod: String {
guard let subscriptionPeriod = self.subscriptionPeriod else { return "" }
let dateComponents: DateComponents
switch subscriptionPeriod.unit {
case .day: dateComponents = DateComponents(day: subscriptionPeriod.numberOfUnits)
case .week: dateComponents = DateComponents(weekOfMonth: subscriptionPeriod.numberOfUnits)
case .month: dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
case .year: dateComponents = DateComponents(year: subscriptionPeriod.numberOfUnits)
@unknown default:
print("WARNING: SwiftyStoreKit localizedSubscriptionPeriod does not handle all SKProduct.PeriodUnit cases.")
// Default to month units in the unlikely event a different unit type is added to a future OS version
dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
}
return DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: .short) ?? ""
}
}
//
// SKProductDiscount+LocalizedPrice.swift
// SwiftyStoreKit
//
// Created by Sam Spencer on 5/29/20.
// Copyright © 2020 Sam Spencer. All rights reserved.
//
// 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 StoreKit
@available(iOSApplicationExtension 11.2, iOS 11.2, OSX 10.13.2, tvOS 11.2, watchOS 4.2, macCatalyst 13.0, *)
public extension SKProductDiscount {
/// The formatted discount price of the product using the local currency.
var localizedPrice: String? {
return priceFormatter(locale: priceLocale).string(from: price)
}
private func priceFormatter(locale: Locale) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
return formatter
}
/// The formatted, localized period / date for the product discount.
/// - note: The subscription period for the discount is independent of the product's regular subscription period, and does not have to match in units or duration.
var localizedSubscriptionPeriod: String {
let dateComponents: DateComponents
switch subscriptionPeriod.unit {
case .day: dateComponents = DateComponents(day: subscriptionPeriod.numberOfUnits)
case .week: dateComponents = DateComponents(weekOfMonth: subscriptionPeriod.numberOfUnits)
case .month: dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
case .year: dateComponents = DateComponents(year: subscriptionPeriod.numberOfUnits)
@unknown default:
print("WARNING: SwiftyStoreKit localizedSubscriptionPeriod does not handle all SKProduct.PeriodUnit cases.")
// Default to month units in the unlikely event a different unit type is added to a future OS version
dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits)
}
return DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: .full) ?? ""
}
}
//
// SwiftyStoreKit+Types.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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 StoreKit
// MARK: Purchases
/// The Purchased protocol allows different purchase flows to be handled by common code in simple cases
///
/// For example you could route through to
///
/// func didPurchase<P:Purchased>(item:P) { ... }
///
/// for example
/// - SwiftyStoreKit.completeTransactions (in .purchased and .restored cases)
/// - SwiftyStoreKit.restorePurchases (for results.restoredPurchases)
/// - SwiftyStoreKit.purchaseProducd (in .success case)
public protocol Purchased {
var productId: String { get }
var quantity: Int { get }
var originalPurchaseDate: Date { get }
}
extension Purchase: Purchased {
public var originalPurchaseDate: Date {
guard let date = originalTransaction?.transactionDate ?? transaction.transactionDate else {
fatalError("there should always be a transaction date, so this should not happen...")
}
return date
}
}
extension PurchaseDetails: Purchased {
public var originalPurchaseDate: Date {
guard let date = originalTransaction?.transactionDate ?? transaction.transactionDate else {
fatalError("there should always be a transaction date, so this should not happen...")
}
return date
}
}
// Restored product
public struct Purchase {
public let productId: String
public let quantity: Int
public let transaction: PaymentTransaction
public let originalTransaction: PaymentTransaction?
public let needsFinishTransaction: Bool
public init(productId: String, quantity: Int, transaction: PaymentTransaction, originalTransaction: PaymentTransaction?, needsFinishTransaction: Bool) {
self.productId = productId
self.quantity = quantity
self.transaction = transaction
self.originalTransaction = originalTransaction
self.needsFinishTransaction = needsFinishTransaction
}
}
/// Purchased product
public struct PurchaseDetails {
public let productId: String
public let quantity: Int
public let product: SKProduct
public let transaction: PaymentTransaction
public let originalTransaction: PaymentTransaction?
public let needsFinishTransaction: Bool
public init(productId: String, quantity: Int, product: SKProduct, transaction: PaymentTransaction, originalTransaction: PaymentTransaction?, needsFinishTransaction: Bool) {
self.productId = productId
self.quantity = quantity
self.product = product
self.transaction = transaction
self.originalTransaction = originalTransaction
self.needsFinishTransaction = needsFinishTransaction
}
}
/// Conform to this protocol to provide custom receipt validator
public protocol ReceiptValidator {
func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void)
}
/// Payment transaction
public protocol PaymentTransaction {
var transactionDate: Date? { get }
var transactionState: SKPaymentTransactionState { get }
var transactionIdentifier: String? { get }
var downloads: [SKDownload] { get }
}
/// Add PaymentTransaction conformance to SKPaymentTransaction
extension SKPaymentTransaction: PaymentTransaction { }
/// Products information
public struct RetrieveResults {
public let retrievedProducts: Set<SKProduct>
public let invalidProductIDs: Set<String>
public let error: Error?
public init(retrievedProducts: Set<SKProduct>, invalidProductIDs: Set<String>, error: Error?) {
self.retrievedProducts = retrievedProducts
self.invalidProductIDs = invalidProductIDs
self.error = error
}
}
/// Purchase result
public enum PurchaseResult {
case success(purchase: PurchaseDetails)
case error(error: SKError)
}
/// Restore purchase results
public struct RestoreResults {
public let restoredPurchases: [Purchase]
public let restoreFailedPurchases: [(SKError, String?)]
public init(restoredPurchases: [Purchase], restoreFailedPurchases: [(SKError, String?)]) {
self.restoredPurchases = restoredPurchases
self.restoreFailedPurchases = restoreFailedPurchases
}
}
public typealias ShouldAddStorePaymentHandler = (_ payment: SKPayment, _ product: SKProduct) -> Bool
public typealias UpdatedDownloadsHandler = (_ downloads: [SKDownload]) -> Void
// MARK: Receipt verification
/// Info for receipt returned by server
public typealias ReceiptInfo = [String: AnyObject]
/// Fetch receipt result
public enum FetchReceiptResult {
case success(receiptData: Data)
case error(error: ReceiptError)
}
/// Verify receipt result
public enum VerifyReceiptResult {
case success(receipt: ReceiptInfo)
case error(error: ReceiptError)
}
/// Result for Consumable and NonConsumable
public enum VerifyPurchaseResult {
case purchased(item: ReceiptItem)
case notPurchased
}
/// Verify subscription result
public enum VerifySubscriptionResult {
case purchased(expiryDate: Date, items: [ReceiptItem])
case expired(expiryDate: Date, items: [ReceiptItem])
case notPurchased
}
public enum SubscriptionType {
case autoRenewable
case nonRenewing(validDuration: TimeInterval)
}
public struct ReceiptItem: Purchased, Codable {
/// The product identifier of the item that was purchased. This value corresponds to the `productIdentifier` property of the `SKPayment` object stored in the transaction’s payment property.
public var productId: String
/// The number of items purchased. This value corresponds to the `quantity` property of the `SKPayment` object stored in the transaction’s payment property.
public var quantity: Int
/// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s `transactionIdentifier` property.
public var transactionId: String
/// For a transaction that restores a previous transaction, the transaction identifier of the original transaction.
///
/// Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s `transactionIdentifier` property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
public var originalTransactionId: String
/// The date and time that the item was purchased. This value corresponds to the transaction’s `transactionDate` property.
public var purchaseDate: Date
/// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s `transactionDate` property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
public var originalPurchaseDate: Date
/// The primary key for identifying subscription purchases.
public var webOrderLineItemId: String?
/// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is **only** present for **auto-renewable** subscription receipts.
public var subscriptionExpirationDate: Date?
/// For a transaction that was canceled by Apple customer support, the time and date of the cancellation.
///
/// Treat a canceled receipt the same as if no purchase had ever been made.
public var cancellationDate: Date?
/// Indicates whether or not the subscription item is currently within a given trial period.
public var isTrialPeriod: Bool
/// Indicates whether or not the subscription item is currently within an intro offer period.
public var isInIntroOfferPeriod: Bool
public init(productId: String, quantity: Int, transactionId: String, originalTransactionId: String, purchaseDate: Date, originalPurchaseDate: Date, webOrderLineItemId: String?, subscriptionExpirationDate: Date?, cancellationDate: Date?, isTrialPeriod: Bool, isInIntroOfferPeriod: Bool) {
self.productId = productId
self.quantity = quantity
self.transactionId = transactionId
self.originalTransactionId = originalTransactionId
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.webOrderLineItemId = webOrderLineItemId
self.subscriptionExpirationDate = subscriptionExpirationDate
self.cancellationDate = cancellationDate
self.isTrialPeriod = isTrialPeriod
self.isInIntroOfferPeriod = isInIntroOfferPeriod
}
}
/// Error when managing receipt
public enum ReceiptError: Swift.Error {
/// No receipt data
case noReceiptData
/// No data received
case noRemoteData
/// Error when encoding HTTP body into JSON
case requestBodyEncodeError(error: Swift.Error)
/// Error when proceeding request
case networkError(error: Swift.Error)
/// Error when decoding response
case jsonDecodeError(string: String?)
/// Receive invalid - bad status returned
case receiptInvalid(receipt: ReceiptInfo, status: ReceiptStatus)
}
/// Status code returned by remote server
///
/// See Table 2-1 Status codes
public enum ReceiptStatus: Int {
/// Not decodable status
case unknown = -2
/// No status returned
case none = -1
/// valid statua
case valid = 0
/// The App Store could not read the JSON object you provided.
case jsonNotReadable = 21000
/// The data in the receipt-data property was malformed or missing.
case malformedOrMissingData = 21002
/// The receipt could not be authenticated.
case receiptCouldNotBeAuthenticated = 21003
/// The shared secret you provided does not match the shared secret on file for your account.
case secretNotMatching = 21004
/// The receipt server is not currently available.
case receiptServerUnavailable = 21005
/// This receipt is valid but the subscription has expired. When this status code is returned to your server, the receipt data is also decoded and returned as part of the response.
case subscriptionExpired = 21006
/// This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.
case testReceipt = 21007
/// This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.
case productionEnvironment = 21008
var isValid: Bool { return self == .valid}
}
// Receipt field as defined in : https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1
public enum ReceiptInfoField: String {
/// Bundle Identifier. This corresponds to the value of CFBundleIdentifier in the Info.plist file.
case bundle_id
/// The app’s version number.This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist.
case application_version
/// The version of the app that was originally purchased. This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist file when the purchase was originally made.
case original_application_version
/// The date when the app receipt was created.
case creation_date
/// The date that the app receipt expires. This key is present only for apps purchased through the Volume Purchase Program.
case expiration_date
/// The receipt for an in-app purchase.
case in_app
public enum InApp: String {
/// The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property.
case quantity
/// The product identifier of the item that was purchased. This value corresponds to the productIdentifier property of the SKPayment object stored in the transaction’s payment property.
case product_id
/// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s transactionIdentifier property.
case transaction_id
/// For a transaction that restores a previous transaction, the transaction identifier of the original transaction. Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s transactionIdentifier property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
case original_transaction_id
/// The date and time that the item was purchased. This value corresponds to the transaction’s transactionDate property.
case purchase_date
/// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s transactionDate property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
case original_purchase_date
/// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is only present for auto-renewable subscription receipts.
case expires_date
/// For a transaction that was canceled by Apple customer support, the time and date of the cancellation. Treat a canceled receipt the same as if no purchase had ever been made.
case cancellation_date
#if os(iOS) || os(tvOS)
/// A string that the App Store uses to uniquely identify the application that created the transaction. If your server supports multiple applications, you can use this value to differentiate between them. Apps are assigned an identifier only in the production environment, so this key is not present for receipts created in the test environment. This field is not present for Mac apps. See also Bundle Identifier.
case app_item_id
#endif
/// An arbitrary number that uniquely identifies a revision of your application. This key is not present for receipts created in the test environment.
case version_external_identifier
/// The primary key for identifying subscription purchases.
case web_order_line_item_id
}
}
#if os(OSX)
public enum ReceiptExitCode: Int32 {
/// If validation fails in OS X, call exit with a status of 173. This exit status notifies the system that your application has determined that its receipt is invalid. At this point, the system attempts to obtain a valid receipt and may prompt for the user’s iTunes credentials
case notValid = 173
}
#endif
//
// SwiftyStoreKit.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// 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 StoreKit
public class SwiftyStoreKit {
private let productsInfoController: ProductsInfoController
fileprivate let paymentQueueController: PaymentQueueController
fileprivate let receiptVerificator: InAppReceiptVerificator
init(productsInfoController: ProductsInfoController = ProductsInfoController(),
paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default()),
receiptVerificator: InAppReceiptVerificator = InAppReceiptVerificator()) {
self.productsInfoController = productsInfoController
self.paymentQueueController = paymentQueueController
self.receiptVerificator = receiptVerificator
}
// MARK: private methods
fileprivate func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
return productsInfoController.retrieveProductsInfo(productIds, completion: completion)
}
fileprivate func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) -> InAppProductRequest {
return retrieveProductsInfo(Set([productId])) { result -> Void in
if let product = result.retrievedProducts.first {
self.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
} else if let error = result.error {
completion(.error(error: SKError(_nsError: error as NSError)))
} else if let invalidProductId = result.invalidProductIDs.first {
let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ]
let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo)
completion(.error(error: SKError(_nsError: error)))
} else {
let error = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: nil)
completion(.error(error: SKError(_nsError: error)))
}
}
}
fileprivate func purchase(product: SKProduct, quantity: Int, atomically: Bool, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping (PurchaseResult) -> Void) {
paymentQueueController.startPayment(Payment(product: product, paymentDiscount: paymentDiscount, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox) { result in
completion(self.processPurchaseResult(result))
})
}
fileprivate func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in
let results = self.processRestoreResults(results)
completion(results)
})
}
fileprivate func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion))
}
fileprivate func finishTransaction(_ transaction: PaymentTransaction) {
paymentQueueController.finishTransaction(transaction)
}
private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult {
switch result {
case .purchased(let purchase):
return .success(purchase: purchase)
case .failed(let error):
return .error(error: error)
case .restored(let purchase):
return .error(error: storeInternalError(description: "Cannot restore product \(purchase.productId) from purchase path"))
}
}
private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults {
var restoredPurchases: [Purchase] = []
var restoreFailedPurchases: [(SKError, String?)] = []
for result in results {
switch result {
case .purchased(let purchase):
let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
restoreFailedPurchases.append((error, purchase.productId))
case .failed(let error):
restoreFailedPurchases.append((error, nil))
case .restored(let purchase):
restoredPurchases.append(purchase)
}
}
return RestoreResults(restoredPurchases: restoredPurchases, restoreFailedPurchases: restoreFailedPurchases)
}
private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError {
let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ])
return SKError(_nsError: error)
}
}
extension SwiftyStoreKit {
// MARK: Singleton
fileprivate static let sharedInstance = SwiftyStoreKit()
// MARK: Public methods - Purchases
/// Check if the current device can make payments.
/// - returns: `false` if this device is not able or allowed to make payments
public class var canMakePayments: Bool {
return SKPaymentQueue.canMakePayments()
}
/// Retrieve products information
/// - Parameter productIds: The set of product identifiers to retrieve corresponding products for
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppRequest {
return sharedInstance.retrieveProductsInfo(productIds, completion: completion)
}
/// Purchase a product
/// - Parameter productId: productId as specified in App Store Connect
/// - Parameter quantity: quantity of the product to be purchased
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) -> InAppRequest {
return sharedInstance.purchaseProduct(productId, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
}
/// Purchase a product
/// - Parameter product: product to be purchased
/// - Parameter quantity: quantity of the product to be purchased
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter product: optional discount to be applied. Must be of `SKProductPayment` type
/// - Parameter completion: handler for result
public class func purchaseProduct(_ product: SKProduct, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping ( PurchaseResult) -> Void) {
sharedInstance.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, paymentDiscount: paymentDiscount, completion: completion)
}
/// Restore purchases
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter completion: handler for result
public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion)
}
/// Complete transactions
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter completion: handler for result
public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
sharedInstance.completeTransactions(atomically: atomically, completion: completion)
}
/// Finish a transaction
///
/// Once the content has been delivered, call this method to finish a transaction that was performed non-atomically
/// - Parameter transaction: transaction to finish
public class func finishTransaction(_ transaction: PaymentTransaction) {
sharedInstance.finishTransaction(transaction)
}
/// Register a handler for `SKPaymentQueue.shouldAddStorePayment` delegate method.
/// - requires: iOS 11.0+
public static var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler? {
didSet {
sharedInstance.paymentQueueController.shouldAddStorePaymentHandler = shouldAddStorePaymentHandler
}
}
/// Register a handler for `paymentQueue(_:updatedDownloads:)`
/// - seealso: `paymentQueue(_:updatedDownloads:)`
public static var updatedDownloadsHandler: UpdatedDownloadsHandler? {
didSet {
sharedInstance.paymentQueueController.updatedDownloadsHandler = updatedDownloadsHandler
}
}
public class func start(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.start(downloads)
}
public class func pause(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.pause(downloads)
}
public class func resume(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.resume(downloads)
}
public class func cancel(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.cancel(downloads)
}
}
extension SwiftyStoreKit {
// MARK: Public methods - Receipt verification
/// Return receipt data from the application bundle. This is read from `Bundle.main.appStoreReceiptURL`.
public static var localReceiptData: Data? {
return sharedInstance.receiptVerificator.appStoreReceiptData
}
/// Verify application receipt
/// - Parameter validator: receipt validator to use
/// - Parameter forceRefresh: If `true`, refreshes the receipt even if one already exists.
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func verifyReceipt(using validator: ReceiptValidator, forceRefresh: Bool = false, completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? {
return sharedInstance.receiptVerificator.verifyReceipt(using: validator, forceRefresh: forceRefresh, completion: completion)
}
/// Fetch application receipt
/// - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func fetchReceipt(forceRefresh: Bool, completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? {
return sharedInstance.receiptVerificator.fetchReceipt(forceRefresh: forceRefresh, completion: completion)
}
/// 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
/// - returns: A `VerifyPurchaseResult`, which may be either `notPurchased` or `purchased`.
public class func verifyPurchase(productId: String, inReceipt receipt: ReceiptInfo) -> VerifyPurchaseResult {
return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt)
}
/**
* Verify the validity of a subscription (auto-renewable, free or non-renewing) in a receipt.
*
* This method extracts all transactions matching the given productId and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date to determine its validity.
* - Parameter type: `.autoRenewable` or `.nonRenewing`.
* - Parameter productId: The product id of the subscription to verify.
* - Parameter receipt: The receipt to use for looking up the subscription.
* - Parameter validUntil: Date to check against the expiry date of the subscription. This is only used if a date is not found in the receipt.
* - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
*/
public class func verifySubscription(ofType type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: [productId], inReceipt: receipt, validUntil: date)
}
/**
* 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.
* - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
*/
public class func verifySubscriptions(ofType type: SubscriptionType = .autoRenewable, productIds: Set<String>, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: productIds, inReceipt: receipt, validUntil: date)
}
/// Get the distinct product identifiers from receipt.
///
/// This Method extracts all product identifiers. (Including cancelled ones).
/// - Note: You can use this method to get all unique product identifiers from receipt.
/// - Parameter type: `.autoRenewable` or `.nonRenewing`.
/// - Parameter receipt: The receipt to use for looking up product identifiers.
/// - returns: Either `Set<String>` or `nil`.
public class func getDistinctPurchaseIds(ofType type: SubscriptionType = .autoRenewable, inReceipt receipt: ReceiptInfo) -> Set<String>? {
return InAppReceipt.getDistinctPurchaseIds(ofType: type, inReceipt: receipt)
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:superCleaner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment