IAP (In-app Purchase) Chinese documents

Source: Internet
Author: User
Tags http post

Content transferred from: http://yarin.blog.51cto.com/1130898/549141

One, in App purchase overview

The store kit represents the communication between the app and the App Store. The program will receive information from the App store about the products you want to provide and display them for purchase.
When a user needs to purchase a product, the program calls Storekit to collect the purchase information. This is the basic store kit model:

The Store Kit API just adds a small part of the app purchase feature to the program. You need to decide how to record the products you want to submit, how to show the store functionality to the user in the program,
Also consider how to submit a product purchased by a user. The remainder of this chapter will show the entire process.

Products
A product can be any feature you want to sell. The product is organized in itunes Connect, which is the same as adding a new app to you. There are four types of products supported:
1. Content type. Includes ebooks, e-magazines, photos, illustrations, game levels, game characters, and other digital content.
2. Extended functionality. These features are already included inside the app. is locked before it is purchased. For example, you can include several mini-games in a game program that users can purchase separately.
3. Service. Allows the program to charge for a single service. such as recording services.
4. Subscribe. Supports extended access to content or services. For example, your program can provide financial information or game portal information on a weekly basis. A reasonable update cycle should be set to avoid too frequent
Prompt bothers the user. Remember: You will be responsible for tracking expiration information for your subscription and managing renewals. The APP store does not monitor the subscription cycle for you, nor does it provide a mechanism for automatic charging.

In APP purchase provides a common mechanism for creating products that you will be responsible for. When you design the program, there are several points to note:

1. You must provide electronic products and services. Do not use the in App Purchase to sell physical and real services.
2. It is not possible to provide items that represent the intermediary currency because it is important for users to be aware of the goods and services they purchase.

2. Server type
With this end-use method, you provide additional servers to send the product to the program. Server delivery is available for subscriptions, content classes of goods and services, as goods can be sent as data without the need to change the program bundle. For example, a game provides new content (levels, etc.). The Store kit does not define the server-side design and interaction, which you need to complete. Also, the Store kit does not provide a mechanism for verifying the user's identity, which you need to design. If your program requires the above features, for example, to record a specific user's subscription plan, you need to design and implement it yourself.

Figure 1-3 shows the purchase process for the server type.

1. The program sends a request to the server to obtain a list of products.
2. The server returns a list containing the product identifiers.
3. The program sends a request to the App Store to get information about the product.
4. The APP store returns product information.
5. The program displays the returned product information to the user (app's store interface)
6. The user selects a product
7. Program sends payment request to App Store
8. The APP store processes payment requests and returns transaction completion information.
9. The program obtains data from the information and sends it to the server.
10. The server records the data, and carries on the examination (our) checks.
11. The server sends the data to the App Store to verify the validity of the transaction.
The APP store parses the received data and returns the data and identifies whether it is valid.
13. The server reads the returned data to determine what the user has purchased.
14. The server passes the purchased content to the program.

Apple recommends that you store product identities on the server side rather than storing them in plist. This allows you to add new products without upgrading the program.

In server mode, your program will get information about the transaction (transaction) and send it to the server. The server can validate the received data and decode it to determine what needs to be delivered. This process will be discussed in the "Verifying Store Receipts" section.

For server mode, we have security and reliability concerns. You should test the entire environment to avoid threats. Instructions are available in the Secure Coding Guide documentation.

Although non-expendable products can be restored with built-in mode, the subscription commodity must be restored through the server. You are responsible for recording subscription information and recovering data.
Consumption of goods can also be recorded by the server way. For example, a service provided by a server, you may require users to regain results on multiple devices.
(This translation is more blunt, because I personally do not have the opportunity to run all types of services, follow-up will be checked and modified.) I hope you will come and see, Welcome to Add. )


Get product Information

To display the "store" inside the program, you need to get information from the App store to purchase the interface. This chapter explains in detail how to get product information from the App Store.

Send a request to the App Store

Store Kit provides a common mechanism for requesting data from the App Store. The program can create and initialize a request object, attach a delegate to it, and then start the process. The request will be sent to the app Store, where it is processed. When processing is complete, the delegate method of the request object is called asynchronously to obtain the requested result. Figure 2-1 shows the data model of the request.

