‹ IAP Doc Home

In-App Purchase Integration Guide

For the Javascript version of cocos2d-x v3.x - (all other versions)


Open a terminal and use the following command to install the SDKBOX IAP plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import iap

NOTE: 1. For iOS, you need Xcode9 because of https://developer.apple.com/app-store/promoting-in-app-purchases/

  1. For iOS, Auto-Renewables subscription, in sandbox the validity time differs from live environment!!!

    Durations Sandbox Duration Incentive Durations (optional)
    7 days 3 minutes 7 days
    1 month 5 minutes 7 days, 1 month
    2 months 10 minutes 7 days, 1 month
    3 months 15 minutes 1 month
    6 months 30 minutes 1 month, 2 months
    1 year 1 hour 1 month, 2 months, 3 months

    After 6 extensions the abo is cancelled automatically in the sandbox environment.

Important Notice

Please make sure the following settings in your project to make the plugin work well.

Disable App Transport Security

Adding the following entry to the info.plist file:


It should look like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't, cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations, you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This setting depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.


SDKBOX Installer will automatically inject a sample configuration to your sdkbox_config.json, that you have to modify it before you can use it for your own app.

Here is an example of the IAP configuration, you need to replace <put the product id for ios here> with the product id from your iTunes Connect or replace <put your googleplay key here> from your Google Play Console.

For GooglePlay, you must specify the public key in the IAP configuration inspector panel. You can get it from the section "Services & APIs" of Google Play Console.

"ios" :
                "id":"<put the product id for ios here>"
        "key":"<put your googleplay key here>",
              "id":"<put the product id for android here>"

