Apphud – Integrate, analyze and improve subscriptions in your iOS app
Development

Swift tutorial: auto-renewable subscriptions in iOS

In this article I will talk about auto-renewable subscriptions on latest iOS 12 & iOS 13. I will show how to create, manage, purchase and validate auto-renewable subscriptions. I will also talk about hidden rocks and some cases that many developers miss out.

Set up subscriptions in App Store Connect

If you already have an app in ASC (abbreviated from App Store Connect) you may skip this tutorial and go to coding part. But if you don’t have an app yet here is what you need to do.

Before going to ASC you should first log in to Apple Developer Portal and open Certificates, Identifiers & Profile page. Then click on Identifiers tab. Since June 2019, Apple has finally updated this page design to match ASC.

A new design of Apple Developer Portal
A new design of Apple Developer Portal

You should create a new explicit Bundle ID. It’s a reverser-domain name style string (i.e. com.apphud.subscriptionstest). If you scroll down, you can see capabilities list where In-App Purchases has already been checked. After you create App ID, go to App Store Connect.

Certificates, identifiers and profiles
Certificates, identifiers and profiles

Another main step is filling up all information in Agreements, Tax and Banking section. You won’t have active Paid apps agreement you won’t be able to test in-app purchases.

After that you create a new App Store app. It’s really simple. Choose your recently created Bundle ID and enter any unique name — you can change it later.

New app creation form
New app creation form

If you already had an app, you can continue reading an article from here

In app page go to Features section. 

Adding auto-renewable subscriptions consists of several steps.

Creating subscription identifier and a subscription group. Subscription groups are like a collection of subscriptions, where just one can be active at one moment. Free trial period can be activated only once within a group. If your app needs two subscriptions at a time, then you will need to create two subscription groups.

You can read more about auto-renewable subscriptions in this article.

Next, you will need to fill subscription page: duration, display name and description. If you add your first subscription to a group you would need to specify a group display name as well. Save changes from time to time: ASC often freezes.

Subscription creation form
Subscription creation form

Finally, add subscription price. This includes the regular price, introductory offers and promotional offers. Add the price in your currency — it will be automatically recalculated for other currencies. Introductory offers let you create free trial, “pay as you go” or “pay up front” offers. Promotional offers is a new thing which was added recently: you can set up personal offers for users who canceled their subscription in order to bring them back.

Shared secret key

At the in-app purchases page you may notice “App-Specific Shared Secret” button. It’s a special key which is used for validating receipt. In our case we use it to get subscription status.

Shared secret key can be app-specific or account-specific (Master shared secret key). Don’t ever touch shared secrets if you have live apps: you won’t be able to validate purchases with an invalid key.

App specific shared secret key
App specific shared secret key

Copy all your subscriptions IDs and shared key. Now is programming part.

Programming auto-renewable subscriptions

How to make a good subscriptions manager class? This class at least should be capable of doing these:

  • Purchasing subscriptions
  • Checking subscription status
  • Refreshing a receipt
  • Restoring transactions (don’t confuse with receipt refreshing!)

Purchasing subscriptions

The process of purchasing a subscription can be divided into two steps: loading products information and implementing payment. But in advance we should set an observer for payment queue SKPaymentTransactionObserver:

// Starts products loading and sets transaction observer delegate
@objc func startWith(arrayOfIds : Set<String>!, sharedSecret : String){
    SKPaymentQueue.default().add(self)
    self.sharedSecret = sharedSecret
    self.productIds = arrayOfIds
    loadProducts()
}

private func loadProducts(){
    let request = SKProductsRequest.init(productIdentifiers: productIds)
    request.delegate = self
    request.start()
}

public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {                
    products = response.products
    DispatchQueue.main.async {
        NotificationCenter.default.post(name: IAP_PRODUCTS_DID_LOAD_NOTIFICATION, object: nil)
    }
}

func request(_ request: SKRequest, didFailWithError error: Error){
    print("error: \(error.localizedDescription)")
}

Full code is available at the end of this article.

When we request products information a delegate method will be called back. IAP_PRODUCTS_DID_LOAD_NOTIFICATION can be used to update UI in the app.

Later lets write payment initializing:

func purchaseProduct(product : SKProduct, success: @escaping SuccessBlock, failure: @escaping FailureBlock){
    guard SKPaymentQueue.canMakePayments() else {
        return
    }
    guard SKPaymentQueue.default().transactions.last?.transactionState != .purchasing else {
        return
    }
    
    self.successBlock = success
    self.failureBlock = failure
    
    let payment = SKPayment(product: product)
    SKPaymentQueue.default().add(payment)
}

And here’s our SKPaymentTransactionObserver delegate method:

