In-App Purchase Helper

What’s IAPHelper

IAPHelper simply wraps the API of Apple’s In-App Purchase using Swift. Very lightweight and easy to use.

IAPHelper opens source and welcome to improve it.

IAPHelper Usage

Request Product List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var productIdentifiers = Set<ProductIdentifier>()
productIdentifiers.insert("product_id_1")
productIdentifiers.insert("product_id_2")
IAP.requestProducts(productIdentifiers) { (response, error) in
if let products = response?.products where !products.isEmpty {
// Get the valid products
} else if let invalidProductIdentifiers = response?.invalidProductIdentifiers {
// Some products id are invalid
} else if error?.code == SKErrorPaymentCancelled {
// User cancelled
} else {
// Some error happened
}
}

Purchase Product

1
2
3
4
5
6
7
8
9
10
11
IAP.purchaseProduct(productIdentifier, handler: { (productIdentifier, error) in
if let identifier = productIdentifier {
// The product of 'productIdentifier' purchased.
} else if error?.code == SKErrorPaymentCancelled {
// User cancelled
} else {
// Some error happened
}
})

Restore

1
2
3
4
5
6
7
8
9
10
11
12
13
14
IAP.restorePurchases { (productIdentifiers, error) in
if !productIdentifiers.isEmpty {
// Products restored
} else if error?.code == SKErrorUnknown {
// NOTE: if no product ever purchased, will return this error.
} else if error?.code == SKErrorPaymentCancelled {
// User cancelled
} else {
// Some error happened
}
}

Validate Receipt

1
2
3
4
5
6
7
IAP.validateReceipt(Constants.IAPSharedSecret) { (statusCode, products) in
if statusCode == ReceiptStatus.NoRecipt.rawValue {
// No Receipt in main bundle
} else {
// Get products with their expire date.
}
})

Note: IAPHelper directly validate with Apple’s server. It’s simple, but has risk. You decide use your own server or not as Apple suggested:

Use a trusted server to communicate with the App Store. Using your own server lets you design your app to recognize and trust only your server, and lets you ensure that your server connects with the App Store server. It is not possible to build a trusted connection between a user’s device and the App Store directly because you don’t control either end of that connection.

Integrate IAPHelper in Your Project

Just copy IAPHelper.swift to your project, and use it as the demo shows.

IAPHelper Demo

NOTE: You need to change the app bundle id and product id to your own. And also set your shared secret in Constants.swift.

Note

This library can’t help you understand the basic concepts for IAP. For it, please refer to these documents.

What’s Test

It’s mainly test on macOS 10.10 with auto-renew subscription. Now it’s used by my app of iPic.