Skip to main content

Android SDK reference

The Aghanim Android SDK that allows you to use the Checkout within your Android app.

Native UI
Native UI

Native UI

Integration

To integrate the SDK, see its prerequisites and the detailed instruction on Integrate → Android.

Method reference

Get Order

To read a single Order by its ID, use the orders.get or orders.getAsync method. Returns an Order with the Order's items, amount, and current status. A blank orderId fails with ApiError.InvalidArgument.

import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val result = aghanim.orders.get(orderId)) {
is ApiResult.Success -> {
val order = result.value
Log.d("Orders", "Order ${order.id} is ${order.status}")
order.items.forEach { item ->
Log.d("Orders", "${item.quantity} x ${item.name}")
}
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Orders", "Failed to get order: ${result.error}")
// TODO: Handle error
}
}
ParameterTypeRequiredDescription
orderIdStringYesUnique ID for the Order.

Get unconsumed Orders

To know what Orders have been paid for but not granted yet, use the getUnconsumed or getUnconsumedAsync method. Requires the player ID to be set via Set player ID.

import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val unconsumedResult = aghanim.orders.getUnconsumed()) {
is ApiResult.Success -> {
// Player has paid but not granted items from orders
val unconsumedOrderIds = unconsumedResult.value
// TODO: Save order IDs for further consuming and granting
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Orders", "Failed to get unconsumed orders: ${unconsumedResult.error}")
// TODO: Handle error
}
}

Consume paid Order

To let the SDK acknowledge that you have granted the items the player has purchased via an Order, use the consume or consumeAsync method. Requires the player ID to be set via Set player ID.

import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val consumeResult = aghanim.orders.consume(orderId)) {
is ApiResult.Success -> {
// Paid orders are marked as consumed
Log.d("Orders", "Order $orderId is successfully consumed")
// TODO: Grant items in order to player
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Orders", "Failed to consume order: ${consumeResult.error}")
// TODO: Handle error
}
}

Set player ID

To set the player ID once for the current SDK instance, use the setPlayerId method. The SDK will use the ID in all following method calls. The method is suspend and returns ApiResult<Unit>; a blank player ID fails with ApiError.InvalidArgument.

import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val result = aghanim.setPlayerId(playerId)) {
is ApiResult.Success -> {
// The SDK attaches the player ID to all following method calls
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Aghanim", "Failed to set player ID: ${result.error}")
// TODO: Handle error
}
}
ParameterTypeRequiredDescription
playerIdStringYesUnique ID for the player.

Clear player ID

To remove the player ID from the SDK instance, for example when the player signs out, use the clearPlayerId method. It is suspend and returns ApiResult<Unit>.

import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val result = aghanim.clearPlayerId()) {
is ApiResult.Success -> {
// The SDK stops attaching the previous player ID to API requests
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Aghanim", "Failed to clear player ID: ${result.error}")
// TODO: Handle error
}
}

Get items

To retrieve items with localized prices, use the items.get or items.getAsync method. The method returns items created in SKU Management → Items with prices localized based on the player's region.

import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val result = aghanim.items.get(
skus = listOf("your-item-sku"),
)) {
is ApiResult.Success -> {
val items = result.value
items.forEach { item ->
// Use item.name, item.price.display, item.imageUrl to populate your store
Log.d("Items", "${item.name}: ${item.price.display}")
}
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Items", "Failed to get items: ${result.error}")
// TODO: Handle error
}
}
ParameterTypeRequiredDescription
skusList<String>YesList of item SKUs to retrieve.
localeLocaleNoLocale for price formatting. Find the full list of supported locales in Checkout → Locales.

Each returned Item carries:

PropertyTypeDescription
skuStringSKU identifier of the item.
nameStringName of the item.
descriptionString?Description of the item.
typeItemTypeType of the item.
priceItemPriceLocalized price of the item.
imageUrlString?Image URL of the item.
quantityIntBase quantity of the item.
isStackableBooleanWhether the item is stackable.
isCurrencyBooleanWhether the item is a virtual currency.