extension IAPManager: SKPaymentTransactionObserver {
    
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                SKPaymentQueue.default().finishTransaction(transaction)
                notifyIsPurchased(transaction: transaction)
                break
            case .failed:
                SKPaymentQueue.default().finishTransaction(transaction)
                print("purchase error : \(transaction.error?.localizedDescription ?? "")")
                self.failureBlock?(transaction.error)
                cleanUp()
                break
            case .restored:
                SKPaymentQueue.default().finishTransaction(transaction)
                notifyIsPurchased(transaction: transaction)
                break
            case .deferred, .purchasing:
                break
            default:
                break
            }
        }
    }
    
    private func notifyIsPurchased(transaction: SKPaymentTransaction) {
        refreshSubscriptionsStatus(callback: { 
            self.successBlock?()
            self.cleanUp()
        }) { (error) in            
            // couldn't verify receipt
            self.failureBlock?(error)
            self.cleanUp()
        }
    }
    
    func cleanUp(){
        self.successBlock = nil
        self.failureBlock = nil
    }
}

After purchase operation finishes it calls func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) delegate method. We check transaction’s state to check whether purchase succeeded or not.

Okay, subscription has been purchased. But how to get its expiration date?

Checking subscription status

It is actually the same as validating receipt with the App Store. We send POST request verifyReceipt to Apple, in this request we include local receipt as a base64encoded string parameter. We get JSON in response, containing all our transactions. There’s an array of transactions with all purchases including renewals (by latest_receipt_info key). All we need to do is loop through array and check expiration date for all of those transactions and get active ones.

At WWDC 2017 a new key has been added as a request parameter: exclude-old-transactions. If we set it to true, then Apple will return only active transactions in a verifyReceipt request.

func refreshSubscriptionsStatus(callback : @escaping SuccessBlock, failure : @escaping FailureBlock){
    // save blocks for further use
    self.refreshSubscriptionSuccessBlock = callback
    self.refreshSubscriptionFailureBlock = failure
    guard let receiptUrl = Bundle.main.appStoreReceiptURL else {
            refreshReceipt()
            // do not call block yet
            return
    }
    #if DEBUG
        let urlString = "https://sandbox.itunes.apple.com/verifyReceipt"
    #else 
        let urlString = "https://buy.itunes.apple.com/verifyReceipt"
    #endif
    let receiptData = try? Data(contentsOf: receiptUrl).base64EncodedString()
    let requestData = ["receipt-data" : receiptData ?? "", "password" : self.sharedSecret, "exclude-old-transactions" : true] as [String : Any]
    var request = URLRequest(url: URL(string: urlString)!)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    let httpBody = try? JSONSerialization.data(withJSONObject: requestData, options: [])
    request.httpBody = httpBody
    URLSession.shared.dataTask(with: request)  { (data, response, error) in
        DispatchQueue.main.async {
            if data != nil {
                if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments){
                    self.parseReceipt(json as! Dictionary<String, Any>)
                    return
                }
            } else {
                print("error validating receipt: \(error?.localizedDescription ?? "")")
            }
            self.refreshSubscriptionFailureBlock?(error)
            self.cleanUpRefeshReceiptBlocks()                
        }
    }.resume()        
}

In the beginning of this method you will find that if local receipt is not found then request is not being sent. That’s correct: local receipt may not exist in some cases: for example, when you install an app from iTunes. In such cases we need to refresh a receipt first, then call this function again.

Refreshing a receipt

There is a special SKReceiptRefreshRequest class for it:

private func refreshReceipt(){
    let request = SKReceiptRefreshRequest(receiptProperties: nil)
    request.delegate = self
    request.start()
}

func requestDidFinish(_ request: SKRequest) {
  // call refresh subscriptions method again with same blocks
    if request is SKReceiptRefreshRequest {
        refreshSubscriptionsStatus(callback: self.successBlock ?? {}, failure: self.failureBlock ?? {_ in})
    }
}

func request(_ request: SKRequest, didFailWithError error: Error){
        if request is SKReceiptRefreshRequest {
            self.refreshSubscriptionFailureBlock?(error)
            self.cleanUpRefeshReceiptBlocks()            
        }
        print("error: \(error.localizedDescription)")
}

After we started this request we will get a delegate method requestDidFinish(_ request : SKRequest) which calls refreshSubscriptionsStatus again.

How we parse JSON response from Apple? Here’s an example how you can do that:

private func parseReceipt(_ json : Dictionary<String, Any>) {
    // It's the most simple way to get latest expiration date. Consider this code as for learning purposes. Do not use current code in production apps.
    guard let receipts_array = json["latest_receipt_info"] as? [Dictionary<String, Any>] else {
        self.refreshSubscriptionFailureBlock?(nil)
        self.cleanUpRefeshReceiptBlocks()
        return
    }
    for receipt in receipts_array {
        let productID = receipt["product_id"] as! String 
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
        if let date = formatter.date(from: receipt["expires_date"] as! String) {
            if date > Date() {
                // do not save expired date to user defaults to avoid overwriting with expired date
                UserDefaults.standard.set(date, forKey: productID)
            }
        }
    }
    self.refreshSubscriptionSuccessBlock?()
    self.cleanUpRefeshReceiptBlocks()
}