If the program exits during the request, the request needs to be resent.

The classes used in the request process are explained below:

Skrequest
Skrequest is the abstract root class for request.

Skrequestdelegate
Skrequestdelegate is a protocol that implements the method used to process the request result, such as a successful request or a request failure.

Send a request for product information
The program uses the products request to obtain information about the product. To complete this process, the program needs to create a request object that contains a list of product identities. As mentioned before, your program can have both a built-in product list and an external server.

When the request is sent, the product ID is routed to the APP Store,app store and will return the localized information (which has already been set up in itunes Connect) and you will use this information to purchase the built-in store interface (display product name, description, etc.). Figure 2-2 shows the process of the request.

Skproductsrequest
Information used to request a product. When created, we will need to display a list of items to join the object.

Skproductsrequestdelegate
The protocol defines the method for handling the App Store response.

Skproductsresponse
The Skproductsresponse object returns the response information for the App Store. It contains two listings (of course, Nsarray): One is a validated product,
@property (nonatomic, readonly) Nsarray *products
The other is a product information that cannot be identified:
@property (nonatomic, readonly) Nsarray * invalidproductidentifiers
There are several reasons why a product identifier cannot be identified, such as a misspelling (of course), is marked as not sold (unavailable for sale), or changes to the product information are not transmitted to all the App Store servers. (The reason is not very clear, again).

Skproduct
The Skproduct object contains localized information for items registered on the App Store.


Buy items
When a user is ready to purchase a product, the program requests payment information from the App Store, and the App Store will create the persisted transaction information and continue to process the payment process, even if the user restarts the program. The APP store synchronizes the list of pending transactions into the program and sends updated data to the program when the transaction status changes.

Collect payment Information

To collect payment information, your program can create a payment object and put it in the payment queue, as shown in 3-1.

1. A Skpayment object, containing the "Sword" product identification, and the establishment of a purchase quantity of 1.
2. Use the Addpayment: method to add the Skpayment object to the Skpaymentqueue.
3. Skpaymentmentqueue contains all the requested goods,
4. Use Skpaymenttransactionobserver's paymentqueue:updatedtransactions: method to detect all completed purchases and send the purchased items.
5. Finally, use the Finishtransaction: method to complete the transaction.

When an payment object is added to the payment queue, a persisted transaction object is created to hold it. When the payment is processed, the transaction is updated. An observer (Observer) object will be implemented in the program to obtain the transaction update message. The viewer should provide the user with the purchased goods and then remove the transaction from the queue.

Here are a few of the classes that are used during the purchase process:
Skpayment
To collect payment information, you need to know the payment object first. The payment object contains the product's identification (identifier) and the number of items to be purchased (quantity) (quantity optional). You can put the same payment object into the payment queue repeatedly, each time such action is equivalent to a separate payment request.

The user can disable the purchased feature in the settings program. Therefore, before requesting payment, the program should first check whether the payment can be processed. Call Skpaymentqueue's Canmakepayments method to check.

Skpaymentqueue
The payment queue is used to communicate with the App Store. When a new payment object is added to the queue, the store kit sends a request to the App Store. The Store kit will pop up a dialog asking if the user is sure of the purchase. The completed transaction will be returned to the program's Observer object.

Skpaymenttransaction
The transaction object is created each time a new payment is added to the queue. The transaction object contains properties that allow the program to determine the current trading state.

The program can get a list of transactions from the payment queue, but the more common practice is to wait for the payment queue to inform the transaction status updates.

Skpaymenttransactionobserver
Implement the Skpaymenttransactionobserver protocol in the program, and then use it as the observer for the Skpaymentqueue object. The main duties of the observer are to check the completed transaction, deliver the purchased content, and remove the completed transaction object from the queue.

At the start of the program, you should specify the corresponding observer object for the payment queue, rather than wait until the user wants to buy the item. The transaction object is not lost when the program exits. When the program restarts, the Store kit continues to execute the unfinished transaction. When the program is initialized to add the Observer object, you can ensure that all transactions are received by the program (also said, if there is an unfinished transaction, if the program restarts, restart, if you add observers later, you may miss some of the transaction information).