ItemPrice carries:

PropertyTypeDescription
amountBigIntegerPrice in the smallest currency unit, for example cents.
amountDecimalBigDecimalPrice in major currency units.
currencyStringISO 4217 currency code.
displayStringFormatted price string, for example $9.99.

ItemType is a sealed class with these subtypes:

TypeMeaning
ItemRegular item.
CurrencyIn-game currency.
BundleBundle of items.
LootboxLootbox with random contents.
SubscriptionSubscription item.
VirtualCurrencyVirtual currency item.
Unknown(raw)A type this SDK version does not recognize.

A type added on the server after your SDK version shipped arrives as Unknown, with the server's original string in raw, so keep an else branch when matching.

Create Checkout item

To create an item representation, use the CheckoutItem method. The item must already exist in SKU Management → Items, either created there or through the S2S API. Checkout rejects a SKU that is not in the game's catalog, and takes every price from the catalog; the client cannot set or override a price.

import com.aghanim.android.sdk.checkout.core.api.models.CheckoutItem

val checkoutItem = CheckoutItem(
sku = "CRS-82500"
)
ParameterTypeRequiredDescription
skuStringYesItem SKU from Dashboard.
nameStringNoItem name from Dashboard.
descriptionStringNoItem description from Dashboard.
imageUrlStringNoItem image URL from Dashboard.

Create redirect behavior

To choose the behavior of redirecting the player after they have completed the payment successfully, use the RedirectSettings method.

When the player has completed the payment, the SDK redirects them immediately to the deep link from backToGameUrl.

import com.aghanim.android.sdk.checkout.core.api.models.RedirectSettings
import com.aghanim.android.sdk.checkout.core.api.models.RedirectMode

val redirectSettings = RedirectSettings(
mode = RedirectMode.IMMEDIATE
)
ParameterTypeRequiredDescription
modeRedirectModeYesRedirect mode. Possible values: IMMEDIATE, DELAYED, NO_REDIRECT.
delaySecondsintYes if DelayedDelay in seconds. For Delayed mode, default is 5.

Create UI settings

To set the appearance mode for the Checkout, use the UiSettings method.

The SDK automatically detects and applies the appropriate appearance mode based on the system setting.

import com.aghanim.android.sdk.checkout.core.api.models.UiSettings
import com.aghanim.android.sdk.checkout.core.api.models.UiMode

val uiSettings = UiSettings(
mode = UiMode.AUTO
)
ParameterTypeRequiredDescription
modeUiModeYesUI mode. Possible values: AUTO, DARK, LIGHT.

Create Checkout params

To create Checkout params, a representation of what the player sees on the payment form, use the CheckoutParams method.

Creating Checkout params is simpler for the Native UI launch mode. Since the Checkout doesn’t use a browser to launch, no need to pass backToGameUrl.

import com.aghanim.android.sdk.checkout.core.api.models.CheckoutParams

val checkoutParams = CheckoutParams(
items = listOf(checkoutItem),
locale = null
)
ParameterTypeRequiredDescription
itemsList<CheckoutItem>YesList of items.
metadataMap<string, string>NoMetadata structured as “key-value” pairs for tracking purposes.
localestringNoLocale for item name and description localization. Find the full list of supported locales in Checkout → Locales.
backToGameUrlstringNoDeep link URL to return player to app. Is auto-generated if not provided.
redirectSettingsRedirectSettingsNoPost-payment redirect behavior.
uiSettingsUiSettingsNoCheckout appearance settings.

Launch Checkout

To launch the Checkout process, use the startCheckout or startWebCheckout method. The method creates an order from the provided checkout params and opens the Checkout UI. Returns ApiResult<String> where the success value is the Order ID. Requires the player ID to be set via Set player ID, since the order is created against it.

The launch mode uses the Native UI that has full control over the players’ experience.

