Detailed IOS application internal purchase/internal payment (i) _ios

Source: Internet
Author: User
Tags reserved uikit

A long time ago to come up with an iOS fee-paid tutorial, but a check on the online tutorial is too much, some write really pretty good, just think about it, and then saved in the draft box. As for why to write it out! It's a long story, and recently a project manager from the company ran to ask me about the details of the Apple-related payment, talk to him for a long time, from the project docking Apple's official payment interface to see how to view the app benefits, and finally gave him some clues, but sad to continue to talk to their programmers to explain the program (really Crazy), So I decided to give them a project to write an internal purchase document, so I drop this blog to complete it!

First into the Apple Itunesconnection (https:// itunesconnect.apple.com) Click on the upper left corner of the plus add a new app application, click on the site will pop up an information edit box, you just fill in the above information click Save on Apple's app platform has a own app.

On the set ID, you need to apply for a appid and Bundleid in advance for the app, as long as the application is successful and will be displayed in the select list.

By the way, here's what this itunesconnect is for, it's a platform that Apple provides to individuals and businesses to manage their apps. On this platform, developers can create new, delete and manage their app apps, and developers can build apps on demand, edit app information, generate the information needed to test the app, such as account number, invitation code, and what we're going to talk about in the billing function today. Of course, he's more than what I'm talking about, and I'm going to say a little bit about the role of this platform, and you'll get familiar with it if you're dealing with it a lot.

Next, I'll show you how to add paid props, first open itunesconnect, display the following page:

Select the circle of the red circle of options, and then the relevant information inside the complete, if the lack of this step, the internal purchase function will not be successful.

If you have completed the relevant bank account settings, click on your app and select "app purchase" in the title bar above.

Then click the "Create new" option in the upper-left corner, as shown in the following image, and go to the next interface:

This interface is the kind of consumer props that you choose, now the revision of the site is Simplified Chinese translation, so not as before open a look do not know which to choose, or even do not know what each representative means (for example, when I first met, in front of the leadership is really embarrassing). It is divided into the following kinds:

Generally, most of the projects are selected "expendable items" this type, such as the game to buy gold coins, gems balabala~ and so on, selected will come to this interface:

In the edit box shown in the image above, enter the product name, product ID, and price level, which is explained here:

1. Product name according to the actual meaning of your consumption props to explain, such as "100 gems", "100 gold coins" and so on.

2. Product ID is more important, by the project customization, as long as the only can, as I generally use the app Bundleid plus a suffix to express, this is related to the project and unique.

3. The price class "View price List" in the corresponding description, you can follow the table in each country's currency price and rank to choose.

We continue, in the next section of this page as shown in the figure:

Select the Add language option to eject an edit page:

Click Save and it will appear as follows in the interface:

The final step is to click the "Select File" to submit an apple pixel (640*920) of the product picture, when he uploaded finished click the "Save" button, we this second part of the workpiece. The goods submitted will be displayed on the internal purchase page as shown below:

This is the image I intercepted on the app that I've released, added 3 items that have been passed in the state of the (show Green), when you just submitted the time, because through the Apple review will take a while to show the yellow waiting status, so do not worry about whether the product editor wrong. As shown in figure:

In this part, I will mainly show you how to apply for the test account, using the Apple Sandbox test environment to simulate the purchase process of the App Store.
Select the "Users and Functions" option in Itunesconnect ~

Then select the sandbox tester in the upper left corner and click on the plus icon in the upper left corner to add a tester, as shown:

Edit the appropriate content, click Save, created a test account, is not very simple ah! Of course this account is irrelevant if you forget that the password can be regenerated.

Incidentally, not in the official App Store with sandbox test account to log in, do remember, this account only for testing environment ~

And then there's the code section.

1. First of all, add "storekit.framework" to the Project project, add the header file #import <StoreKit/StoreKit.h>

2. Inclusion of the "skpaymenttransactionobserver,skproductsrequestdelegate" listening mechanism in the. h file

Below the core of the purchase of the Code, on a few functions, I do not do in this side to do more detailed explanation, you reader can run run a glance at.
. h Files

 
//PaymentViewController.h 
//iappaytest//// 
Created by 
Silicon on 14-10-28. 
Copyright (c) 2014 silicon. All rights reserved. 
 
#import <UIKit/UIKit.h> 
 
#import <StoreKit/StoreKit.h> 
 
@interface Paymentviewcontroller : uiviewcontroller<skpaymenttransactionobserver,skproductsrequestdelegate> 
 
@property (Strong, nonatomic) Iboutlet Uitextfield *productid; 
 
@property (Strong, nonatomic) Iboutlet UIButton *purchase; 
 
-(Ibaction) Purchasefunc: (ID) sender; 
 
@end 

. m file

PAYMENTVIEWCONTROLLER.M//Iappaytest////Created by silicon on 14-10-28. Copyright (c) 2014 silicon. 
All rights reserved. #import "PaymentViewController.h" @interface Paymentviewcontroller () @end @implementation paymentviewcontr Oller-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) Nibbundleornil {self = [super initwithnibn 
  Ame:nibnameornil Bundle:nibbundleornil]; 
