Follow our walkthrough to get Checkout Drop-in running in minutes.
Before you start, make sure you have:
- Android Studio installed on your computer
- Android SDK 24 or higher (`minSdk = 24`)
- Kotlin 2.x (2.2.10 or higher), with a Compose compiler plugin version that matches your Kotlin version
- Jetpack Compose enabled in your app module (SDK UI is Compose-only)
- JitPack repository configured (required for some SDK transitive dependencies)
- Your API credentials from the Unity Portal
Add the JitPack repository and enable Compose in your Gradle files.
// settings.gradle.kts
dependencyResolutionManagement {
repositories {
mavenCentral()
maven("https://jitpack.io")
}
}
// Root build.gradle.kts. Compose plugin version must match Kotlin
plugins {
kotlin("android") version "{kotlinVersion}" apply false
id("org.jetbrains.kotlin.plugin.compose") version "{kotlinVersion}" apply false
}
// App build.gradle.kts
plugins {
id("org.jetbrains.kotlin.plugin.compose")
}
android {
buildFeatures {
compose = true
}
}// settings.gradle
dependencyResolutionManagement {
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
// Root build.gradle
buildscript {
ext.kotlin_version = '{kotlinVersion}'
dependencies {
classpath "org.jetbrains.kotlin:compose-compiler-gradle-plugin:$kotlin_version"
}
}
// App build.gradle
plugins {
id 'org.jetbrains.kotlin.plugin.compose'
}
android {
buildFeatures {
compose true
}
}To get started, add the latest version of the Android SDK to your project using Maven Central.
In your app-level build.gradle file, add the dependency:
dependencies {
implementation("io.pxp:android-components-sdk:{versionNumber}")
}The walkthrough samples (create-session.kt, CheckoutActivity.kt, and webhook-handler.kt) also use Ktor and kotlinx serialization. Add these when you follow the samples as written:
// Root build.gradle.kts
plugins {
kotlin("plugin.serialization") version "{kotlinVersion}" apply false
}
// App build.gradle.kts
plugins {
kotlin("plugin.serialization")
}
dependencies {
implementation("io.ktor:ktor-client-core:{ktorVersion}")
implementation("io.ktor:ktor-client-cio:{ktorVersion}")
implementation("io.ktor:ktor-client-content-negotiation:{ktorVersion}")
implementation("io.ktor:ktor-serialization-kotlinx-json:{ktorVersion}")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:{serializationVersion}")
}// Root build.gradle
buildscript {
ext.kotlin_version = '{kotlinVersion}'
dependencies {
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}
}
// App build.gradle
plugins {
id 'org.jetbrains.kotlin.plugin.serialization'
}
dependencies {
implementation "io.ktor:ktor-client-core:{ktorVersion}"
implementation "io.ktor:ktor-client-cio:{ktorVersion}"
implementation "io.ktor:ktor-client-content-negotiation:{ktorVersion}"
implementation "io.ktor:ktor-serialization-kotlinx-json:{ktorVersion}"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:{serializationVersion}"
}The SDK automatically includes the required Android permissions in its manifest (INTERNET, ACCESS_NETWORK_STATE, and SYSTEM_ALERT_WINDOW). These permissions are necessary for payment processing, network connectivity checks, and 3DS authentication challenges.
Drop-in needs a session from the PXP API. This must happen on your backend using HMAC authentication.
Store your credentials securely
Set up your API credentials as environment variables. Never hardcode them in your application.
Create the HMAC signature function
This function generates a secure authentication hash by combining the timestamp, request ID, request path, and request body (no separators), then hashing with your token value using HMAC SHA256. Put the Token ID in the Authorization header (PXP-UST1 $TOKEN_ID:$timestamp:$hmac), not in the HMAC message body.
Build the session request body
Create a request with your merchant details and transaction information. Set serviceType to "CheckoutDropIn". For returning shoppers, include optional customerProfileId (omit it for guest checkout). The request body must be minified (no whitespace) for the HMAC signature. See Implementation — Customer Profile.
Send the session creation request
POST to https://api-services.pxp.io/api/v1/sessions with these headers and your minified JSON body:
Content-Type: application/jsonX-Client-Id: your Unity Portal client IDX-Request-Id: the same request ID used in the HMAC messageAuthorization:PXP-UST1 $TOKEN_ID:$timestamp:$hmac
Return the session data to your app
The API returns sessionId, hmacKey, data, encryptionKey, locale, allowedFundingTypes, and optional restrictions. Return that JSON from your backend. Map it into SessionConfig on the Android client with toSessionConfig() (see CheckoutActivity.kt). Include allowedFundingTypes (at minimum a non-null cards array, which may be empty) so the card UI can render. cardSchemes alone doesn't enable the card panel.
To show the Aeropay panel, include allowedFundingTypes.payByBanks.aeropay (with externalMerchantId and configurationId from the session response). Aeropay isn't part of WalletsConfig. Map it under payByBanks, as in the sample toAllowedFundingTypes() in CheckoutActivity.kt.
package com.example.checkout
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
// {% step id="credentials-setup" %}
// Store your credentials securely
val CLIENT_ID = System.getenv("PXP_CLIENT_ID") ?: throw Exception("PXP_CLIENT_ID not set")
val TOKEN_ID = System.getenv("PXP_TOKEN_ID") ?: throw Exception("PXP_TOKEN_ID not set")
val TOKEN_VALUE = System.getenv("PXP_TOKEN_VALUE") ?: throw Exception("PXP_TOKEN_VALUE not set")
// {% /step %}
// {% step id="create-signature-function" %}
fun createHmacSignature(
timestamp: String,
requestId: String,
requestPath: String,
requestBody: String,
tokenValue: String
): String {
val message = "$timestamp$requestId$requestPath$requestBody"
val mac = Mac.getInstance("HmacSHA256")
val secretKey = SecretKeySpec(tokenValue.toByteArray(), "HmacSHA256")
mac.init(secretKey)
val hash = mac.doFinal(message.toByteArray())
return hash.joinToString("") { "%02X".format(it) }
}
// {% /step %}
@Serializable
data class SessionRequest(
val merchant: String,
val site: String,
val sessionTimeout: Int,
val merchantTransactionId: String,
val transactionMethod: TransactionMethod,
val amounts: Amounts,
val allowTransaction: Boolean = true,
val serviceType: String = "CheckoutDropIn",
// Optional. Omit for guest checkout. Set on your backend for known shoppers.
val customerProfileId: String? = null,
)
@Serializable
data class TransactionMethod(
val intent: Intent
)
@Serializable
data class Intent(
val card: String,
val paypal: String,
val aeropay: String? = null
)
@Serializable
data class Amounts(
val currencyCode: String,
val transactionValue: Double
)
@Serializable
data class SessionResponse(
val sessionId: String,
val hmacKey: String,
val data: String? = null,
val encryptionKey: String,
val locale: String,
val allowedFundingTypes: AllowedFundingTypesDto? = null,
val restrictions: RestrictionsDto? = null
)
@Serializable
data class AllowedFundingTypesDto(
val cards: List<String>? = null,
val cardSchemes: List<String>? = null,
val wallets: WalletsDto? = null,
val payByBanks: PayByBanksDto? = null
)
@Serializable
data class WalletsDto(
val paypal: PayPalWalletDto? = null,
val googlePay: GooglePayWalletDto? = null
)
@Serializable
data class PayByBanksDto(
val aeropay: AeropayFundingDto? = null
)
@Serializable
data class AeropayFundingDto(
val externalMerchantId: String? = null,
val configurationId: String? = null
)
@Serializable
data class PayPalWalletDto(
val allowedFundingOptions: List<String>? = null,
val merchantId: String? = null
)
@Serializable
data class GooglePayWalletDto(
val merchantId: String? = null,
val merchantName: String? = null
)
@Serializable
data class RestrictionsDto(
val card: RestrictionsCardDto? = null
)
@Serializable
data class RestrictionsCardDto(
val ownerTypes: List<String>? = null,
val fundingSources: List<String>? = null
)
private val sessionJson = Json { ignoreUnknownKeys = true }
suspend fun createSession(): SessionResponse {
val client = HttpClient()
// {% step id="build-request-body" %}
val sessionRequest = SessionRequest(
merchant = "MERCHANT-1",
site = "SITE-1",
sessionTimeout = 120,
merchantTransactionId = UUID.randomUUID().toString(),
transactionMethod = TransactionMethod(
intent = Intent(
card = "Authorisation",
paypal = "Purchase",
aeropay = "Authorisation"
)
),
amounts = Amounts(
currencyCode = "USD",
transactionValue = 25.00
),
// Include when the shopper is known. Omit (or leave null) for guest checkout.
customerProfileId = "your-customer-profile-id",
)
// Minify the JSON (no whitespace)
val requestBody = sessionJson.encodeToString(sessionRequest)
// {% /step %}
// {% step id="send-session-request" %}
// Unix seconds — matches create-session.cs and the Android sample SessionDataUtil
val timestamp = (System.currentTimeMillis() / 1000).toString()
val requestId = UUID.randomUUID().toString()
val requestPath = "api/v1/sessions"
val hmac = createHmacSignature(
timestamp = timestamp,
requestId = requestId,
requestPath = requestPath,
requestBody = requestBody,
tokenValue = TOKEN_VALUE
)
val authHeader = "PXP-UST1 $TOKEN_ID:$timestamp:$hmac"
val response: HttpResponse = client.post("https://api-services.pxp.io/api/v1/sessions") {
contentType(ContentType.Application.Json)
headers {
append("X-Client-Id", CLIENT_ID)
append("X-Request-Id", requestId)
append("Authorization", authHeader)
}
setBody(requestBody)
}
// {% /step %}
// {% step id="handle-response" %}
// Return SessionResponse JSON to the Android app. Map to SessionConfig on the client
// with toSessionConfig() in CheckoutActivity.kt.
return sessionJson.decodeFromString<SessionResponse>(response.bodyAsText())
// {% /step %}
}
Wire session data into CheckoutDropInConfig, then create and render Drop-in in your Compose UI.
Import the required dependencies
Import CheckoutDropIn, CheckoutDropInConfig, and the necessary types from the Android SDK. Use com.pxp.checkout.models.SessionConfig, CardIntentType, DropInPayPalIntentType, and DropInAeropayIntentType (when Aeropay is enabled), and com.pxp.checkout.services.models.transaction.Shopper.
Set up your Compose activity
Create a Jetpack Compose activity that will host the Checkout Drop-in interface.
Fetch the session data from your backend
Call your backend endpoint to get the session data you created in the previous steps, and map it to SessionConfig with toSessionConfig(). Include allowedFundingTypes from the response (at minimum a non-null cards array, which may be empty) so that the card UI can render. For Aeropay, also map payByBanks.aeropay. Map optional restrictions when the Sessions API returns them.
Create sessions on your backend with HMAC authentication. Don't call the Sessions API from the Android app or embed PXP_CLIENT_ID, token ID, or token value in the app process. The walkthrough shortcut that calls createSession() from the client is for local exploration only.
Initialise Checkout Drop-in
Configure Drop-in with your environment, SessionConfig, and transaction details.
Configure the transaction data
Specify the currency, amount, entry type, and payment intents for each payment method. Use CardIntentType for card. Import DropInAeropayIntentType when Aeropay is enabled, and set aeropayDropInIntent to DropInAeropayIntentType.Authorisation, Purchase, or EstimatedAuthorisation, as in CheckoutActivity.kt.
Provide a shopper identifier (for card-on-file)
Optionally implement the onGetShopper callback. Card-on-file requires a non-empty Shopper.id when showCOF resolves to true (the default when omitted). This is separate from optional customerProfileId on the session request. See Implementation — Customer Profile.
Use methodConfig.card to show or hide card-on-file and new card entry. See Cards. How Drop-in stores a new card for card-on-file is controlled by site storeCardConsent in the Unity Portal (including ConsentAlreadyObtained when consent was already collected outside Drop-in). See Cards — Store-card consent.
Handle successful payments
Implement the onSuccess callback to handle successful payments. Always verify payments on your backend before fulfilling orders. Frontend callbacks can be manipulated.
Handle payment errors
Implement the onError callback as (PaymentMethod?, BaseSdkException) -> Unit. Use error.errorCode for programmatic handling. paymentMethod is null for initialisation or cross-method errors.
Create the Drop-in component
Call the suspend create() method from a coroutine (for example LaunchedEffect) after initialisation.
Render the Drop-in content
Call checkoutDropIn.Content() to display the payment interface. Prefer this over calling Content() on the create() return value so Drop-in can show its loading UI.
// {% step id="import-dependencies" %}
package com.example.checkout
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.pxp.checkout.checkoutdropin.CheckoutDropIn
import com.pxp.checkout.checkoutdropin.types.CheckoutDropInConfig
import com.pxp.checkout.checkoutdropin.types.PaymentMethod
import com.pxp.checkout.exceptions.BaseSdkException
import com.pxp.checkout.models.AeropayFundingConfig
import com.pxp.checkout.models.AllowedFundingTypes
import com.pxp.checkout.models.CardIntentType
import com.pxp.checkout.models.DropInAeropayIntentType
import com.pxp.checkout.models.DropInPayPalIntentType
import com.pxp.checkout.models.DropInTransactionData
import com.pxp.checkout.models.DropInTransactionIntentData
import com.pxp.checkout.models.Environment
import com.pxp.checkout.models.EntryType
import com.pxp.checkout.models.GooglePayWalletConfig
import com.pxp.checkout.models.PayByBanksConfig
import com.pxp.checkout.models.PayPalWalletConfig
import com.pxp.checkout.models.RestrictionFundingSource
import com.pxp.checkout.models.RestrictionOwnerType
import com.pxp.checkout.models.Restrictions
import com.pxp.checkout.models.RestrictionsCard
import com.pxp.checkout.models.SessionConfig
import com.pxp.checkout.models.WalletsConfig
import com.pxp.checkout.services.models.transaction.Shopper
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
import java.time.Instant
import java.util.UUID
// {% /step %}
// {% step id="setup-activity" %}
class CheckoutActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CheckoutScreen()
}
}
}
}
}
// {% /step %}
@Composable
fun CheckoutScreen() {
val context = LocalContext.current
// {% step id="fetch-session" %}
var sessionConfig by remember { mutableStateOf<SessionConfig?>(null) }
LaunchedEffect(Unit) {
// Fetch session from your backend
sessionConfig = fetchSessionFromBackend()
}
// {% /step %}
// {% step id="initialize-dropin" %}
val checkoutDropIn = remember(sessionConfig) {
sessionConfig?.let { session ->
CheckoutDropIn.initialize(
context = context,
config = CheckoutDropInConfig(
environment = Environment.TEST,
session = session,
ownerType = "MerchantGroup",
ownerId = "MERCHANT-1",
// {% step id="configure-transaction" %}
transactionData = DropInTransactionData(
currency = "USD",
amount = 25.00,
entryType = EntryType.Ecom,
intent = DropInTransactionIntentData(
card = CardIntentType.Authorisation,
paypalDropInIntent = DropInPayPalIntentType.Purchase,
aeropayDropInIntent = DropInAeropayIntentType.Authorisation
),
merchant = "MERCHANT-1",
merchantTransactionId = UUID.randomUUID().toString(),
merchantTransactionDate = { Instant.now().toString() }
),
// {% /step %}
// {% step id="setup-shopper" %}
onGetShopper = {
// id must be non-empty for card-on-file UI
Shopper(id = "shopper-${System.currentTimeMillis()}")
},
// {% /step %}
// {% step id="success-callback" %}
onSuccess = { transactionResult ->
// Payment succeeded
println("Payment successful: ${transactionResult.systemTransactionId}")
// IMPORTANT: Always verify on your backend before fulfilling orders
},
// {% /step %}
// {% step id="error-callback" %}
onError = { paymentMethod: PaymentMethod?, error: BaseSdkException ->
// Handle payment error
println(
"Payment failed [${paymentMethod?.value}]: ${error.errorCode} — ${error.message}"
)
}
// {% /step %}
)
)
}
}
// {% /step %}
// {% step id="create-dropin" %}
LaunchedEffect(checkoutDropIn) {
checkoutDropIn?.create()
}
// {% /step %}
// {% step id="render-content" %}
// Prefer CheckoutDropIn.Content() so Drop-in can show its loading UI
checkoutDropIn?.Content(modifier = Modifier.fillMaxWidth())
// {% /step %}
}
private val httpClient = HttpClient {
install(ContentNegotiation) {
json(Json { ignoreUnknownKeys = true })
}
}
suspend fun fetchSessionFromBackend(): SessionConfig {
// Production: call your backend HTTP endpoint, then map with the client-side extensions below.
val response = httpClient.get("https://your-backend.example/session").body<SessionResponse>()
return response.toSessionConfig()
// Walkthrough shortcut only (not for production): reuse createSession() from create-session.kt
// val response = createSession()
// return response.toSessionConfig()
}
// Android client only — maps backend session DTOs onto SessionConfig from the Android SDK.
fun SessionResponse.toSessionConfig(): SessionConfig =
SessionConfig(
sessionId = sessionId,
hmacKey = hmacKey,
data = data.orEmpty(),
encryptionKey = encryptionKey,
locale = locale,
allowedFundingTypes = allowedFundingTypes?.toAllowedFundingTypes(),
restrictions = restrictions?.toRestrictions(),
)
fun AllowedFundingTypesDto.toAllowedFundingTypes(): AllowedFundingTypes =
AllowedFundingTypes(
cards = cards,
cardSchemes = cardSchemes,
wallets = wallets?.let { wallet ->
WalletsConfig(
paypal = wallet.paypal?.let { paypal ->
PayPalWalletConfig(
allowedFundingOptions = paypal.allowedFundingOptions,
merchantId = paypal.merchantId
)
},
googlePay = wallet.googlePay?.let { googlePay ->
GooglePayWalletConfig(
merchantId = googlePay.merchantId,
merchantName = googlePay.merchantName
)
}
)
},
payByBanks = payByBanks?.let { payByBanks ->
PayByBanksConfig(
aeropay = payByBanks.aeropay?.let { aeropay ->
AeropayFundingConfig(
externalMerchantId = aeropay.externalMerchantId,
configurationId = aeropay.configurationId
)
}
)
}
)
fun RestrictionsDto.toRestrictions(): Restrictions? {
val card = card ?: return null
val ownerTypes =
card.ownerTypes
.orEmpty()
.mapNotNull { raw -> RestrictionOwnerType.fromString(raw.trim()) }
val fundingSources =
card.fundingSources
.orEmpty()
.mapNotNull { raw -> RestrictionFundingSource.fromString(raw.trim()) }
if (ownerTypes.isEmpty() && fundingSources.isEmpty()) {
return null
}
return Restrictions(
card =
RestrictionsCard(
ownerTypes = ownerTypes.takeIf { it.isNotEmpty() },
fundingSources = fundingSources.takeIf { it.isNotEmpty() },
),
)
}
When a payment succeeds, the onSuccess callback fires with transaction details. However, you must always verify the payment on your backend before fulfilling orders.
Configure webhooks in the Unity Portal to receive real-time payment notifications on your backend.
Create the webhook endpoint
Set up an endpoint at /webhooks/pxp to receive payment notifications from Unity.
Verify the webhook signature
Verify the webhook HMAC signature before processing events. Reject unauthenticated requests.
Process webhook events
Loop through the events array and filter for Transaction events.
Check payment state
Verify the transaction state is Authorised or Captured before processing.
Prevent duplicate processing
Check if you've already processed this transaction using systemTransactionId.
Verify transaction details
Match the merchantTransactionId, amount, and currency against your order records.
Fulfil the order
If verification passes, fulfil the order and mark the transaction as processed.
Respond to webhook
Always return { state: 'Success' } to acknowledge receipt, even if processing failed.
You can also verify payments using the Transactions API to query transaction status directly. See the Implementation guide for details.
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
// {% step id="webhook-endpoint" %}
fun Application.configureWebhooks() {
routing {
post("/webhooks/pxp") {
// {% step id="verify-signature" %}
// Verify webhook authenticity using HMAC before processing
if (!verifyWebhookSignature(call)) {
return@post call.respond(HttpStatusCode.Unauthorized)
}
// {% /step %}
val webhookPayload = call.receive<WebhookPayload>()
// {% step id="process-events" %}
webhookPayload.events.forEach { event ->
if (event.type == "Transaction") {
val transaction = event.data as? TransactionData ?: return@forEach
// {% step id="check-state" %}
if (transaction.state in listOf("Authorised", "Captured")) {
// {% /step %}
// {% step id="prevent-duplicates" %}
val alreadyProcessed = checkIfProcessed(transaction.systemTransactionId)
if (alreadyProcessed) {
return@forEach
}
// {% /step %}
// {% step id="verify-details" %}
val order = getOrderByMerchantTransactionId(transaction.merchantTransactionId)
if (order != null &&
order.amount == transaction.amount &&
order.currency == transaction.currency) {
// {% /step %}
// {% step id="fulfill-order" %}
fulfillOrder(order.id)
markTransactionAsProcessed(transaction.systemTransactionId)
// {% /step %}
}
}
}
}
// {% /step %}
// {% step id="respond" %}
call.respond(mapOf("state" to "Success"))
// {% /step %}
}
}
}
// {% /step %}
@Serializable
data class WebhookPayload(
val events: List<WebhookEvent>
)
@Serializable
data class WebhookEvent(
val type: String,
val data: TransactionData
)
@Serializable
data class TransactionData(
val systemTransactionId: String,
val merchantTransactionId: String,
val state: String,
val amount: Double,
val currency: String
)
data class Order(
val id: String,
val merchantTransactionId: String,
val amount: Double,
val currency: String
)
// Placeholder — implement using your Unity webhook signing secret
fun verifyWebhookSignature(call: ApplicationCall): Boolean {
// Verify the webhook HMAC / signature headers from Unity
return true
}
// Placeholder functions - implement these according to your database
fun checkIfProcessed(systemTransactionId: String): Boolean {
// Check your database to see if this transaction was already processed
return false
}
fun getOrderByMerchantTransactionId(merchantTransactionId: String): Order? {
// Retrieve order from your database
return null
}
fun fulfillOrder(orderId: String) {
// Fulfill the order (ship product, grant access, etc.)
}
fun markTransactionAsProcessed(systemTransactionId: String) {
// Mark transaction as processed in your database to prevent duplicates
}
That's it! You now have a working Checkout Drop-in integration.
Now that you have Drop-in running, here are the recommended next steps:
- Customise the look and feel to match your brand (configured in the Unity Portal).
- Configure card display to show or hide card-on-file and new card entry.
- Enable Aeropay for USD pay-by-bank payments when Aeropay is enabled in your session.
- Set up backend verification to verify payments before fulfilling orders.
- Add optional callbacks to enhance the user experience with validation and loading states.