Resuming trading information (transactions)
When transaction is processed and removed from the queue, the program will no longer be visible to them under normal circumstances. If your program provides non-expendable or subscription-like items, you must provide restore functionality that allows users to re-store the purchase information on other devices.

Store Kit provides built-in functionality to re-store trading information for non-consumable items. Call Skpaymentqueue's Restorecompletedtransactions method to re-store it. For non-expendable items that have been previously completed, the Apple store generates new, transaction information for recovery. It contains the original trading information. Your program can get this information and then continue to unlock the purchased feature. When all previous transactions have been restored, the paymentqueuerestorecompletedtransactionsfinished method of the Observer object is invoked.

If a user tries to purchase a non-expendable item that has already been purchased, the program receives a regular trading message instead of resuming the transaction information. However, users will not be charged again. The procedure should treat such transactions as equal to the original transaction.

Subscription-type services and consumable items are not automatically restored by the store kit. To recover these items, you must record the transaction information on your own server when the user buys these items, and provide a mechanism for the user's device to recover the transaction information.


Add a store feature to your program
This chapter provides instructions for adding a purchase function

Detailed process:

The preparation is, of course, adding storekit.framework.
Then there are the specific steps:

1. Determine the type of goods to be sold within the program.
As mentioned before, there are restrictions on the types of new feature that can be sold within the program. Store Kit does not allow us to download new code. Your product can either work through the current code (bundle type), or it can be downloaded from the server (of course, the data file is downloaded here, the code is not possible). If you want to modify the source code, you can only be honest upgrade.

2. Register your product with itunes Connect
This step is required every time a new item is added. Each product requires a unique product identifier. The APP store uses this logo to find product information and process the payment process. The method of registering the product identification is similar to the method of registering the procedure.

To learn how to create and register your product information, refer to the ITunes Connect Developer Guide documentation.

3. Check if payment can be made
Users can disable the ability to pay within the program. Before sending a payment request, the program should check whether the feature is turned on. The program can check the settings before displaying the store interface (it doesn't show the store interface if it's not enabled), or it can be checked before the user sends a payment request so that the user can see a list of items that can be purchased.

Example:

    1. if ([Skpaymentqueue canmakepayments])
    2. {
    3. ... //display a store to the user
    4. }
    5. Else
    6. {
    7. ...  //warn the user that purchases is disabled.
    8. }

4. Access to product information
The program creates the Skproductsrequest object, initializes it with the identity of the item you want to sell, and then attaches the corresponding delegate object. The response to the request contains localized information for the available products.

  1. Send request here
  2. -(void) Requestproductdata
  3. {
  4. Skproductsrequest *request = [[Skproductsrequest alloc]initwithproductidentifiers:
  5. [Nsset Setwithobject:kmyfeatureidentifier]];
  6. Request.delegate = self;
  7. [Request start];
  8. }
  9. This is the delegate method of response.
  10. -(void) Productsrequest: (skproductsrequest *) Request
  11. Didreceiveresponse: (Skproductsresponse *) response
  12. {
  13. Nsarray *myproduct = response.products;
  14. //Generate store's UI
  15. [Request Autorelease];
  16. }

5. Add an interface to display the product
The Store kit does not provide a class for the interface. This interface needs to be designed and implemented by ourselves.

6. Register an observer object for the payment queue (Payment queue)
Your program needs to initialize a transaction observer object and designate it as the observer for the payment queue.

On the code:

    1. Mystoreobserver *observer = [[Mystoreobserver alloc]init];
    2. [[Skpaymentqueue Defaultqueue]addtransactionobserver:observer];

The viewer should be added at the start of the program, as mentioned earlier, after restarting the program will continue the last outstanding transaction, then add the Observer object will not miss the previous transaction information.