if (self) {//Custom initialization} return self; 
  }-(void) viewdidload {[Super viewdidload]; 
   
  Do no additional setup after loading the view from its nib. 
  [[Skpaymentqueue Defaultqueue] addtransactionobserver:self]; 
Self.productID.text = @ "Com.games.ztyxs.product_point.1"; 
  }-(void) didreceivememorywarning {[Super didreceivememorywarning]; 
Dispose of any of the can is recreated. 
  }-(Ibaction) Purchasefunc: (ID) Sender {nsstring *product = Self.productID.text; if ([Skpaymentqueue canmakepayments]){[Self requestproductdata:product]; 
  }else{NSLog (@ "not allowed to pay within the program"); 
  }//Request commodity-(void) Requestproductdata: (NSString *) type{NSLog (@ "-------------request corresponding product information----------------"); 
 
  Nsarray *product = [[Nsarray alloc] initwithobjects:type, nil Nil]; 
  Nsset *nsset = [Nsset setwitharray:product]; 
  Skproductsrequest *request = [[Skproductsrequest alloc] initwithproductidentifiers:nsset]; 
  Request.delegate = self; 
   
[Request start]; 
 
  //Receive Product return information-(void) Productsrequest: (skproductsrequest *) Request Didreceiveresponse: (Skproductsresponse *) response{ 
  NSLog (@ "--------------Receive product Feedback message---------------------"); 
  Nsarray *product = response.products; 
    if ([Product count] = = 0) {NSLog (@ "--------------no commodity------------------"); 
  Return 
  } NSLog (@ "productid:%@", response.invalidproductidentifiers); 
   
  NSLog (@ "Number of products paid:%d", [Product Count]); 
  Skproduct *p = nil; 
    For (skproduct *pro in product) {NSLog (@ "%@", [pro description]); NsLog (@ "%@", [pro Localizedtitle]); 
    NSLog (@ "%@", [pro localizeddescription]); 
    NSLog (@ "%@", [pro price]); 
     
    NSLog (@ "%@", [pro Productidentifier]); 
    if ([Pro.productidentifier IsEqualToString:self.productID.text]) {p = Pro; 
   
  } skpayment *payment = [Skpayment paymentwithproduct:p]; 
  NSLog (@ "Send purchase Request"); 
[[Skpaymentqueue Defaultqueue] addpayment:payment]; }//Request failed-(void) Requests: (Skrequest *) Request Didfailwitherror: (Nserror *) error{NSLog (@ "------------------error------ 
-----------:%@ ", error); 
}-(void) Requestdidfinish: (Skrequest *) request{NSLog (@ "------------feedback end-----------------"); //Monitor purchase result-(void) Paymentqueue: (Skpaymentqueue *) queue updatedtransactions: (Nsarray *) transaction{for (skpayment Transaction *tran in Transaction) {switch (tran.transactionstate) {case Skpaymenttransactionstatepurcha 
         
        Sed:nslog (@ "Transaction complete"); 
      Break Case SkpaymenttransactionstatepurchasiNg:nslog (@ "Product add in List"); 
      Break 
       
        Case Skpaymenttransactionstaterestored:nslog (@ "already purchased goods"); 
      Break 
         
        Case Skpaymenttransactionstatefailed:nslog (@ "Transaction failure"); 
      Break 
    Default:break; 
   
  }}//Transaction end-(void) Completetransaction: (skpaymenttransaction *) transaction{NSLog (@ "Transaction end"); 
