IOS: Implementing Apple's in-app purchases

Source: Internet
Author: User

First, Introduction:

After the app was put on the AppStore, Apple officially allowed us to use our app on AppStore, which is called a buy-in. Where payment is required by Apple's payment method: in-app payment.

Second, the process:

1. Background settings

(1) Configure Developer.apple.com to create an app ID without wildcards for your app

(2) Generate and install the corresponding provisioning profile with the app ID

2. Configure itunes Connect

(1) Create a new app with the app ID;

(2) In this application, create in-app paid items, select the payment type, usually optional is a repeatable consumption (consumenable) and permanent effective (non-consumenable) two, and then set the price, Product ID, purchase introduction and, The Product ID here has to be remembered, and it needs to be developed later.

(3) Add a test user to pay in the sandbox, note that Apple's password requirements for the test user are the same as the account, at least 8 bits, and the package contains numbers and uppercase and lowercase letters;

(4) Fill in the relevant tax. Banks and contacts

3. iOS-side development

(1) Introduction of Storekit.framework and #import <storeKit/storeKit.h>; in engineering

(2) Get a list of all paid product IDs. This can be stored in a constant local, or it can be returned by their own server;

(3) Create an interface (such as TableView) to display all in-app paid items. The price and introductory information for these in-app paid items can be returned by your own server. However, if it is a standalone game app or tool application without a server, you can search for it from the App store;

(4) When the user clicks on an IAP item, we need to check whether the user allows in-app billing, and if not, do not proceed to the next step;

(5) First through the IAP ProductID to AppStore query, get skpayment instance, and then through the Skpaymentqueue Addpayment method to initiate a purchase operation;

(6) In the Viewdidload method, the purchase page is set to the purchase amount observe;

(7) When the user buys the operation has the result, will trigger invokes the callback function, the corresponding processing;

(8) Server authentication credentials (optional). If the purchase is successful, we need to send the voucher to the server for verification. Taking into account the network anomalies, the IOS send credential operation should be persistent, if the program exits, crashes or network exceptions, you can resume the retry.

4, the development of the service side

(1) Receive the purchase voucher sent by the iOS side;

(2) Determine whether the voucher already exists, whether it has been verified, and then stored;

(3) Send the voucher to Apple's server for authentication and return the result to the client;

(4) If necessary, modify the user's corresponding member rights.

Note: In the case of network anomalies, the server's authentication should be a recoverable queue, and if it fails, it should be retried.

Verification of purchase voucher on Apple AppStore line address:htpps://buy.itunes.apple.com/verifyreceipt

Verification of the test address:htpps://sandbox.itunes.apple.com/verifyreceipt

Three, iOS basic code is as follows:

//VIEWCONTROLLER.M////Created by Xiahuan on 16/11/20.//Copyright 2016 Guangzhou Network Technology Co., Ltd. All rights reserved.//#import "ViewController.h"#import<StoreKit/StoreKit.h>@interfaceViewcontroller () <SKProductsRequestDelegate,SKPaymentTransactionObserver>@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //Monitor Purchase Results[[Skpaymentqueue Defaultqueue] addtransactionobserver:self];}-(void) dealloc{//Remove Purchase Monitor[[Skpaymentqueue Defaultqueue] removetransactionobserver:self];}//when a user clicks on an IAP item, it first inquires whether the user is allowed to pay in-app (Tableviewcell Click, delivery in-store goods productid,productid can be stored in advance to local, when used to directly get it)-(void) validateiscanbought{if([Skpaymentqueue canmakepayments]) {[Self getproductinfo:@[@"Productids"]]; }Else{NSLog (@"failed, user prohibited in-app pay purchase"); }}//Query the App Store with the product ID of the IAP, get the Skpayment instance, and then initiate a purchase with the Skpaymentqueue Addpayment method//The following ProductID should be in advance in the itunesconnect to add a good, already existing paid items, otherwise the query will fail-(void) Getproductinfo: (Nsarray *) productids{Nsset*Set=[Nsset Setwitharray:productids]; Skproductsrequest*request = [[Skproductsrequest alloc] Initwithproductidentifiers:Set]; Request.Delegate=Self ; [Request start];}#pragmaMark-skproductsrequestdelegate//callback functions for queries-(void) Productsrequest: (skproductsrequest *) Request Didreceiveresponse: (Skproductsresponse *) response{//get all in-store itemsNsarray *myproducts =response.products; //Number of Judgments    if(myproducts.count==0) {NSLog (@"Unable to obtain product information, purchase failed. "); return; }        //initiate a purchase operationSkpayment *payment = [Skpayment paymentwithproduct:myproducts[0]]; [[Skpaymentqueue Defaultqueue] addpayment:payment];}#pragmaMark-skpaymenttransactionobserver//when a user buys a result, the following callback function is triggered and processed accordingly-(void) Paymentqueue: (Skpaymentqueue *) queue updatedtransactions: (nsarray<skpaymenttransaction *> *) transactions{ for(Skpaymenttransaction *transactioninchtransactions) {                Switch(transaction.transactionstate) { CaseSkpaymenttransactionstatepurchased://Transaction CompletionNSLog (@"transactionidentifier =%@", Transaction.transactionidentifier);                [Self completetransaction:transaction];  Break;  CaseSkpaymenttransactionstatefailed://Transaction Failure[self failedtransaction:transaction];  Break;  CaseSkpaymenttransactionstaterestored://have purchased this product[self restoretransaction:transaction];  Break;  CaseSkpaymenttransactionstatepurchasing://Add items to the listNSLog (@"Add items to the list");  Break; default:                 Break; }    }}//operations after the transaction is completed-(void) Completetransaction: (Skpaymenttransaction *) transaction{NSString*productidentifier =Transaction.payment.productIdentifier; NSData*transactionreceiptdata =[NSData Datawithcontentsofurl:[[nsbundle Mainbundle] appstorereceipturl]; NSString*receipt =[Transactionreceiptdata base64encodedstringwithoptions:nsdatabase64encoding64characterlinelength]; if([Productidentifier length]>0) {        //Verify the proof of purchase to your own serverNSLog (@"%@", receipt); }        //Remove Transaction purchase operation[[Skpaymentqueue Defaultqueue] finishtransaction:transaction];}//operations after a failed transaction-(void) Failedtransaction: (Skpaymenttransaction *) transaction{if(Transaction.error.code! =skerrorpaymentcancelled) {NSLog (@"Purchase failed"); }Else{NSLog (@"user cancels the transaction"); }    //Remove Transaction purchase operation[[Skpaymentqueue Defaultqueue] finishtransaction:transaction];}//have purchased this product-(void) Restoretransaction: (Skpaymenttransaction *) transaction{//for purchased items, handle the logic to restore purchases//Remove Transaction purchase operation[[Skpaymentqueue Defaultqueue] finishtransaction:transaction];}@end

Reference book: Tang Qi "iOS Development Advanced"

IOS: Implementing Apple's in-app purchases

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.