Unity3d Access IOS Internal purchase __ios

Source: Internet
Author: User

The use of Unity3d produced game released to the App Store, and sometimes do the game to buy virtual goods, that is, internal purchase.

In the development of iOS is called: in APP Purchase, abbreviation IAP

So how to embed IPA in Unity3d. After a few, many search, find out some experience, share to everyone, if there are omissions, but also please advise.

Of course, some people write good plug-ins available, I feel that they write to use smoothly.

First, the preparation conditions:

1, the application of Apple developer account. Create a certificate in the background, create an application, fill in application details, create a test account, and create an internal purchase item.

This is where you create consumable (each time you need to buy) or non-consumable (the purchase is always available, that is, if you buy one that can be purchased again).

As follows we created the non-consumable type, the name "Package_2", which can only be used once, and cannot be reused even if it is deleted.


To create a tester account, you can test and purchase all of the items under this developer account for free:


2, a simple understanding of the development of iOS Object-c language, mainly used to do within the purchase, detailed please Baidu:

3. Simple understanding of IPA

See also for details: Storekit Guide (in App Purchase) translation

http://yarin.blog.51cto.com/1130898/549141

4, understand Unity3d and iOS communications, detailed see: For iOS to create Plug-ins building Plugins for iOS

Http://game.ceeger.com/Manual/PluginsForIOS.html

Two, we will create a separate example to illustrate the following:

1, create the project, switch to the iOS platform, create an empty Gameobject, renamed to Main, create a click button to trigger the purchase of the script, hanging on main. To create a platform file, create a subfolder of iOS below.

2, in the settings to modify the package name, instead of your own in the App Store background to create the name


Ipademo inside write with the iOS communication code as well as the purchase code, in which the name of the purchased product is modified for its own app Store background definition:private stringproduct = "package_2";

Using Unityengine;

Using System.Collections;

Using System.Collections.Generic;

Using System.Runtime.InteropServices;

public class Ipademo:monobehaviour {

publiclist<string> ProductInfo = new list<string> ();

Privatestring Product = "package_2";

[DllImport ("__internal")]

privatestatic extern void Testmsg ();//test message Send

[DllImport ("__internal")]

privatestatic extern void testsendstring (string s);//Test Send string

[DllImport ("__internal")]

privatestatic extern void testgetstring ()//test receive string

[DllImport ("__internal")]

privatestatic extern void Initiapmanager ();//initialization

[DllImport ("__internal")]

privatestatic extern bool Isproductavailable ()//Determine whether you can buy

[DllImport ("__internal")]

privatestatic extern void Requstproductinfo (string s);//Get commodity information

[DllImport ("__internal")]

privatestatic extern void Buyproduct (string s);//Buy goods

To test the string received from Xcode

Voidiostou (String s)

{

Debug.Log ("[Msgfrom iOS]" +s);

}

Get Product List

Voidshowproductlist (string s) {

Productinfo.add (s);

}

Get a receipt for a product

Voidprovidecontent (String s)

{

Debug.Log ("[Msgfrom ios]proividecontent:" +s);

}

Voidstart ()

{

Initiapmanager ();

}

Voidupdate ()

{

}

Voidongui ()

{

if (Btn ("GetProducts")) {

if (! Isproductavailable ())

Thrownew System.Exception ("IAP not Enabled");

productinfo= new list<string> ();

Requstproductinfo (product);

}

Guilayout.space (40);

For (inti=0 i<productinfo.count; i++) {

if (Guilayout.button (productinfo[i],guilayout.height), Guilayout.minwidth (200)) {

String[]cell = Productinfo[i]. Split (' t ');

Debug.Log ("[Buy]" +cell[cell. Length-1]);

Buyproduct (Cell[cell. Length-1]);

}

}

}

BOOLBTN (String msg) {

Guilayout.space (100);

Return Guilayout.button (Msg,guilayout.width), Guilayout.height (100));

}

}

Also need to write inside the Xcode inside the code and then copy to the platform under the iOS folder:


Only in the real machine can appear in the Purchase window, unity in the operation of the results are as follows:


3, Export iOS project, on the Mac Xcode open:

4, add dependencies, Libz,storekit:


5, in the real machine running, first get the list of goods, and then click to Buy, and then in the Pop-up account password box to modify the sandbox test account. You can test your purchase success.


The 2. h files were:

1, IAPInterface.h


#import <Foundation/Foundation.h>


@interface Iapinterface:nsobject


@end


2, IAPManager.h


#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>


@interface Iapmanager:nsobject<skproductsrequestdelegate, skpaymenttransactionobserver>{
Skproduct *proupgradeproduct;
Skproductsrequest *productsrequest;
}


-(void) attachobserver;
-(BOOL) canmakepayment;
-(void) Requestproductdata: (NSString *) productidentifiers;
-(void) Buyrequest: (NSString *) Productidentifier;


@end


2. m files are:

1/iapmanager.m

#import "IAPManager.h"

@implementation Iapmanager


-(void) attachobserver{
NSLog (@ "Attachobserver");
[[Skpaymentqueue Defaultqueue] addtransactionobserver:self];
}