7. Execute the Paymentqueue:updatedtransactions: method in the Mystoreobserver class.
This method is called when a new transaction is created, or when the transaction is updated.

  1. -(void) Paymentqueue: (Skpaymentqueue *) queue updatedtransactions: (Nsarray *) Transactions
  2. {
  3. For (skpaymenttransaction * Transaction in transactions)
  4. {
  5. switch (transaction.transactionstate)
  6. {
  7. Case skpaymenttransactionstatepurchased:
  8. [Self completetransaction:transaction];
  9. Break ;
  10. Case skpaymenttransactionstatefailed:
  11. [Self failedtransaction:transaction];
  12. Break ;
  13. Case skpaymenttransactionstaterestored:
  14. [Self restoretransaction:transaction];
  15. Default:
  16. Break ;
  17. }
  18. }
  19. }

The function above calls the corresponding handler function for the different return states of the transaction.

8. The viewer object provides the appropriate content when the user successfully buys a product, the following is the method to be called after the successful transaction

    1. -(void) Completetransaction: (skpaymenttransaction *) transaction
    2. {
    3. //Your program needs to implement both of these methods
    4. [Self recordtransaction:transaction];
    5. [Self provideContent:transaction.payment.productIdentifier];
    6. //Move the completed transaction information out of the queue
    7. [[Skpaymentqueue defaultqueue]finishtransaction:transaction];
    8. }

The transaction success information contains the attributes of Transactionidentifier and Transactionreceipt. where Transactionreceipt records details of payment, this information can help you track, audit (our) transactions, if your program is to use the server to deliver content, Transactionreceipt can be transferred to the server, and then through the app Store verification transactions. (previously mentioned in the server mode, you can refer to the previous diagram)

9. If the transaction is restored (restore), we use this method to process:

    1. -(void) Restoretransaction: (skpaymenttransaction *) transaction
    2. {
    3. [Self recordtransaction:transaction];
    4. [Self provideContent:transaction.payment.productIdentifier];
    5. [[Skpaymentqueue Defaultqueue] finishtransaction:transaction];
    6. }

This process is similar to completing the purchase process. The restored purchase provides a new transaction information that contains the new transaction identification and receipt data. If necessary, you can save this information separately for retrospective examination (our). But more of the case, when the transaction is complete, you may need to overwrite the original transaction data and use the product logo in it.

10. If the trading process fails, we call the following method:

    1. -(void) Failedtransaction: (skpaymenttransaction *) transaction
    2. {
    3. if (transaction.error.code! = skerrorpaymentcancelled)
    4. {
    5. //In this class displays error messages other than user cancellation
    6. }
    7. [[Skpaymentqueue Defaultqueue] finishtransaction:transaction];
    8. }

Typically, the reason for a transaction failure is the process of canceling the purchase of a product. The program can read the details of the transaction failure from the error.

It is not necessary to display the error message, but in the above process, the failed transaction needs to be removed from the payment queue. In general, we use a dialog box to display the error message, so you should avoid having the user cancel the purchase error displayed.

11. Organize the UI of the "store" within the program. When the user selects a product, a payment object is created and placed in the queue.

    1. Skpayment *payment = [Skpayment paymentwithproductidentifier:kmyfeatureidentifier];
    2. [[Skpaymentqueue Defaultqueue] addpayment:payment];

If your store supports the selection of the same item quantity, you can set the Quantity property of the Payment object

    1. Skmutablepayment *payment = [Skmutablepayment paymentwithproductidentifier:kmyfeatureidentifier];
    2. payment.quantity = 3;
    3. [[Skpaymentqueue Defaultqueue] addpayment:payment];

Next:
The code shown in this chapter can be used for built-in commodity mode (built-in). If your program wants to use a server to publish goods, you need to be responsible for designing and executing the communication between the iphone program and your server. The server should validate the data and provide the content for the program.

Verify receipt for Store

Using the server to deliver the content, we also need to do some extra work to verify receipt information sent from the store kit.

Important information: The format of receipt information from the store is private. Your program should not parse this type of data directly. You can use the following mechanisms to extract information from them.

Verify receipt information returned by the App Store
When the transaction is complete, the Store kit INFORMS payment observer the message and returns the completed transaction. The Transactionreceipt attribute of Skpaymenttransaction contains a signed receipt information that records the key information of the transaction. Your server is responsible for submitting the receipt information to determine its validity and to ensure that it has not been tampered with. In this process, the information is sent to the App Store,app Store in JSON format, which also returns data as JSON.
(You can get a look at the JSON format first)