We loop through array looking for expires_date key and save it if is not expired yet. It’s a simple example which considered to be for learning purposes. It doesn’t handle errors or several cases, for example, canceling (refunding) a subscription.

In order to check if subscription is active or not you should compare current date with subscription’s expiration date:

func expirationDateFor(_ identifier : String) -> Date?{
        return UserDefaults.standard.object(forKey: identifier) as? Date
    }
    
let subscriptionDate = IAPManager.shared.expirationDateFor("YOUR_PRODUCT_ID") ?? Date()
let isActive = subscriptionDate > Date()

Restoring transactions

It’s just one method: SKPaymentQueue.default().restoreCompletedTransactions(). These functions restore transactions so that observer calls updatedTransactions delegate method as many times as many transactions you have.

Popular question is being asked:

Restoring transactions vs. refreshing a receipt. What are the differences?

Well, both methods let you restore purchases information. Here’s a good screenshot from this WWDC video:

Restoring transactions vs. refreshing a receipt
Restoring transactions vs. refreshing a receipt

In most cases you just need to use receipt refreshing. And you don’t really need restoring transactions. In case of auto-renewable subscriptions we send a local receipt to Apple to validate it in order to get subscription’s expiration date. And we don’t actually care about transactions. However, if you use Apple-hosted content in your purchases or target device below iOS 7 you will need to use the first method.

Sandbox testing

To test auto-renewable subscriptions you will need to add sandbox testers first. Subscriptions can be tested only using device. So in ASC go to Users & Access then go to Sandbox Testers. There you will create your first sandbox tester.

Creating a new tester
Creating a new tester

While creating a new tester you, can enter any text. However, don’t forget email and password!

Previously when testing in-app purchases you used to log out from the App Store. This was very annoying: your iTunes music were being removed from device. Now this problem has gone, sandbox test account is separated from real App Store account.

The process of making an in-app purchase is similar to real purchase. But it has some nuances:

  • You will also have to enter sandbox credentials: Apple ID & password. Using device’s Touch ID / Face ID is still not supported.
  • If you entered credentials correctly but system keeps showing the same dialog box, then you should tap on “Cancel”, hide the app, then go back and try again. Seems ridiculous but it works. Sometimes payment process may go on from second attempt.
  • You can’t test subscriptions cancellations.
  • Sandbox subscription durations are much less than real durations. And they renew only 6 times a day. Here’s a table:
Actual durationTest duration
1 week3 minutes
1 month5 minutes
2 months10 minutes
3 months15 minutes
6 months30 minutes
1 year1 hour

What’s new in StoreKit in iOS 13?

Well, the only new thing is SKStorefront, which gives you a country code of user’s App Store account. It may be useful if you need to show different in-app purchases for different countries. Previously, developers had to check iPhone region settings or location to get the country. But now it is made with in one line of code: SKPaymentQueue.default().storefront?.countryCode. There’s also a delegate method which tells you if user’s App Store country has been changed during purchase process. In this case you may continue or cancel the payment process.

Caveats when working with auto-renewable subscriptions

  • Online receipt validation directly from device is not recommended by Apple. It’s being said in this video from WWDC (starting at 5:50) and in documentation. It’s not secure, because your data may be compromised with man-in-the-middle attack. The only right way to validate receipts — using local receipt validation or server-to-server validation.
  • There is a problem related to an expiration date comparing. If you don’t use server-to-server validation, user may change system date to a passed one, and given code will give an unexpected result — expired subscription will become active. To avoid this problem, you should get the world time from any online service.
  • Not every user is eligible for free trial. He may already used it. But many developers don’t handle this case, they just display “Start Free Trial” text on a button. To handle this case, you should validate receipt before showing a purchase screen and check JSON for trial eligibility.
  • If user has canceled his trial via Apple Care (made a refund), then JSON will provide a new cancellation_date key. But an expires_date key will still be there. That means that you should always check for cancellation date first, as it’s primary.
  • You shouldn’t refresh receipt too often. This action sometimes asks for user’s Apple ID password. But we don’t want that — we need everything to be done behind the scenes. You should refresh receipt when showing purchase screen if needed or when user taps on “Restore Purchases” button.
  • How often you should validate a receipt to get the latest subscription info? Probably the good way is to call once during app launch. Or you may do this only when subscription expires. However, don’t forget possible cancellations (refunds). User will be able to use your app for free until the end of billing period.

Conclusion

I hope this article was useful. I tried not only include the code but explain some important caveats. The full class code can be downloaded here. This class will be useful for learning purposes. However, for live apps you should use more complex solutions, such as SwiftyStoreKit.

As being said, Apple doesn’t recommend using online receipt validation directly from your device. And not every step can be easily done without a server. But what if you don’t have a server for your app? Well, you can use our Apphud SDK — a subscription validation, managing and analytics tool.