In App Purchase Programming Guide: Networking & Internet
In App Purchase Programming Guide: Networking & Internet
2011-02-15
Apple Inc. 2011 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. The Apple logo is a trademark of Apple Inc. Use of the keyboard Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Every effort has been made to ensure that the information in this document is accurate. Apple is not responsible for typographical errors. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 App Store is a service mark of Apple Inc. Apple, the Apple logo, iTunes, Sand, and Xcode are trademarks of Apple Inc., registered in the United States and other countries. IOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license. Simultaneously published in the United States and Canada.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE
ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.
Contents
Introduction
Introduction 7
Who Should Read This Document 7 Organization of This Document 7 See Also 8
Chapter 1
Chapter 2
Chapter 3
Making a Purchase 19
Collecting Payments 19 SKPayment 20 SKPaymentQueue 20 SKPaymentTransaction 20 SKPaymentTransactionObserver 20 Restoring Transactions 21
Chapter 4
Chapter 5
3
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CONTENTS
Testing a Store 31
The Sandbox Environment 31 Testing in the Sandbox 31 Validating Receipts in the Sandbox 32
Chapter 7
Auto-renewable Subscriptions 33
Adding Auto-renewable Subscriptions to Your Store 33 Designing your iOS Client Application 33 Verifying an Auto-renewable Subscription Receipt 34 Restoring Auto-Renewable Subscriptions 35
4
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
Chapter 2
Chapter 3
Making a Purchase 19
Figure 3-1 Adding a payment request to the queue 19
Chapter 5
Chapter 7
Auto-renewable Subscriptions 33
Table 7-1 Table 7-2 Status codes for auto-renewable subscriptions 34 Auto-renewable subscription info keys 35
5
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
6
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
In App Purchase allows you to embed a store directly within your application. You implement In App Purchase in your iOS application using the Store Kit framework. Store Kit connects to the App Store on your application's behalf to securely process payments from the user. Store Kit prompts the user to authorize the payment, then notifies your application so that it can provide items the user purchased. You can use this in-application payment functionality to collect payment for enhanced functionality or additional content usable by your application. For example, you could use In App Purchase to implement any of the following scenarios:
A basic version of your application with additional premium features. A book reader application that allows the user to purchase and download new books. A game that offers new environments (levels) to explore. An online game that allows the player to purchase virtual property.
Important: In App Purchase only collects payment. You must provide any additional functionality, including unlocking built-in features or downloading content from your own servers. This documentation details the technical requirements of adding a store to your application. For more information on the business requirements of using In App Purchase, see the App Store Resource Center. You must also read your licensing agreement for the definitive treatment of what you may sell and how you are required to provide those products in your application.
Overview of In App Purchase (page 9) introduces the functionality offered by In App Purchase. Retrieving Product Information (page 15) describes how your iOS application retrieves information from the App Store about products it offers. Making a Purchase (page 19) explains how your application requests payment from the App Store. Adding a Store to Your Application (page 23) is a walkthrough that describes how to add a store to your application.
INTRODUCTION
Introduction
Verifying Store Receipts (page 27) describes how your server can verify that a receipt came from the App Store. Testing a Store (page 31) discusses how to use the sandbox environment to test your iOS application. Auto-renewable Subscriptions (page 33) describes how your application can implement subscriptions using the Apple Store to manage the renewal process for you.
See Also
The App Store Resource Center describes the business side of using In App Purchase, as well as the steps you need to take to sell a product within your application. The iTunes Connect Developer Guide describes how to configure products and test accounts on the App Store. The Store Kit Framework Reference describes the API for interacting with the App Store.
See Also
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Store Kit communicates with the App Store on behalf of your application. Your application uses Store Kit to receive localized information from the App Store about products you want to offer in your application. Your application displays this information to users and allows them to purchase items. When a user wants to purchase an item, your app calls Store Kit to collect payment from the user. Figure 1-1 shows the basic store model. Figure 1-1 In App Store model
App Store
iOS Device
My App
Store Kit
Request Response
The Store Kit API is only a small part of the process of adding a store to your application. You need to decide how to track the products you plan to deliver, how your application presents a store front to the user, and how your application delivers the products users purchase from your store. The rest of this chapter explains the process of creating products and adding a store to your application.
Products
A product is any feature that you want to sell in your applications store. Products are associated with the App Store through iTunes Connect in the same way that you create new applications. There are four supported kinds of products that you may sell using In App Purchase:
Content includes digital books, magazines, photos, artwork, game levels, game characters, and other digital content that can be delivered within your application. Functionality products unlock or expand features youve already delivered in your application. For example, you could ship a game with multiple smaller games that could be purchased by the user. Services allow your application to charge users for one-time services, such as voice transcription. Each time the service is used is a separate purchase.
Products
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Subscriptions provide access to content or services on an extended basis. For example, your application might offer monthly access to financial information or to an online game portal.
In App Purchase provides a general mechanism for creating products, leaving the specifics of how your products are implemented up to you. However, there are few important guidelines to keep in mind as you design your application:
You must deliver a digital good or service within your application. Do not use In App Purchase to sell real-world goods and services. You may not offer items that represent intermediary currency because it is important that users know the specific good or service they are buying. Items you offer for purchase may not contain, or relate to, pornography, hate speech, defamation, or gambling (simulated gambling is acceptable).
For detailed information about what can be offered using In App Purchase, consult your licensing agreement.
Consumable products must be purchased each time the user needs that item. For example, one-time services are commonly implemented as consumable products. Nonconsumable products are purchased only once by a particular user. Once a nonconsumable product is purchased, it is provided to all devices associated with that users iTunes account. Store Kit provides built-in support to restore nonconsumable products on multiple devices. Auto-renewable subscriptions are delivered to all of a users devices in the same way as nonconsumable products. However, auto-renewable subscriptions differ in other ways. When you create an auto-renewable subscription in iTunes Connect, you choose the duration of the subscription. The App Store automatically renews the subscription each time its term expires. If the user chooses to not allow the subscription to be renewed, the users access to the subscription is revoked after the subscription expires. Your application is responsible for validating whether a subscription is currently active and can also receive an updated receipt for the most recent transaction. Subscriptions are an older mechanism for creating products with a limited duration; consider using auto-renewable subscriptions instead. Subscriptions differ from auto-renewable subscriptions in a few key ways:
The term of the subscription is not declared when you create the product in iTunes Connect; your application is responsible for providing this information to the user. In most cases, you would include the term of the subscription in the description of your product.
10
CHAPTER 1
Subscriptions may be purchased multiple times (like a consumable product) and are not automatically renewed. You must implement your own renewal code in your application. Specifically, your application must recognize when the subscription has expired and prompt the user to purchase the product again. You are required to deliver the subscription to all devices owned by the user. Subscriptions are not automatically synchronized to all devices; you must implement this infrastructure yourself. For example, most subscriptions are provided by an external server; your server would need to implement a mechanism to identify users and associate specific subscription purchases with the user who purchased them.
Detailed information about registering products with the App Store can be found in the iTunes Connect Developer Guide.
Feature Delivery
The delivery mechanism your application uses to provide products to users has significant implications on its design and implementation. There are two basic models you should expect to use to deliver products to users: the built-in model and the server model. In both models, you track the list of products offered in the store and deliver products successfully purchased by users.
Feature Delivery
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
11
CHAPTER 1
Figure 1-2
App Store
1
iOS Application The application retrieves the list of product identifiers from its bundle The application sends a request to the App Store to get information on the products The application uses the product information to display a store to the user The user selects an item from the store The application sends a payment request to the App Store The application reads the transaction and delivers the purchased content
The App Store processes the 7 payment and returns a completed transaction
12
Feature Delivery
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Figure 1-3
App Store
1
iOS Application The application sends a request to the server to retrieve a list of product identifiers The application sends a request to the App Store to get information for the products The application uses the product information to display a store to the user
2
The user selects an item from the store The application sends a payment request to the App Store The application retrieves the receipt data from the transaction and sends it to the server
10
The App Store processes the payment and returns a completed transaction
The server records the receipt data to establish an audit trail The server sends the receipt data to the App Store to verify that this is a valid transaction
11
12
The App Store parses the receipt data and returns both the receipt and whether the receipt is valid
13
The server reads the returned receipt data to determine what the user purchased The server delivers the purchased content to the application
14
Apple recommends you retrieve product identifiers from your server, rather than including them in a property list. This gives you the flexibility to add new products without updating your application. In the server model, your application retrieves the signed receipt associated with a transaction and sends it to your server. Your server can then validate the receipt and decode it to determine which content to deliver to your application. This process is covered in detail in Verifying Store Receipts (page 27).
Feature Delivery
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
13
CHAPTER 1
The server model has additional security and reliability concerns. You should test the entire environment for security threats. Secure Coding Guide provides additional recommendations. Although nonconsumable products may be recovered using the built-in capabilities of Store Kit, subscriptions must be restored by your server. You are responsible for recording information about subscriptions and restoring them to users. Optionally, consumable products could also be tracked by your server. For example, if your consumable product is a service provided by your server, you may want the user to retrieve the results of that request on multiple devices.
14
Feature Delivery
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 2
When your application is ready to display a store to the user, it must populate its user interface with information from the App Store. This chapter details how to request product details from the App Store.
SKRequestDelegate
If your application quits while a request is pending, your application needs to resend it.
SKRequest
SKRequest is an abstract base class for requests sent to the store.
SKRequestDelegate
SKRequestDelegate is a protocol that your application implements to handle requests that completed
15
CHAPTER 2
SKProductsRequestDelegate
SKProductsResponse SKProduct Name: Expansion Pack Description: New levels to explore! Price: $0.99
Important: You must make a product request for a particular product identifier before allowing the user to purchase that product. Retrieving product information from the App Store ensures that you are using a valid product identifier for a product you have marked available for sale in iTunes Connect.
SKProductsRequest
An SKProductsRequest object is created with a list of product identifier strings for the products you want to display in your store.
SKProductsRequestDelegate
The SKProductsRequestDelegate protocol is implemented by an object in your application to receive the response from the store. It receives the response asynchronously when the request is successfully processed.
16
CHAPTER 2
SKProductsResponse
An SKProductsResponse object contains a SKProduct object for each valid product identifier in the original request as well as a list of the product identifiers that were not recognized by the store. The store might not recognize the identifier for a number of reasons; it might be misspelled, marked unavailable for sale, or changes you have made in iTunes Connect have not propagated to all of the App Store servers.
SKProduct
An SKProduct object provides localized information about a product youve registered with the App Store.
17
CHAPTER 2
18
CHAPTER 3
Making a Purchase
When the user is ready to purchase an item, your application asks the App Store to collect payment. When your application asks for payment, the App Store creates a persistent transaction and continues to process the payment, even if the user quits and relaunches your application. The App Store synchronizes the list of pending transactions with your application and delivers updates to your application when the status of any of these transactions changes.
Collecting Payments
To collect payment, your application creates a payment object and queues it on the payment queue, as shown in Figure 3-1. Figure 3-1 Adding a payment request to the queue
Application
1
Store Kit
2
SKPayment
SKPaymentQueue
3 4
paymentQueue:updatedTransactions: SKPaymentTransactionObserver Examine all completed purchases and deliver purchased items
finishTransaction:
Collecting Payments
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
19
CHAPTER 3
Making a Purchase
When the payment is added to the payment queue, a persistent transaction is created to hold it. After the payment is processed, the transaction is updated with information about the payment collection. Your application implements an observer that receives messages when transactions are updated. The observer should provide purchased items to the user and then remove the transaction from the payment queue.
SKPayment
Collecting payment starts with a payment object. The payment object includes a product identifier and optionally includes the quantity of that product to be purchased. You can queue the same payment object more than once; each time a payment object is queued results in a separate request for payment. Users can disable the ability to make purchases in the Settings application. Before attempting to queue a purchase, your application should first confirm that payment can be processed. You do this by calling the payment queues canMakePayments method.
SKPaymentQueue
The payment queue is used to communicate with the App Store. When payments are added to the queue, Store Kit transmits the request to the App Store. Store Kit presents dialogs to ask the user to authorize payment. The completed transaction is returned to your applications observer.
SKPaymentTransaction
A transaction is created for every payment added to the queue. Each transaction has properties that allow your application to determine the status of the transaction. When payment is collected, the transaction includes additional details about the successful transaction. Although your application can ask the payment queue for a list of pending transactions, it is more common for an application to wait until the payment queue notifies the payment queues observer with a list of updated transactions.
SKPaymentTransactionObserver
Your application implements the SKPaymentTransactionObserver protocol on an object and adds it as an observer to the payment queue. The observers primary responsibility is to examine completed transactions, deliver items that were successfully purchased, and remove those transactions from the payment queue. Your application should associate an observer with the payment queue when it launches, rather than wait until the user attempts to purchase an item. Transactions are not lost when an application terminates. The next time the application launches, Store Kit resumes processing transactions. Adding the observer during your applications initialization ensures that all transactions are returned to your application.
20
Collecting Payments
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Making a Purchase
Restoring Transactions
Once a transaction has been processed and removed from the queue, your application normally never sees it again. If your application supports nonconsumable or subscription products, it must provide the ability for users to restore these purchases on additional devices. Store Kit provides built-in functionality to restore transactions for nonconsumable products. To restore transactions, your application calls the payment queues restoreCompletedTransactions method. For each nonconsumable and renewable subscription product that was previously completed, the App Store generates a new restore transaction. The restore transaction includes a copy of the original transaction. Your application processes restore transactions by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method. If the user attempts to purchase a nonconsumable product or a renewable subscription they have already purchased, your application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Subscriptions and consumable products are not automatically restored by Store Kit. To restore these products, you must record the transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the users devices.
Restoring Transactions
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
21
CHAPTER 3
Making a Purchase
22
Restoring Transactions
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
This chapter provides guided steps for adding a store to your application.
4.
23
CHAPTER 4
Your application creates an SKProductsRequest object and initializes it with a set of product identifiers for the items you wish to sell, attaches a delegate to the request, and then starts it. The response holds the localized product information for all valid product identifiers. Your application cannot create a payment request unless you have first retrieved the product information for that product.
- (void) requestProductData { SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers: [NSSet setWithObject: kMyFeatureIdentifier]]; request.delegate = self; [request start]; } - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { NSArray *myProduct = response.products; // populate UI [request autorelease]; }
5.
Add a user interface that displays products to the user. Store Kit does not provide user interface classes. The look and feel of how you offer products to your customers is up to you!
6.
Register a transaction observer with the payment queue. Your application should instantiate a transaction observer and add it as an observer of the payment queue.
MyStoreObserver *observer = [[MyStoreObserver alloc] init]; [[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
Your application should add the observer when your application launches. The App Store remembers queued transactions even if your application exited before completing all transactions. Adding an observer during initialization ensures that all previously queued transactions are seen by your application. 7. Implement the paymentQueue:updatedTransactions: method on MyStoreObserver. The observers paymentQueue:updatedTransactions: method is called whenever new transactions are created or updated.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions { for (SKPaymentTransaction *transaction in transactions) { switch (transaction.transactionState) { case SKPaymentTransactionStatePurchased: [self completeTransaction:transaction]; break; case SKPaymentTransactionStateFailed: [self failedTransaction:transaction]; break; case SKPaymentTransactionStateRestored: [self restoreTransaction:transaction]; default:
24
CHAPTER 4
break; } } }
8.
Your observer provides the product when the user successfully purchases an item.
- (void) completeTransaction: (SKPaymentTransaction *)transaction { // Your application should implement these two methods. [self recordTransaction: transaction]; [self provideContent: transaction.payment.productIdentifier]; // Remove the transaction from the payment queue. [[SKPaymentQueue defaultQueue] finishTransaction: transaction]; }
A successful transaction includes a transactionIdentifier property and a transactionReceipt property that record the details of the processed payment. Your application is not required to do anything with this information. You may wish to record this information to establish an audit trail for the transaction. If your application uses a server to deliver content, the receipt can be sent to your server and validated by the App Store. It is critical that your application take whatever steps are necessary to provide the product that the user purchased. Payment has already been collected, so the user expects to receive the new purchase. See Feature Delivery (page 11) for suggestions on how you might implement this. Once youve delivered the product, your application must call finishTransaction: to complete the transaction. When you call finishTransaction:, the transaction is removed from the payment queue. To ensure that products are not lost, your application should deliver the product before calling finishTransaction:. 9. Finish the transaction for a restored purchase.
- (void) restoreTransaction: (SKPaymentTransaction *)transaction { [self recordTransaction: transaction]; [self provideContent: transaction.originalTransaction.payment.productIdentifier]; [[SKPaymentQueue defaultQueue] finishTransaction: transaction]; }
This routine is similar to that for a purchased item. A restored purchase provides a new transaction, including a different transaction identifier and receipt. You can save this information separately as part of any audit trail if you desire. However, when it comes time to complete the transaction, youll want to recover the original transaction that holds the actual payment object and use its product identifier. 10. Finish the transaction for a failed purchase.
- (void) failedTransaction: (SKPaymentTransaction *)transaction { if (transaction.error.code != SKErrorPaymentCancelled) { // Optionally, display an error here. } [[SKPaymentQueue defaultQueue] finishTransaction: transaction]; }
25
CHAPTER 4
Usually a transaction fails because the user decided not to purchase the item. Your application can read the error field on a failed transaction to learn exactly why the transaction failed. The only requirement for a failed purchase is that your application remove it from the queue. If your application chooses to put up an dialog displaying the error to the user, you should avoid presenting an error when the user cancels a purchase. 11. With all the infrastructure in place, you can finish the user interface. When the user selects an item in the store, create a payment object and add it to the payment queue.
SKPayment *payment = [SKPayment paymentWithProductIdentifier:kMyFeatureIdentifier]; [[SKPaymentQueue defaultQueue] addPayment:payment];
If your store offers the ability to purchase more than one of a product, you can create a single payment and set the quantity property.
SKMutablePayment *payment = [SKMutablePayment paymentWithProductIdentifier:kMyFeatureIdentifier]; payment.quantity = 3; [[SKPaymentQueue defaultQueue] addPayment:payment];
Where to Go Next
The code provided in these steps is best used for the built-in product model. If your application uses a server to deliver content, you are responsible for designing and implementing the protocols used to communicate between your iOS application and your server. Your server should also verify receipts before delivering products to your application.
26
Where to Go Next
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Your application should perform the additional step of verifying that the receipt you received from Store Kit came from Apple. This is particularly important when your application relies on a separate server to provide subscriptions, services, or downloadable content. Verifying receipts on your server ensures that requests from your iOS application are valid. Important: The contents and format of the store receipt is private and subject to change. Your application should not attempt to parse the receipt data directly. Use the mechanism described here to validate the receipt and retrieve the information stored inside it.
2.
3.
Post the JSON object to the App Store using an HTTP POST request. The URL for the store is https://buy.itunes.apple.com/verifyReceipt. The response received from the App Store is a JSON object with two keys, status and receipt. It should look something like this:
{ "status" : 0, "receipt" : { ... } }
4.
If the value of the status key is 0, this is a valid receipt. If the value is anything other than 0, this receipt is invalid.
27
CHAPTER 5
Purchase info keys Description The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transactions payment property. The product identifier of the item that was purchased. This value corresponds to the productIdentifier property of the SKPayment object stored in the transactions payment property. The transaction identifier of the item that was purchased. This value corresponds to the transactions transactionIdentifier property. The date and time this transaction occurred. This value corresponds to the transactions transactionDate property. For a transaction that restores a previous transaction, this holds the original transaction identifier. For a transaction that restores a previous transaction, this holds the original purchase date. A string that the App Store uses to uniquely identify the iOS application that created the payment transaction. If your server supports multiple iOS applications, you can use this value to differentiate between them. Applications that are executing in the sandbox do not yet have an app-item-id assigned to them, so this key is missing from receipts created by the sandbox. An arbitrary number that uniquely identifies a revision of your application. This key is missing in receipts created by the sandbox. The bundle identifier for the iOS application.
product_id
transaction_id
purchase_date
version_external_identifier bid
28
CHAPTER 5
Key
bvrs
29
CHAPTER 5
30
CHAPTER 6
Testing a Store
During development, you should test your application to ensure that purchases are working correctly. However, you do not want to charge users while testing your application. Apple provides a sandbox environment to allow you to test your application without creating financial transactions. Note: Store Kit does not operate in iOS Simulator. When running your application in iOS Simulator, Store Kit logs a warning if your application attempts to retrieve the payment queue. Testing the store must be done on actual devices.
31
CHAPTER 6
Testing a Store
32
CHAPTER 7
Auto-renewable Subscriptions
In App Purchase provides a standardized way to implement auto-renewable subscriptions. Auto-renewable subscriptions have a few notable characteristics:
When you configure an auto-renewable subscription in iTunes Connect, you also configure the duration for the subscription. Auto-renewable subscriptions are restored automatically using the same Store Kit functions used to restore nonconsumable products. The original purchase transaction as well as the transactions for each renewal are sent to your application. See Restoring Transactions (page 21). When your server verifies a receipt with the App Store and the subscription is both active and has been renewed by the App Store, the App Store sends your application an updated receipt.
Connect to iTunes Connect and use it to create a shared secret. A shared secret is password that your server must provide when validating receipts for auto-renewable subscriptions. This shared secret provides an additional layer of security to your transactions with the store. See iTunes Connect Developer Guide. Configure new products in iTunes Connect with the new auto-renewable subscription type. Modify your servers receipt verification code so that it sends the shared secret to the App Store. Your code must parse the response to determine whether the subscription has expired; if it has not expired, it should also retrieve the most recent receipt data and use it update your servers records.
33
CHAPTER 7
Auto-renewable Subscriptions
The response, as before, includes whether the request was successfully validated, and the decoded receipt data:
{ "status" : 0, "receipt" : { ... } "latest-receipt" : "(base-64 encoded receipt)" }
If the users receipt was valid and the subscription is active, the status field holds 0, and the receipt fields are populated appropriately. If your server receives a non-zero status value, use Table 7-1 (page 34) to interpret the results. Table 7-1 Status codes for auto-renewable subscriptions
Status Code Description 21000 21002 21003 21004 21005 21006 The App Store could not read the JSON object you provided. The data in the receipt-data property was malformed. The receipt could not be authenticated. The shared secret you provided does not match the shared secret on file for your account. The receipt server is not currently available. This receipt is valid but the subscription has expired.
Important: The non-zero status codes here apply only when recovering information about a auto-renewable subscription. Do not use these status codes when testing responses for other kinds of products. The receipt field on the JSON object holds the parsed information from the receipt. The receipt data for an auto-renewable subscription includes one additional key, and some other key previously described in Table 5-1 (page 28) are modified slightly for subscriptions. See Table 7-2 for details on the new and modified keys.
34
CHAPTER 7
Auto-renewable Subscriptions
Auto-renewable subscription info keys Description The expiration date of the subscription receipt, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is not included on restored transactions. This holds the transaction identifier for the initial purchase. All subsequent renewals of this subscription and recovered transactions all share this identifier. This holds the purchase date for the initial purchase; it represents the start date for the subscription. This holds the billing date when this transaction occurred. For a transaction for a renewable subscription, this would be the date when the subscription was renewed. If the receipt being parsed by the App Store was the latest receipt for this subscription, this field holds the date when this subscription was most recently renewed.
expires_date
The response also includes an additional latest-receipt field; if the users subscription is active and was renewed in a transaction that took place after the transaction you provided to the App Store, the latest-receipt field includes a new base-64 encoded receipt for the latest renewal for this subscription. Your server can use this new receipt to maintain a record of the most recent renewal.
35
CHAPTER 7
Auto-renewable Subscriptions
36
REVISION HISTORY
This table describes the changes to In App Purchase Programming Guide. Date 2011-02-15 Notes Apps must always retrieve product information before submitting a purchase; this ensures that the item has been marked for sale. Information added about renewable subscriptions. Minor edits. Minor clarifications to SKRequest. Fixed a typo in the JSON receipt object. Receipt data must be base64 encoded before being passed to the validation server. Other minor updates. Revised introductory chapter. Clarified usage of receipt data. Recommended the iTunes Connect Developer Guide as the primary source of information about creating product metadata. Renamed from "Store Kit Programming Guide" to "In App Purchase Programming Guide". Revised to include discussion on retrieving price information from the Apple App Store as well as validating receipts with the store. New document that describes how to use the StoreKit API to implement a store with your application.
2009-09-09
2009-06-12
2009-03-13
37
2011-02-15 | 2011 Apple Inc. All Rights Reserved.
REVISION HISTORY
38
2011-02-15 | 2011 Apple Inc. All Rights Reserved.