import com.aghanim.android.sdk.checkout.ui.api.startCheckout
import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val result = aghanim.startCheckout(
context = context,
checkoutParams = checkoutParams,
)) {
is ApiResult.Success -> {
// Order is created and checkout has launched successfully
val orderId = result.value
// TODO: Save order ID for further granting or tracking
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Checkout", "Failed to launch Checkout: ${result.error}")
// TODO: Show user-friendly error message to player
}
}
ParameterTypeRequiredDescription
contextActivityYesCurrent Activity.
checkoutParamsCheckoutParamsYesCheckout configuration.

Present Checkout

To present the Checkout UI for an existing order, use the presentCheckout or presentWebCheckout method. Use this when you have an order ID from server-to-server order creation or when resuming a previously abandoned checkout.

The launch mode uses the Native UI that has full control over the players' experience.

import com.aghanim.android.sdk.checkout.ui.api.presentCheckout
import com.aghanim.android.sdk.common.api.result.ApiResult
import android.util.Log

when (val result = aghanim.presentCheckout(
context = context,
orderId = orderId,
)) {
is ApiResult.Success -> {
// Checkout has launched successfully for the existing order
val presentedOrderId = result.value
}

is ApiResult.Failure -> {
// Log debug information for troubleshooting
Log.e("Checkout", "Failed to present Checkout: ${result.error}")
// TODO: Show user-friendly error message to player
}
}
ParameterTypeRequiredDescription
contextActivityYesCurrent Activity.
orderIdStringYesID of the existing order to open.

Order reference

orders.get returns an Order from com.aghanim.android.sdk.common.api.models.order. Its properties are all val. Every field below is non-null unless the type is marked with ?.

PropertyTypeDescription
idStringUnique ID of the Order.
userIdStringIdentifier of the user who created the Order.
playerIdStringID of the player who placed the Order, as you set it via setPlayerId.
statusOrderStatusCurrent status of the Order. See Order status.
itemsList<OrderItem>Items included in the Order. See Order item.
amountBigIntegerTotal amount in the smallest currency unit, for example cents for USD.
priceMinorUnitIntNumber of decimal places for currency, for example 2 for USD.
currencyStringISO 4217 currency code of the Order.
countryStringCountry code for the Order, for example US.
checkoutUrlStringURL of the payment form for this Order.
emailString?Email address associated with the Order.
ipAddressString?IP address the Order was created from.
userAgentString?User agent the Order was created from.
localeLocale?Locale of the Order. Find the full list in Checkout → Locales.
platformPlatform?Platform the Order was created on. See Platform.
metaMap<String, String>?Developer-defined metadata attached to the Order, for example via CheckoutParams.metadata.
couponsEnabledBoolean?Whether coupons are enabled for this Order.
countryLockedBoolean?Whether the country selection is locked for this Order.
uiSettingsUiSettings?Appearance applied to the Checkout. See UI settings.
redirectSettingsRedirectSettings?Post-payment redirect applied to the Checkout. See Redirect settings.
eligibleForRewardPointsBigInteger?Reward points this Order is eligible for.
eligibleForLoyaltyPointsBigInteger?Loyalty points this Order is eligible for.
rewardsOrderRewards?Virtual currency rewards attached to the Order. See Order rewards.
backToGameUrlString?URL that returns the player to the game after payment.
backToGameSettingsBackToGameSettings?Per-platform back-to-game deep links configured for the game.

To render amount as a human-readable price, divide it by 10 to the power of priceMinorUnit. An amount of 1999 with a priceMinorUnit of 2 is 19.99.

Order status

OrderStatus is a sealed class with these subtypes:

StatusMeaning
CreatedOrder created, awaiting payment.
CapturedPayment captured and processing.
PaidPayment completed; goods and rewards granted.
CanceledOrder canceled.
RefundedOrder refunded.
RefundRequestedA refund has been requested.
ReattemptedPayment was reattempted.
DisputedOrder is under dispute.
Unknown(raw)A status this SDK version does not recognize.

A status added on the server after your SDK version shipped arrives as Unknown, with the server's original string in raw, so keep an else branch when matching.

Order item