[[Skpaymentqueue Defaultqueue] finishtransaction:transaction]; 
  }-(void) dealloc{[[Skpaymentqueue Defaultqueue] removetransactionobserver:self]; 
[Super Dealloc]; 
 } @end

The code is so much, to this side of our iOS tutorial is nearing the end of the test, there are several factors to pay attention to:

1. Sandbox environment test in the store process, please use the equipment without escape.

2. Be sure to use the real machine to test, all the real machine to prevail.

3. The bundle identifier of the project needs to be consistent with the bundleid you fill out when you apply for AppID, or you will not be able to request merchandise information.

After talking so much, attach a few test screenshots to show you:

Print log when requesting merchandise:

After successful transaction:

Phone screen:

Requires that you enter the App Store ledger and use the test build to:

Confirm Purchase:

Transaction complete:

When our deal is done, we have to go to the App Store to verify that the ticket information is correct so that we can give the player a prop, the official Apple document:

End of transaction-(void) Completetransaction: (skpaymenttransaction *) transaction{NSLog (@ "Transaction end"); 
  Transaction verification Nsurl *recepiturl = [[NSBundle mainbundle] appstorereceipturl]; 
   
  NSData *receipt = [NSData Datawithcontentsofurl:recepiturl]; 
  if (!receipt) {} nserror *error; 
                   Nsdictionary *requestcontents = @{@ "Receipt-data": [Receipt base64encodedstringwithoptions:0] 
  }; 
                              NSData *requestdata = [Nsjsonserialization datawithjsonobject:requestcontents options:0 
   
  error:&error]; if (!requestdata) {/* ... Handle error ... */}//in the test environment, use Https://sandbox.itunes.apple.com/verifyReceipt//in the Rea 
  L Environment, use https://buy.itunes.apple.com/verifyReceipt//Create a POST request with the receipt data. 
  Nsurl *storeurl = [Nsurl urlwithstring:@ "Https://buy.itunes.apple.com/verifyReceipt"]; Nsmutableurlrequest *storerequest = [Nsmutableurlrequest Requestwithurl:storeurl]; 
  [Storerequest sethttpmethod:@ "POST"]; 
   
  [Storerequest Sethttpbody:requestdata]; 
  Make a connection into the ITunes Store on a background queue. 
  Nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; [Nsurlconnection sendasynchronousrequest:storerequest queue:queue completionhandler:^ (NSURLResponse *respon SE, NSData *data, Nserror *connectionerror) {if (connectionerror) {/* ... 
                  Handle error ... * *} else {nserror *error; 
                  Nsdictionary *jsonresponse = [nsjsonserialization jsonobjectwithdata:data options:0 error:&error]; if (!jsonresponse) {/* ... Handle error ... * * ... 
 
   
   
  Send a response back to the device ... * *//parse the response}]; 
[[Skpaymentqueue Defaultqueue] finishtransaction:transaction]; 
 }

OK, all the internal purchase process is basically finished, forgive me in the picture of the smear, because it is related to the product of sensitive words so I hope you can not mind. The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.