Process for verifying receipts:

1. Obtain the receipt data from the Transactionreceipt attribute of the transaction and encode it in base64 manner.
2. Create a JSON object, a dictionary format, a single-key-value pair, the key named "Receipt-data", and the value is the data after the previous step of encoding. The effect is:

    1. {
    2. "Receipt-data": "(encoded data)"
    3. }

3. Send an HTTP POST request to send the data to the app Store with the address:
Https://buy.itunes.apple.com/verfyReceipt

4. The return value of the APP store is also a JSON-formatted object that contains two key-value pairs, status, and receipt:

    1. {
    2. "status": 0,
    3. "Receipt": {...}
    4. }

If the value of status is 0, it indicates that the receipt is valid. Otherwise, it is invalid.

Receipt for APP Store
The receipt data sent to the App Store is created by encoding the corresponding information in the transaction. When the App store validates the receipt, it decodes the data from it and returns it with the "receipt" key. The response information returned is in JSON format and is included in the Skpaymenttransaction object (Transactionreceipt property). These values are used by the server to understand the details of the transaction. Apple recommends sending only receipt data to the server and using receipt data to authenticate and obtain transaction details. Because the App Store verifies receipt information, returns information, and ensures that information is not tampered with, it is more secure than submitting receipt and transaction data at the same time. (This section has to be looked at again)

Table 5-1 is all the keys for the transaction information, and many of the keys correspond to the properties of the skpaymenttransaction.
Note: Some keys depend on whether your program is linked to the App store or a sandbox environment for testing. For more information about sandboxes, please see the chapter "Testing a Store".

Table 5-1 key to purchase information:

Key Name Describe
Quantity The number of items purchased. Corresponds to the Quantity property in the Skpayment object
product_id The identification of the commodity, corresponding to the Productidentifier attribute of the Skpayment object.
transaction_id Identification of the trade, corresponding to the Transactionidentifier attribute of the Skpaymenttransaction
Purchase_date The date of the transaction, corresponding to the TransactionDate attribute of the Skpaymenttransaction
original_-transaction_id For the restored transaction object, the key corresponds to the original transaction identity
Original_purchase_-date For the restored transaction object, the key corresponds to the original trading date
app_item_id The string used by the App store to identify the program. A server may need to support multiple server payment functions, which can be used to differentiate programs. The link sandbox is used to test for programs that do not have this value, so the key does not exist.
Version_external_-identifier Used to identify the number of program revisions. The key does not exist in the sandbox environment
Di Bundle Identification for iphone programs
Bvrs Version number of iphone program

Test Store Features
During the development process, we need to test the payment function to ensure that it works properly. However, we do not want to charge users for testing. Apple provides a sandbox environment for us to test.

Note: The Store kit cannot be run on the emulator. When running the store kit on the emulator, accessing the payment queue will cause a warning log to be typed. The test store feature must be on the real machine.

Sandbox environment
In a sandbox environment, the store kit does not link to the real App store, but instead links to a dedicated sandbox environment. The sandbox content is consistent with the App Store, except that it does not perform real payment actions. It returns information about the success of the transaction. The sandbox uses a dedicated itunes connect test account. You cannot use the official itunes Connect account to test.

To test your program, you need to create a dedicated test account. At a minimum, you need to create at least one Test account for each area of the program. For more information, please see the itunes Connect Developer Guide documentation.

Test in a sandbox environment
Steps:
1. Exit the itunes account on the tested iphone
Settings may log in and out of previously logged-in accounts.

Important: You cannot log in through the test account in the settings program.

2. Running the program
When you purchase a product in the App Store, the store kit prompts you to verify the transaction. Log in with your test account and approve the payment. So the virtual deal is done.

Verify receipts in the sandbox
The verified URLs are different:

      1. Nsurl *sandboxstoreurl = [[Nsurl alloc]initwithstring:
      2. @"Https://sandbox.itunes.apple.com/verifyReceipt"];

IAP (In-app Purchase) Chinese documents

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.