PropertyTypeDescription
skuStringSKU identifier of the item.
nameStringName of the item.
descriptionString?Description of the item.
currencyStringISO 4217 currency code for the item price.
quantityIntQuantity of the item in the Order.
imageUrlString?Image URL of the item.

Order rewards

OrderRewards carries:

PropertyTypeDescription
availableList<OrderReward>Available rewards for this Order.

Each OrderReward carries:

PropertyTypeDescription
nameStringDisplay name of the reward, for example Gems.
amountBigIntegerReward amount.
iconUrlString?Icon URL of the reward.

Back-to-game settings

BackToGameSettings holds the per-platform deep links configured for the game:

PropertyTypeDescription
androidAppLinkString?Android App Link, with the {order_id} placeholder already substituted.

Platform

Platform is a sealed class with these subtypes:

PlatformMeaning
AnyAny platform.
IosiOS.
AndroidAndroid.
OtherOther platform.
Unknown(raw)A platform this SDK version does not recognize.

UI settings

Order.uiSettings reports the appearance the server applied:

PropertyTypeDescription
modeUiMode?Appearance applied to the Checkout.

UiMode is a sealed class with these subtypes:

ModeMeaning
AutoDetect and apply the appropriate mode.
DarkForce dark mode appearance.
LightForce light mode appearance.
Unknown(raw)A mode this SDK version does not recognize.

Redirect settings

Order.redirectSettings reports the post-payment redirect the server applied:

PropertyTypeDescription
modeRedirectMode?Redirect applied after a successful payment.
delaySecondsInt?Delay before redirecting, used with Delayed.

RedirectMode is a sealed class with these subtypes:

ModeMeaning
NoRedirectNo automatic redirect.
ImmediateRedirect immediately.
DelayedRedirect after a visible countdown.
Unknown(raw)A mode this SDK version does not recognize.

Error reference

Every SDK method returns ApiResult. On failure, ApiResult.Failure.error is an ApiError. Match on the type to map an error to user-visible behavior; every type carries a debugMessage for logs.

TypePayloadWhen fired
NetworkdebugMessage: StringNo connectivity, DNS failure, and similar transport errors.
TimeoutdebugMessage: StringHTTP 408 or 504, or a client-side request timeout.
NotAuthenticateddebugMessage: StringHTTP 401.
NotAuthorizeddebugMessage: StringHTTP 403.
BadRequestdebugMessage: StringHTTP 400.
NotFounddebugMessage: StringHTTP 404.
ConflictdebugMessage: StringHTTP 409.
ValidationdebugMessage: String, errors: List<ValidationErrorDetail>HTTP 422.
RateLimitExceededdebugMessage: StringHTTP 429.
ServerUnavailabledebugMessage: StringHTTP 503.
Servercode: Int, debugMessage: StringAny other HTTP 5xx.
PlayerIdNotSetAn API that needs a player was called before setPlayerId.
InvalidArgumentargumentName: ArgumentName, reason: Reason, debugMessage: StringAn argument you passed failed client-side validation.
DisposedThe operation was issued against an instance whose dispose was called.
UnknowndebugMessage: StringCatch-all for unrecognized errors.

Validation error detail

Validation.errors is a list of ValidationErrorDetail, one per field-level error:

PropertyTypeDescription
locationList<String>Path to the invalid field, for example ["body", "email"].
messageStringHuman-readable error message.
typeStringError type identifier, for example value_error.email.

Invalid argument

InvalidArgument is raised by the SDK before any request goes out. It is distinct from BadRequest, which is an HTTP 400 from the server.

argumentName identifies the offending argument:

ValueArgument
ORDER_IDThe orderId of order and present-checkout methods.
PLAYER_IDThe playerId of setPlayerId.
SKUThe sku of a single checkout item.
SKUSThe skus of catalog lookups.
ITEMSThe items of a checkout.

reason describes how it failed validation:

ValueMeaning
BLANKA required identifier was empty or whitespace.
EMPTYA required collection had no entries.

Need help?
Contact our integration team at integration@aghanim.com