-(BOOL) canmakepayment{
return [Skpaymentqueue canmakepayments];
}


-(void) Requestproductdata: (NSString *) productidentifiers{
Nsarray *idarray = [productidentifiers componentsseparatedbystring:@ "T"];
Nsset *idset = [Nsset Setwitharray:idarray];
[Self sendrequest:idset];
}


-(void) SendRequest: (Nsset *) idset{
Skproductsrequest *request = [[Skproductsrequest alloc] initwithproductidentifiers:idset];
Request.delegate = self;
[Request start];
}


-(void) Productsrequest: (skproductsrequest *) Request Didreceiveresponse: (Skproductsresponse *) response{
Nsarray *products = response.products;

For (skproduct *p in products) {
Unitysendmessage ("Main", "showproductlist", [[Self productinfo:p] utf8string]);
}

For (NSString *invalidproductid in response.invalidproductidentifiers) {
NSLog (@ "Invalid product id:%@", Invalidproductid);
}

[Request Autorelease];
}


-(void) Buyrequest: (NSString *) productidentifier{
Skpayment *payment = [Skpayment paymentwithproductidentifier:productidentifier];
[[Skpaymentqueue Defaultqueue] addpayment:payment];
}


-(NSString *) ProductInfo: (skproduct *) product{
Nsarray *info = [Nsarray arraywithobjects:product.localizedtitle,product.localizeddescription,product.price, Product.productidentifier, nil];

return [info componentsjoinedbystring:@ "T"];
}


-(NSString *) Transactioninfo: (skpaymenttransaction *) transaction{

return [self encode: (uint8_t *) transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length];

return [[NSString alloc] InitWithData:transaction.transactionReceipt encoding:nsasciistringencoding];
}


-(NSString *) encode: (const uint8_t *) input length: (Nsinteger) length{
static char table[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/=";

Nsmutabledata *data = [Nsmutabledata datawithlength: ((length+2)/3) *4];
uint8_t *output = (uint8_t *) data.mutablebytes;

For (Nsinteger i=0 i<length; i+=3) {
Nsinteger value = 0;
For (Nsinteger j= i; j< (i+3); j + +) {
value<<=8;

if (j<length) {
Value |= (0xFF & Input[j]);
}
}

Nsinteger index = (I/3) *4;
Output[index + 0] = table[(value>>18) & 0x3f];
Output[index + 1] = table[(value>>12) & 0x3f];
Output[index + 2] = (i+1) <length? table[(value>>6) & 0x3f]: ' = ';
Output[index + 3] = (i+2) <length? table[(value>>0) & 0x3f]: ' = ';
}

return [[NSString alloc] Initwithdata:data encoding:nsasciistringencoding];
}


-(void) Providecontent: (skpaymenttransaction *) transaction{
Unitysendmessage ("Main", "providecontent", [[Self transactioninfo:transaction] utf8string]);
}


-(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];
Break
Default
Break
}
}
}


-(void) Completetransaction: (skpaymenttransaction *) transaction{
NSLog (@ "Comblete transaction:%@", transaction.transactionidentifier);
[Self providecontent:transaction];
[[Skpaymentqueue Defaultqueue] finishtransaction:transaction];
}


-(void) Failedtransaction: (skpaymenttransaction *) transaction{
NSLog (@ "Failed transaction:%@", transaction.transactionidentifier);

if (Transaction.error.code!= skerrorpaymentcancelled) {
NSLog (@ "!) Cancelled ");
}
[[Skpaymentqueue Defaultqueue] finishtransaction:transaction];
}


-(void) Restoretransaction: (skpaymenttransaction *) transaction{
NSLog (@ "Restore transaction:%@", transaction.transactionidentifier);
[[Skpaymentqueue Defaultqueue] finishtransaction:transaction];
}




@end


2, #import "IAPInterface.h"
#import "IAPManager.h"


@implementation Iapinterface


void Testmsg () {
NSLog (@ "MSG received");


}


void testsendstring (void *p) {
NSString *list = [NSString stringwithutf8string:p];
Nsarray *listitems = [list componentsseparatedbystring:@ "T"];

for (int i =0; i<listitems.count; i++) {
NSLog (@ "msg%d:%@", i,listitems[i]);
}

}


void Testgetstring () {
Nsarray *test = [Nsarray arraywithobjects:@ "T1", @ "T2", @ "T3", nil];
NSString *join = [Test componentsjoinedbystring:@ ' \ n '];


Unitysendmessage ("Main", "Iostou", [join Utf8string]);
}


Iapmanager *iapmanager = nil;


void Initiapmanager () {
Iapmanager = [[Iapmanager alloc] init];
[Iapmanager Attachobserver];

}


BOOL Isproductavailable () {
return [Iapmanager canmakepayment];
}


void Requstproductinfo (void *p) {
NSString *list = [NSString stringwithutf8string:p];
NSLog (@ "productkey:%@", list);
[Iapmanager requestproductdata:list];
}


void buyproduct (void *p) {
[Iapmanager buyrequest:[nsstring Stringwithutf8string:p]];
}


@end


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.