Unity Package Manager Billing SDK
The Aptoide Billing SDK via Unity Package Manager is a straightforward solution for implementing Catappult billing on Unity Android based games. It includes a Billing client that integrates with the AppCoins Wallet, enabling you to retrieve products from Catappult and handle their purchase seamlessly. This is performed by a bridge between Unity (C#) and AppCoinsAdapter.java, that allows you to access all features of the Android Native SDK.
Summary
For this article we will dive in some key points on how to fully integrate and verify success status of the Aptoide Billing SDK via Unity Package Manager.
- Import Unity Package Manager
- Setup AptoPurchaseManager script
- Setup Purchase
- Perform Server Side Check - Client
- Setup Consume
- Additional Setups and Tools
Step By Step Integration Guide
Step 1 - Import Unity Package Manager
- Start by opening on the top menu bar the Window > Package Manager
- In the new window on the top left corner click on the + sign and select Import via git URL and paste the following link: https://github.com/Catappult/appcoins-sdk-unity.git#v0.9.0.7
- Wait to import and compile all files
- After import it should look like this:
Note:
- If you have already a Plugin/Android/ folder, with custom Android Manifest, Build Gradle files you need to move temporarily the folder from the Assets folder, and then do the install of the UPM, after it you need to check the differences that comes from the UPM, or if you prefer you can edit yours and add the following on the mentioned files. (Check in the end the specific changes needed to be made on Graddle files and Android Manifest)
- Android Manifest: permissions, queries, …
- Gradle: dependencies
Step 2 - Setup AptoPurchaseManager
- Select the a Game Object (Main Camera or your logic game Game Object), on the Inspector panel scroll to bottom
- Add Component, search for AptoPurchaseManager
- Set the params of KEY, SKU (string divided by ";") and Developer Payload
Note:
It's important to make sure you call in other scripts that make use of the AptoPurchaseManager to add the import "using UnityAppCoinsSDK;"
Step 3 - Setup Purchase
- Select the Play button, on the Inspector panel scroll to bottom
- Add entry on the OnClick area
- Drag and drop the Game Object in which you added the AptoPurchaseManager script to the box under Runtime (on OnClick section)
- After that select the Script AptoPurchaseManager and the method StartPurchase , to which you can set the sku
Step 4 - Setup Consume
- Select the Consume button and in the inspector on the bottom add on the on click a new entry
- Drag and drop the Main Camera to the box under Runtime (on OnClick section)
- After that select the Script AptoPurchaseManager and the method ConsumeItem
**Note: The current version as the startPurchase making the consumption as well, but you can separate
Step 5 - Additional Setups and Tools
Android Manifest
- Open the Manifest file (or create one in your Assets folder - via Build Settings > Player Settings ) and update the package name to your project
In the plugins folder on Runtime you get a sample of Manifest, note that permissions, queries and intent-actions are required to be there in order to work properly. In AndroidManifest.xml you need to add 2 permissions and a package in the queries tag so the SDK can communicate with the AppCoins Wallet.
<manifest>
...
<queries>
<!-- Required to work with Android 11 and above -->
<package android:name="com.appcoins.wallet" />
...
</queries>
...
<uses-permission android:name="com.appcoins.BILLING" />
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
Graddle Files
As well as in the Manifest, at the Plugin folder, we provide a set of graddle files to base and mainTemplate required to import libraries needed and proper setup, you may use those files or pass some parts to your current base and mainTemplate file
dependencies {
implementation("io.catappult:android-appcoins-billing:0.9.0.8") //check the latest version in mvnrepository
<...other dependencies..>
}
Note in case you don't have build.graddle files we suggest this approach:
- Module (baseProjectTemplate.gradle)
allprojects {
buildscript {
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
}
dependencies {
// If you are changing the Android Gradle Plugin version, make sure it is compatible with the Gradle version preinstalled with Unity
// See which Gradle version is preinstalled with Unity here https://docs.unity3d.com/Manual/android-gradle-overview.html
// See official Gradle and Android Gradle Plugin compatibility table here https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
// To specify a custom Gradle version in Unity, go do "Preferences > External Tools", uncheck "Gradle Installed with Unity (recommended)" and specify a path to a custom Gradle version
classpath 'com.android.tools.build:gradle:3.4.3'
**BUILD_SCRIPT_DEPS**
}
}
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
flatDir {
dirs "${project(':unityLibrary').projectDir}/libs"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
- Application (mainTemplate.gradle)
apply plugin: 'com.android.library'
**APPLY_PLUGINS**
repositories {
google()
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation("io.catappult:android-appcoins-billing:0.9.0.8")
implementation('org.json:json:20210307')
**DEPS**}
android {
compileSdkVersion **APIVERSION**
buildToolsVersion '**BUILDTOOLS**'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
minSdkVersion **MINSDKVERSION**
targetSdkVersion **TARGETSDKVERSION**
ndk {
abiFilters **ABIFILTERS**
}
versionCode **VERSIONCODE**
versionName '**VERSIONNAME**'
consumerProguardFiles 'proguard-unity.txt'**USER_PROGUARD**
}
lintOptions {
abortOnError false
}
aaptOptions {
noCompress = **BUILTIN_NOCOMPRESS** + unityStreamingAssets.tokenize(', ')
ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~"
}**PACKAGING_OPTIONS**
}
**REPOSITORIES**
**IL_CPP_BUILD_SETUP**
**SOURCE_BUILD_SETUP**
**EXTERNAL_SOURCES**
Additional Tools
To verify the proper operability of the SDK we suggest to test via Backend in order to check the status of initialisation, status of purchase and consumption. Also from the interaction on device we have included a plugin called Android Logcat so you can further get more information.
- Backend Validation
- Android Logcat - You need to access in the top bar "Windows > Analysis > Android Logcat", then you need to select the apk (currently active) and search via tag "APPC" this will help you see more detailed information about the purchase/consumption, initialisation of the Billing SDK.
Billing SDK Flow
Overview
To better understand how the flow operates and how can you customise the previous files, such as the AppCoinsAdapter and AptoPurchaseManager, it's important to understand how it operates and which tools are at your disposal.
To integrate the Appcoins SDK on Unity we have two use an adapter between Unity and Android. For that we use AppCoinsAdapter to catch SDK events of start purchase, initialise, launch billing flow, query purchase, purchase and consume. This provides already all the setup required to implement, thus you just need to call it from AptoPurchaseManager, which can be customised as well as the AppCoinsAdapter.
The billing flow in your application with the SDK is as follows:
- Setup connection with Android Billing SDK;
- Query In-App Products from Android Billing SDK;
- End-user wants to buy a product on your app;
- Application launches the AppCoins Wallet via Android Billing SDK;
- The AppCoins Wallet handles the payment and, on completion, calls back your application;
- Application requests Android Billing SDK to validate transaction data;
- Application gives the product to the end-user.
For additional information check here.
Response Codes
The possible values of the Response from the Android SDK are:
Value | Title | Description |
---|---|---|
-2 | FEATURE_NOT_SUPPORTED | Feature requested is not supported for the current Billing SDK Version, Billing Service or any of the User parameters (eg: device ). |
0 | OK | Success. |
1 | USER_CANCELED | User pressed back or canceled the interaction. |
2 | SERVICE_UNAVAILABLE | The network connection is down. |
3 | BILLING_UNAVAILABLE | This billing API version is not supported for the type requested. |
4 | ITEM_UNAVAILABLE | Requested SKU is not available for purchase. |
5 | DEVELOPER_ERROR | Invalid arguments provided to the API or incorrect invocation of the Methods. |
6 | ERROR | Fatal error during the API action. |
7 | ITEM_ALREADY_OWNED | Failure to purchase since item is already owned. |
8 | ITEM_NOT_OWNED | Failure to consume since item is not owned. |
UPM Sample Scene
To ease the understanding and setup we provide a Sample Scene that enables you to perform purchases or subscriptions and understand better thus you can implement easily.
In the Sample Scene in order to execute you just have to go to Samples folder, and open the DemoSample1 Scene.
You need to open the Main Camera Game Object and on the Inspector, in the AptoPurchaseManager (Script) you need to fill params of Public Key, SKUs and Developer Payload.
To get the Public Key you need to go to your app and Upload New Version, then on the next page on the top you have the API KEY to copy and paste.
In terms of the SKUs, for demo purposes we have set in the AptoPurchaseManager the pattern for 2 SKUs, being each the first for Purchase and the second for Subscription. This can and should be updated to your needs.
Then you open Build Settings, add the scene to Scene in Build and Run.
Diceroll Demo App
Besides the Sample Scene we have a full Demo App that integrates the Billing SDK via UPM, you can use as example - Diceroll Aptoide - via UPM
The flow is the following:
-
Initialise the Billing SDK
-
Load SKU information
-
Query Purchases
-
When pressed on Purchase or Subscription, it will trigger billing flow, which will vary if there's wallet installed or not
-
After inserting payment data it will provide feedback with specific responseCode (you can see using the tool Android LogCat, as mentioned above)
-
After purchase done you have to perform server side check, and if all correctly you should provide the item to the user*
-
After item delivered you can now consume the purchase, and this concludes the payment process.
*NOTE: Here is a snippet of how we performed the diceroll server side check (client side)private IEnumerator ValidatePurchase(Purchase purchase) { string url = $"https://sdk.diceroll.catappult.io/validate/{purchase.packageName}/{purchase.sku}/{purchase.token}"; using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { // Send the request and wait for a response yield return webRequest.SendWebRequest(); if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError) { Debug.LogError($"Validation failed for purchase: {purchase.sku}. Error: {webRequest.error}"); } else { // Parse the response string responseText = webRequest.downloadHandler.text.Trim(); Debug.Log($"Validation response for {purchase.sku}: {responseText}"); // Check if the response is "true" or "false" if (responseText == "true") { Debug.Log($"Purchase validated successfully for {purchase.sku}. Consuming the purchase..."); _aptoPurchaseManager.consumePurchase(purchase.token); if (purchase.itemType == "subs") { Debug.Log("Subscription purchased."); isGoldenDice = true; setGoldenDice(); } else { Debug.Log("Item purchased."); UpdateAttempts(_startingAttempts); } } else if (responseText == "false") { Debug.LogError($"Purchase validation failed for {purchase.sku}."); } else { Debug.LogError($"Unexpected response for purchase validation: {responseText}"); } } } }
FAQ
What is the recommended Unity Version?
Currently the most suitable Unity version is 2021.3.8f1.
Updated 12 days ago