If you have IAP items, whose type is non-consumable or subscription, it is also necessary to supply the type for each item in your sdkbox_config.json. Taking the same json above your config might now look like this example:

        "key":"<put your googleplay key here>",
            "coins":{ //this is consumable item
                "id":"<put the product id for android here>"
                "id":"<put the product id for android here>",
                "type":"non_consumable" //this is non-consumable item
                "id":"<put the product id for android here>",
                "type":"subs" //this is subscription item

Note: the key in sdkbox_config.json should be get from Google Play Console, Google Console->Developer Tools->Services & APIs, take a look at follow screenshot:

Test IAP for iOS

Test IAP for android

  1. To test Android IAP you need to publish you app with alpha/beta chanel
  2. To test Android IAP you need to opt-in as an alpha tester here
  3. You can only test IAP in release build
  4. Replace the key with your key. In https://play.google.com/apps/publish/, open your game, follow menu "Development tools -> Services & APIs -> in-app billing"

SKPaymentTransactionStateDeferred test

SKPaymentTransactionStateDeferred is a middle transaction status of iOS IAP . for most developer, need't case about this status.

if you want to test this status, you can add simulatesAskToBuyInSandbox to sdkbox_config.json.

    "iap": {
        "simulatesAskToBuyInSandbox": true,
        "items": { ... }

more about SKPaymentTransactionStateDeferred

Initialization opportunity

For the initialization of IAP, please note the following:

  1. After the app starts, initialize the IAP as early as possible.
  2. Please setListener first , then init .
  3. If there are multiple plugins, the IAP init should be called first.


Register Javascript Functions

You need to register all the IAP JS functions with cocos2d-x before using them.

To do this: * Modify ./frameworks/runtime-src/Classes/AppDelegate.cpp to include the following headers:

#include "PluginIAPJS.hpp"
#include "PluginIAPJSHelper.h"

Initialize IAP

Initialize the plugin by calling init() where appropriate in your code. We recommend to do this in the app.js. Example:


Retrieve latest Product data

It's always a good idea to retrieve the latest product data from store when your game starts.

To retrieve latest IAP data, simply call sdkbox.IAP.refresh().

onProductRequestSuccess if retrieved successfully.

onProductRequestFailure if exception occurs.

Make a purchase

To make a purchase call sdkbox.IAP.purchase(name)

Note: name is the name of the IAP item in your config file under items tag, not the product id you set in iTunes or GooglePlay Store

onSuccess will be triggered if purchase is successful.

onFailure will be triggered if purchase fails.

onCanceled will be triggered if purchase is canceled by user.

Restore purchase

To restore purchase call sdkbox.IAP.restore().

onRestored will be triggered if restore is successful.

Note: onRestored could be triggered multiple times

Handling Purchase Events

This allows you to catch the IAP events so that you can perform operations based upon the response from your players and IAP servers.

    onSuccess : function (product) {
        //Purchase success
    onFailure : function (product, msg) {
        //Purchase failed
        //msg is the error message
    onCanceled : function (product) {
        //Purchase was canceled by user
    onRestored : function (product) {
        //Purchase restored
    onProductRequestSuccess : function (products) {
        //Returns you the data for all the iap products
        //You can get each item using following method
        for (var i = 0; i < products.length; i++) {
            // loop
    onProductRequestFailure : function (msg) {
        //When product refresh request fails.

Remote Configuration

Optionally, you can choose to use SDKBOX LiveOps to remotely update this plugin's configuration. Learn more

IAP Receipts Verification

If you're using remote configration for SDKBOX IAP Receipts verification is turn on by default Click here to learn more..

Implement your own verification

You can get the receipt data and verify it with your own server by calling following method


And then you should be able to access iap receipts using the following fields


Note: iOS don't provide purchase receipt, only ciphered payload

Promotion IAP

Enable Promotion IAP

if you want to use iOS promotion iap

  1. implement onShouldAddStorePayment of IAPListener class.
  2. configure itunes connect

we return true by default in onShouldAddStorePayment. this will not cancel or defer user's purchase action.

Promotion IAP Setting

You can also customize which promoted in-app purchases a user sees on a specific device with follow api:

  1. sdkbox.IAP.updateStorePromotionOrder(["remove_ads"]);
  2. sdkbox.IAP.updateStorePromotionVisibility('remove_ads', true);
  3. sdkbox.IAP.fetchStorePromotionOrder();
  4. sdkbox.IAP.fetchStorePromotionVisibility('remove_ads');

more detailPromoting IAP official Document

API Reference



Initialize SDKBox IAP


Enable/disable debug logging


Make a purchase request

@Param name is the name of the item specified in sdkbox_config.json

Refresh the IAP data(title, price, description)


Restore purchase


Set listener for IAP


Remove listener for IAP


get auto invoke finishTransaction flag


set auto invoke finishTransaction flag


to invoke ios finishTransaction api

sdkbox.IAP.updateStorePromotionVisibility(productName, visibility);

get all purchase history, include cancelled, expired


get initialized error message


request all unfinish transaction, and retrigger onSuccess, onFailed or onCancel event with corresponding transaction.

just valid on iOS

e.g. if there have two transaction (one is success, on is canceled) havn't been finish, after invoke requestUpdateTransaction, onSuccess will trigger with the success transaction, onCancelled will trigger with the cancelled transaction.

Note: for most developer, this api is needn't, onSuccess, onFailed or onCancel will auto trigger when transaction updated.



Called when IAP initialized


Called when an IAP processed successfully

onFailure(p, msg);

Called when an IAP fails


Called when user canceled the IAP


Called when server returns the IAP items user already purchased @note this callback will be called multiple times if there are multiple IAP


Called the product request is successful, usually developers use product request to update the latest info(title, price) from IAP


Called when the product request fails

onRestoreComplete(ok, msg);

Called when the restore completed

onFetchStorePromotionOrder(productNames, error);
onFetchStorePromotionVisibility(productName, visibility, error);
onConsumed(p, error);

Called when consume completed, just trigger on android


Called when IAP pay deferred

Note: Pay deferred status is a middle status, for most developer, needn't case this status
this status will change to success or failed or cancel, its final status is pending external action.
Please DO NOT finishTransaction when status is deferred.

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of the IAP bundle into your Xcode project, check Copy items if needed when adding frameworks:



The above frameworks depend upon other frameworks. You also need to add the following system frameworks, if you don't already have them:





Copy all source and header files from plugin/jsbindings/ to your projects Classes folder.

NOTE: plugin/jsbindings/jsb2 for creator 1.7.

Add these same files, that you just copied, to Xcode by either dragging and dropping them into Xcode or by using File -> Add files to....

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy jar files

Copy the following jar files from plugin/android/libs folder of this bundle into your project's /libs folder.




Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Edit AndroidManifest.xml

Include the following permissions above the application tag:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.vending.BILLING"/>

Include the following activity in the application tag:

<activity android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:name="com.android.billingclient.api.ProxyBillingActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Add additional dependencies to LOCAL_WHOLE_STATIC_LIBRARIES:


Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./sdkbox)
$(call import-module, ./pluginiap)

This means that your ordering should look similar to this:

$(call import-add-path,$(LOCAL_PATH))
$(call import-module, ./sdkbox)
$(call import-module, ./pluginiap)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 - v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Copy all source and header files from plugin/jsbindings/ to your projects Classes folder.

NOTE: plugin/jsbindings/jsb2 for creator 1.7.

Add all .cpp files, that you just copied, to Android.mk in the LOCAL_SRC_FILES section. Example

LOCAL_SRC_FILES := hellocpp/main.cpp \
                  ../../Classes/AppDelegate.cpp \
                  ../../Classes/HelloWorldScene.cpp \

Modify AppActivity.java

Plugin >=

  1. Find the AppActivity.java
find . -name "AppActivity.java"
  1. Replace extends Cocos2dxActivity with extends com.sdkbox.plugin.SDKBoxActivity

Example of the directory where the AppActivity.java file is located:

  - proj.android/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android-studio/app/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android/app/src/org/cocos2dx/cpp/AppActivity.java ( from cocos2d-x 3.17)

  - frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/lua/AppActivity.java (from cocos2d-x 3.17)

  - frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/javascript/AppActivity.java ( from cocos2d-x 3.17)

Plugin <

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
    protected void onStart() {
    protected void onStop() {
    protected void onResume() {
    protected void onPause() {
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {

Manual Integration for Google Play Services SDK (dependent library only)


Please try the SDKBOX installer first. It will do all the following step for you automatically.

$ sdkbox import googleplayservices

Modify project.properties

An Android Library Reference for Google Play Services is required. The path will be different depending upon your setup. Also, this is an additional download that does not come as part of a standard install. To install use the sdk installer and choose extras->google play services. Here is an example of what this line could look like:


Note: if you already have an android.library.reference.1 you can add another by incrementing the number as android.library.reference.2, etc.

Integration manually

We make a lite version of Google Play Services, the project repo is https://github.com/darkdukey/Google-Play-Service-Lite

Copy Files

Copy the gps folder from plugin folder of this bundle into your project's /libs folder.

Modify files for Eclipse

  1. Modify project.properties
# For source project

# Or
# For framework project

Modify files for Android Studio

1. Modify cocos2d/cocos/platform/android/libcocos2dx/build.gradle
 dependencies {
+    compile project(':gps')
     compile fileTree(dir: '../java/libs', include: ['*.jar'])
2. Modify proj.android-studio/app/project.properties
 # Project target.
3. Modify proj.android-studio/settings.gradle
 project(':libcocos2dx').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/libcocos2dx')
 include ':your_project_name'
 project(':your_project_name').projectDir = new File(settingsDir, 'app')
+include ':gps'
+project(':gps').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/java/libs/gps')

Proguard (optional)

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;

# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep public class com.google.android.gms.** { public *; }
-dontwarn com.google.android.gms.**

-keep class com.google.protobuf.** { *; }
-dontwarn com.google.protobuf.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;

-keep public class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.