Skip to navigation

Pay In

Beta
Natively add card and ACH payments to your mobile app with the Pay In component
View as MarkdownOpen in Claude
Applies to:Developers

The Pay In component is Payabli’s native mobile UI for card and ACH payments in your app. It owns sensitive field state and renders a hosted form. See Tap to Pay if you’re looking for Payabli’s contactless payment component instead.

The component is available for iOS and Android. Where steps differ by platform, open the iOS or Android section.

Prerequisites

The requirements cover your build tools, your Payabli sandbox paypoint, and the OAuth permissions for each operation:

Before you start, confirm you have:

  • Xcode 15 or later and Swift 5.9 or later
  • iOS 16.0 or later as your deployment target
  • A Payabli sandbox entryPoint with card and ACH enabled
  • A Payabli clientId and clientSecret with a permission for each operation you use. See OAuth authentication to provision them.
OperationPermission
.capture, .authorize, capture(_:), authorize(_:), captureAuthorizedTransaction(_:)inboundpayments_create
voidTransaction(_:)inboundpayments_void
readTransaction(_:)inboundpayments_read
.storePaymentMethod, addCard(_:options:), addBankAccount(_:options:), addPaymentMethod(_:options:)tokens_create

Before you start, confirm you have:

  • minSdk 23 or later and compileSdk 31 or later. The form’s Compose dependencies can require a higher compileSdk. If yours is too low, the Gradle error names the version you need.
  • Jetpack Compose, to render the Pay In form
  • Payabli Maven repository credentials. Contact your Payabli representative to get them.
  • A Payabli sandbox entryPoint with card and ACH enabled
  • A Payabli clientId and clientSecret with a permission for each operation you use. See OAuth authentication to provision them.
OperationPermission
Capture, Authorize, capture, authorize, captureAuthorizedTransactioninboundpayments_create
voidTransactioninboundpayments_void
readTransactioninboundpayments_read
StoreMethod, storeMethodtokens_create

Installation

Install the Pay In component from the sdk-ios Swift package on iOS, or from Payabli’s Maven repository on Android:

Install PayabliSDKPayIn from the sdk-ios Swift package. These docs cover version 0.2.0. A later version can change the code that these docs show, so install 0.2.0:

1

Add the package

In Xcode, choose File → Add Package Dependencies… and enter the sdk-ios repository URL. Then choose the Exact Version dependency rule and enter 0.2.0:

https://github.com/payabli/sdk-ios.git

Or add it to your Package.swift dependencies:

.package(url: "https://github.com/payabli/sdk-ios.git", exact: "0.2.0")

Your app’s deployment target must be iOS 16.0 or later. Tap to Pay needs iOS 16.7 or later.

3

Import the modules

Import PayabliSDKCore, which holds the configuration types, and PayabliSDKPayIn where you construct or render the component:

import PayabliSDKCore
import PayabliSDKPayIn

The SDK sends error and usage events to Payabli. The events contain no card, payor, or account data. You can’t turn this off. The SDK’s privacy manifests declare what each module collects. PayabliSDKCore declares device ID, performance data, other diagnostic data, and product interaction, linked to the user, for app functionality and analytics. PayabliSDKPayIn declares payment info, name, email address, and user ID, linked to the user, for app functionality. None of this data is used for tracking. Regenerate your app’s privacy report in Xcode before you update your app’s App Store privacy details.

Install sdk-android-payin from Payabli’s Maven repository. These docs cover version 0.2.0. A later version can change the code that these docs show, so install 0.2.0:

1

Add the repository

Payabli hosts the SDK in its own Maven repository.

Payabli’s Maven repository requires credentials. Get them from your Payabli representative before you add the repository, or the build can’t download the SDK.

Add the repository to settings.gradle.kts. The content block limits the repository to the groups that Payabli hosts there:

// settings.gradle.kts
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven {
url = uri("https://sdk.payabli.com/maven")
content {
includeGroup("com.payabli")
}
credentials {
username = providers.gradleProperty("payabli.maven.user").orNull
password = providers.gradleProperty("payabli.maven.password").orNull
}
authentication { create<BasicAuthentication>("basic") }
}
}
}

Keep payabli.maven.user and payabli.maven.password in ~/.gradle/gradle.properties or a secret store for your CI builds. Never commit them to your repository.

2

Add the dependency

Add sdk-android-payin to your app module’s build.gradle.kts:

// app/build.gradle.kts
dependencies {
implementation("com.payabli:sdk-android-payin:0.2.0")
}

sdk-android-payin includes sdk-android-core, which holds the session and configuration types, so you don’t need to add sdk-android-core separately.

To use the Pay In and Tap to Pay components in the same app, add com.payabli:sdk-android instead. It includes both components and requires minSdk 30. Add includeGroup("com.fiserv.ch") and includeGroup("com") to the repository’s content block as well, because the card reader library comes from those groups. Tap to Pay also needs the setup in Tap to Pay installation.

3

Declare the INTERNET permission

sdk-android-payin doesn’t declare the INTERNET permission. Add it to your app’s manifest:

<uses-permission android:name="android.permission.INTERNET" />

If your app also includes Tap to Pay, you can skip this step. Tap to Pay declares the permission for you.

The SDK sends error and usage events to Payabli. The events contain no card, payor, or account data. You can’t turn this off. For Google Play’s Data safety form, note that the SDK collects device or other IDs, app interactions, and diagnostics. sdk-android-payin also collects financial info, and personal info from PayabliPayInForm: name, email address, and user IDs. None of this data is shared or used for tracking.

Backend token endpoint

The Pay In component authenticates every request with a short-lived Payabli access token, obtained through a tokenProvider function you implement. Your backend holds the Payabli clientId and clientSecret, exchanges them for the access token, and never exposes them to your mobile app.

1

Create the project

This example server uses JavaScript with Node.js and Express.

Requires: Node.js 18 or later, and npm

Create a new Node.js project and enable ES modules:

mkdir payabli-token-proxy
cd payabli-token-proxy
npm init -y
npm pkg set type=module
2

Install dependencies

Install Express and dotenv:

npm install express dotenv
3

Write the token endpoint

Create server.js with the following. It returns the token as { "accessToken": "..." }:

// server.js
import "dotenv/config";
import express from "express";
const app = express();
const PAYABLI_URL = process.env.PAYABLI_URL ?? "https://api-sandbox.payabli.com/api";
// Replace with your app's own check of the caller's session. This example
// accepts a single development credential from APP_SESSION_TOKEN.
async function authenticateUser(req) {
const expected = process.env.APP_SESSION_TOKEN;
if (!expected || req.get("Authorization") !== `Bearer ${expected}`) {
return null;
}
return { id: "dev-user" };
}
// Replace with your app's own rule for who may take payments for this paypoint.
async function mayTakePayments(user) {
return true;
}
app.post("/payabli/token", async (req, res) => {
// Never return a token to a caller you haven't authenticated.
const user = await authenticateUser(req);
if (!user) {
return res.status(401).json({ error: "unauthenticated" });
}
if (!(await mayTakePayments(user))) {
return res.status(403).json({ error: "forbidden" });
}
let accessToken;
try {
const upstream = await fetch(`${PAYABLI_URL}/v2/token/serverside`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
clientId: process.env.PAYABLI_CLIENT_ID,
clientSecret: process.env.PAYABLI_CLIENT_SECRET,
}),
redirect: "error", // Never send the client secret to another origin.
signal: AbortSignal.timeout(10_000), // Well inside the SDK's 30-second limit.
});
const body = await upstream.json();
accessToken = upstream.ok ? (body.access_token ?? body.accessToken) : undefined;
} catch {
// A timeout, a redirect, a network failure, or a response that isn't JSON.
}
if (!accessToken) {
return res.status(502).json({ error: "token exchange failed" });
}
res.set("Cache-Control", "no-store").json({ accessToken });
});
app.listen(process.env.PORT ?? 3000, () => console.log("Token server ready"));

Create a .env file next to server.js with your credentials:

PAYABLI_CLIENT_ID=<your sandbox client ID>
PAYABLI_CLIENT_SECRET=<your sandbox client secret>
APP_SESSION_TOKEN=<a long random string your app sends as a bearer token>

Anyone who can call this route gets a token that can charge, store payment methods, and void for your paypoint. Before you go live, replace authenticateUser and mayTakePayments with the same session and permission checks the rest of your app uses.

Keep clientId and clientSecret on your server, in environment variables or a secret store. Never commit .env to source control.

4

Start the server

Start the server:

node server.js
5

Call it from your app

Pass a tokenProvider that calls this endpoint and returns the token when you start the session:

let session = try await PayabliSession.initialize(config: PayabliConfig(
entryPoint: "your-entry-point",
environment: .sandbox,
tokenProvider: { try await backend.fetchPayabliAccessToken() }
))

A call that takes longer than 30 seconds, throws, or returns a token the SDK can’t use fails with PayabliErrorType.tokenProviderFailed. If Payabli refuses the new token too, the call fails with .tokenExpired (1002). The SDK doesn’t retry .tokenProviderFailed or .tokenExpired itself.

val session =
PayabliSession.initialize(
PayabliConfig(
entryPoint = "your-entry-point",
environment = PayabliEnvironment.SANDBOX,
tokenProvider = { backend.fetchPayabliAccessToken() },
),
HostBindings(applicationContext),
)

A call that takes longer than 30 seconds, throws, or returns a token the SDK can’t use fails with PayabliErrorType.TOKEN_PROVIDER_FAILED. initialize and the token provider are suspend functions, so call initialize from a coroutine. Don’t catch CancellationException in the provider. The SDK doesn’t retry TOKEN_PROVIDER_FAILED or TOKEN_EXPIRED itself. Try again only when the user asks, or wait longer between attempts.

The SDK calls the token provider before its first request, and again when a token is rejected. Return a newly minted token each time. Concurrent callers share one call, so you don’t need to cache the token or schedule refreshes yourself. Don’t wait in the provider on an SDK call that needs a new token, because it can’t finish until the provider returns.

Anyone who can call your token endpoint gets a token that can charge, store payment methods, and void for your paypoint. Authenticate the caller and check that they’re allowed to take payments before you return a token.

Operations

The Pay In form has three operations:

  • Store a payment method — Tokenizes a card or ACH account for later use, without charging it.
  • Capture — Authorizes and captures a card or ACH payment in one step.
  • Authorize — Authorizes a card payment without capturing it. The form offers card only in this mode.

PayabliPayIn’s operation parameter selects the hosted form’s behavior: .storePaymentMethod (the default), .capture, or .authorize.

PayabliPayIn also exposes direct methods for building your own UI: capture(_:), authorize(_:), captureAuthorizedTransaction(_:), voidTransaction(_:), readTransaction(_:), addCard(_:options:), addBankAccount(_:options:), and addPaymentMethod(_:options:). capture(_:) and authorize(_:) take a PayabliPayInRequest(paymentMethod:options:). readTransaction(_:) reads a transaction so you can check a payment whose outcome is unknown. These methods take card and bank details as String values in PayabliPayInCardData and PayabliPayInBankAccountData, so your app holds the raw values.

PayabliPayInForm’s operation parameter selects the form’s behavior: PayabliPayInOperation.StoreMethod(options), PayabliPayInOperation.Capture(options), or PayabliPayInOperation.Authorize(options).

PayabliPayIn also exposes direct suspend methods for building your own UI: capture(request), authorize(request), captureAuthorizedTransaction(request), voidTransaction(transId), readTransaction(transId), and storeMethod(request). readTransaction reads a transaction so you can check a payment whose outcome is unknown. These methods take card numbers, security codes, and bank account numbers in SensitiveDigits buffers. Collect the digits into a CharArray, never a String. SensitiveDigits.of copies the array, so overwrite your array as soon as you build the buffer. Wrap each buffer in use, which erases the buffer when the block returns:

val number = SensitiveDigits.of(numberChars).also { numberChars.fill('0') }
// requestWith is your own function that builds a PayInRequest around the buffer.
val result = number.use { payIn.capture(requestWith(it)) }

If you collect card data in your own UI and pass it to the direct methods, your app handles card numbers and security codes. That puts your app in scope for PCI DSS. The form keeps that data out of your app.

Implementation walkthrough

This walkthrough builds a minimal card or ACH capture, from constructing PayabliPayIn through rendering the form:

Loading walkthrough content

Loading walkthrough...

Loading walkthrough...

/// Add the imports

Import PayabliSDKCore, which holds the session and configuration types, and PayabliSDKPayIn. Then create a view model that holds the component. You can use your own API client and view model patterns. This walkthrough uses a minimal ObservableObject.

/// Implement the backend token provider

Add a function that calls your backend’s token endpoint and returns a Payabli access token. Your backend holds the Payabli clientSecret, not the app. In production, send your app’s own session credential with this request so your token endpoint can authenticate the caller.

/// Start the session

Start one PayabliSession with your entrypoint, environment, and token provider before you build a component. PayabliConfig throws if the entrypoint is blank. Start the session once: calling initialize again with the same settings returns the same session, and different settings throw invalidConfiguration. If Payabli refuses the session’s credential for good (tokenExpired), calling initialize again starts a new session. Pay In and Tap to Pay both run on this session.

/// Create the Pay In component

Construct PayabliPayIn on the session with the .capture operation and a requestConfiguration that describes the amount to charge. Identify the payor in customerData, because a paypoint can require customer identifiers and refuses a charge without them with E7020. Set orderId to your own order reference so you can find the transaction if its outcome is unknown.

/// Render the hosted form and handle the result

Add a view that renders PayabliPayInView and handles the result. The hosted form collects card or ACH details itself. Your view never sees raw card data. A returned result means that the payor was charged. If it has no transaction ID, find the transaction by orderId. If the error is PayabliPayInError.submissionInterrupted, the outcome is unknown. The error carries a paymentTransId when Payabli returned one. Read that transaction with readTransaction(_:), or find it by orderId, before you let the payor try again. The form shows the payor its own message for every error, so your onError handler only needs to reconcile and log.

import SwiftUI
import PayabliSDKCore
import PayabliSDKPayIn
func fetchPayabliAccessToken() async throws -> String {
var request = URLRequest(url: URL(string: "https://your-backend.example.com/payabli/token")!)
request.httpMethod = "POST"
// Your app's own session credential, which your token endpoint verifies.
request.setValue("Bearer \(yourSessionToken)", forHTTPHeaderField: "Authorization")
struct Response: Decodable { let accessToken: String }
let (data, _) = try await URLSession.shared.data(for: request)
return try JSONDecoder().decode(Response.self, from: data).accessToken
}
func startPayabliSession(entryPoint: String) async throws -> PayabliSession {
try await PayabliSession.initialize(config: PayabliConfig(
entryPoint: entryPoint,
environment: .sandbox,
tokenProvider: { try await fetchPayabliAccessToken() }
))
}
@MainActor
final class CheckoutViewModel: ObservableObject {
let payIn: PayabliPayIn
init(session: PayabliSession, orderId: String) {
payIn = PayabliPayIn(
session: session,
operation: .capture,
requestConfiguration: PayabliPayInRequestConfiguration(
paymentDetails: PayabliPayInPaymentDetails(
totalAmount: 1.00,
currency: "USD"
),
customerData: PayabliPayInCustomerData(
customerNumber: "C-1001",
firstName: "Jane",
lastName: "Doe"
),
orderDescription: "iOS checkout",
orderId: orderId,
source: "ios-sdk"
)
)
}
}
struct CheckoutView: View {
@StateObject var viewModel: CheckoutViewModel
var body: some View {
PayabliPayInView(
component: viewModel.payIn,
configuration: PayabliPayInFormConfiguration(),
onCompleted: { result in
guard let paymentTransId = result.transaction?.paymentTransId else {
// The payment was charged, but no transaction ID came back.
// Find the transaction by orderId to get its ID.
reconcileByOrderId()
return
}
// Store paymentTransId with your order record. Don't log it.
saveTransactionId(paymentTransId)
},
onError: { error in
if case let .submissionInterrupted(_, _, paymentTransId, _) = error as? PayabliPayInError {
// The outcome is unknown, and the payor may have been charged.
// Read the transaction with readTransaction(_:), or find it
// by orderId when there's no ID, before another attempt.
reconcile(paymentTransId: paymentTransId)
return
}
// The form already shows the payor a message for this error.
// Log only the code. Don't log localizedDescription.
logFailure(code: (error as? any PayabliError)?.code)
}
)
}
}
Loading walkthrough content

Loading walkthrough...

Loading walkthrough...

/// Add the imports

Import the core session and configuration types from com.payabli.sdk.core, and the Pay In types from com.payabli.sdk.payin. You can use your own API client and view model patterns. This walkthrough uses a minimal ViewModel and a composable screen.

/// Implement the backend token provider

Add a suspend function that calls your backend’s token endpoint and returns a Payabli access token. Your backend holds the Payabli clientSecret, not the app. In production, send your app’s own session credential with this request so your token endpoint can authenticate the caller.

/// Start the session

Start one PayabliSession with your entrypoint, environment, and token provider before you build a component. PayabliConfig throws if the entrypoint is blank. Start the session once. Calling initialize again with the same settings returns the same session. Different settings throw a PayabliException whose type is INVALID_CONFIGURATION. Pay In and Tap to Pay both run on this session. initialize is a suspend function, so call it from a coroutine.

/// Create the Pay In component

Construct PayabliPayIn in a ViewModel, and pass the view model’s viewModelScope. The component and any running submission then keep working after configuration changes, such as a screen rotation. Set the operation to PayabliPayInOperation.Capture. Identify the payor in customerData, because a paypoint can require customer identifiers and refuses a charge without them with E7020. Set orderId to your own order reference so you can find the transaction if its outcome is unknown. Set paymentReference to your own identifier for the payment. Store the operation in Compose state. After an unknown outcome, you can then replace it with an operation that sets attempt = PayabliAttempt.Retry. A retry resends the earlier payment’s idempotency key, so Payabli doesn’t charge the payor twice.

/// Render the form and handle the result

Add a composable that renders PayabliPayInForm and handles the result. The form collects card or ACH details itself. Your code never sees raw card data. A success means that the payor was charged. If the result has no transaction ID, find the transaction by orderId and store its ID. If the failure’s cause is PayInException.Unsettled, the outcome is unknown. When cause.paymentTransId is set, read the transaction with readTransaction and check its status. If the payment wasn’t charged, start a new payment with a new paymentReference. If its outcome is still unknown, send the next submission as a retry with the paymentReference that Unsettled returns. Hide the form until you resolve the earlier payment, even when the read fails. Otherwise, the payor can submit a new payment that charges again.

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.payabli.sdk.core.HostBindings
import com.payabli.sdk.core.PayabliSession
import com.payabli.sdk.core.config.PayabliConfig
import com.payabli.sdk.core.config.PayabliEnvironment
import com.payabli.sdk.core.model.PayabliAttempt
import com.payabli.sdk.core.model.PayabliErrorType
import com.payabli.sdk.payin.PayabliPayIn
import com.payabli.sdk.payin.PayabliPayInForm
import com.payabli.sdk.payin.form.PayInFormConfiguration
import com.payabli.sdk.payin.model.PayInCustomerData
import com.payabli.sdk.payin.model.PayInException
import com.payabli.sdk.payin.model.PayInPaymentDetails
import com.payabli.sdk.payin.model.PayInTransactionOptions
import com.payabli.sdk.payin.model.PayInTransactionStatus
import com.payabli.sdk.payin.payment.PayInSubmissionState
import com.payabli.sdk.payin.payment.PayabliPayInOperation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.math.BigDecimal
import java.net.HttpURLConnection
import java.net.URL
import java.util.UUID
suspend fun fetchPayabliAccessToken(): String =
withContext(Dispatchers.IO) {
val url = URL("https://your-backend.example.com/payabli/token")
val connection = url.openConnection() as HttpURLConnection
try {
connection.requestMethod = "POST"
// Your app's own session credential, which your token endpoint verifies.
connection.setRequestProperty("Authorization", "Bearer $yourSessionToken")
check(connection.responseCode == HttpURLConnection.HTTP_OK) {
"Token endpoint returned ${connection.responseCode}"
}
val body = connection.inputStream.bufferedReader().use { it.readText() }
JSONObject(body).getString("accessToken")
} finally {
connection.disconnect()
}
}
suspend fun startPayabliSession(context: Context, entryPoint: String): PayabliSession =
PayabliSession.initialize(
PayabliConfig(
entryPoint = entryPoint,
environment = PayabliEnvironment.SANDBOX,
tokenProvider = { fetchPayabliAccessToken() },
),
HostBindings(context.applicationContext),
)
class CheckoutViewModel(session: PayabliSession, entryPoint: String, private val orderId: String) : ViewModel() {
val payIn = PayabliPayIn(session, entryPoint = entryPoint, scope = viewModelScope)
// Compose state, so the form submits the operation that you set last.
var operation by mutableStateOf(capture(UUID.randomUUID().toString(), PayabliAttempt.NewPayment))
private set
// True while an earlier payment's outcome is unknown. Checkout stays hidden until it's resolved.
var reconciling by mutableStateOf(false)
private set
private fun capture(paymentReference: String, attempt: PayabliAttempt) =
PayabliPayInOperation.Capture(
PayInTransactionOptions(
paymentDetails = PayInPaymentDetails(totalAmount = BigDecimal("1.00"), currency = "USD"),
customerData = PayInCustomerData(customerNumber = "C-1001", firstName = "Jane", lastName = "Doe"),
orderId = orderId,
orderDescription = "Android checkout",
source = "android-sdk",
// Your own name for this payment. The SDK never sends it.
paymentReference = paymentReference,
attempt = attempt,
),
)
// The outcome is unknown, and the payor may have been charged.
fun onUnknownOutcome(cause: PayInException.Unsettled) {
reconciling = true
val paymentTransId = cause.paymentTransId
if (paymentTransId == null) {
// No transaction ID came back. Find the transaction by orderId
// in the Payabli Portal before you charge again.
reconcileByOrderId()
return
}
viewModelScope.launch {
val transaction =
payIn.readTransaction(paymentTransId).getOrElse {
// A failed read, such as TRANSACTION_NOT_FOUND, says nothing about the payment.
// Read the transaction again later. Don't charge again.
return@launch
}
when (transaction.status) {
// Charged. Checkout stays hidden, because the order is paid.
PayInTransactionStatus.Captured -> saveTransactionId(paymentTransId)
// Not charged. The next submission is a new payment under a new reference.
PayInTransactionStatus.Declined, PayInTransactionStatus.Voided, PayInTransactionStatus.Blocked -> {
operation = capture(UUID.randomUUID().toString(), PayabliAttempt.NewPayment)
reconciling = false
}
// Still unknown. The next submission retries the same payment.
else -> retry(cause)
}
}
}
private fun retry(cause: PayInException.Unsettled) {
// RETRY_REFUSED means Payabli already has this payment. Read it back later instead.
if (cause.type == PayabliErrorType.RETRY_REFUSED) return
val paymentReference = cause.paymentReference ?: return
operation = capture(paymentReference, PayabliAttempt.Retry)
reconciling = false
}
}
@Composable
fun CheckoutScreen(viewModel: CheckoutViewModel) {
// Show your own status here instead, so the payor can't submit again.
if (viewModel.reconciling) return
PayabliPayInForm(
payIn = viewModel.payIn,
operation = viewModel.operation,
configuration = PayInFormConfiguration(),
onCompleted = { succeeded ->
if (succeeded is PayInSubmissionState.Succeeded.Payment) {
val paymentTransId = succeeded.result.transaction?.paymentTransId
if (paymentTransId == null) {
// The payment was charged, but no transaction ID came back.
// Find the transaction by orderId to get its ID.
reconcileByOrderId()
} else {
// Store paymentTransId with your order record. Don't log it.
saveTransactionId(paymentTransId)
}
}
},
onFailed = { failed ->
val cause = failed.cause
if (cause is PayInException.Unsettled) {
viewModel.onUnknownOutcome(cause)
} else {
// Show cause.reason to the payor. Don't log it, because it can repeat
// what was submitted. Log cause.code instead.
showError(cause.reason)
}
},
onMethodChanged = { },
)
}

Implementation reference

The form’s configuration controls its fields, labels, and layout. The request configuration carries the data sent with each operation.

Form configuration

The form configuration controls which fields the form shows, how it groups and labels them, and how it formats input:

PayabliPayInFormConfiguration controls the hosted form’s fields, labels, and layout for every operation. Its options carry the data that the form sends when it stores a payment method. Its hiddenValues carry values that the form submits without showing a field. The hosted form is shared by all three operations. See Operations for what each one does.

allowedMethods
array[string]Defaults to [.card, .bankAccount]

Hosted methods the payor can select. For .authorize, the form offers card only. When the payor switches methods, the form clears the fields that only the other method shows.

defaultMethod
stringDefaults to .card

Initial selected method. Falls back to the first allowed method if .card isn’t allowed.

cardSections
array[object]

Custom section grouping for card fields. Required and payment-summary fields are appended automatically if missing.

id
string

Optional stable identifier. Defaults to the section title or its joined field names.

title
string

Section title, for example Card Information.

titleStyle
object

Per-section text style override.

fields
array[string]Required

Ordered PayabliPayInField values in this section.

inputVerticalSpacing
number

Vertical spacing between inputs in this section.

inputHorizontalSpacing
number

Horizontal spacing for paired inputs in this section.

fieldVerticalSpacings
object

Per-field vertical spacing overrides, keyed by field.

style
stringDefaults to .inputs

.inputs for a section of input fields, or .summary for the section that shows the operation’s amounts. A capture or authorize form without a .summary section gets one. A .summary section with no title has the heading Payment. An .inputs section with no title has no heading.

bankSections
array[object]

Custom section grouping for ACH fields. .secCode is never rendered, even if listed.

id
string

Optional stable identifier. Defaults to the section title or its joined field names.

title
string

Section title, for example Card Information.

titleStyle
object

Per-section text style override.

fields
array[string]Required

Ordered PayabliPayInField values in this section.

inputVerticalSpacing
number

Vertical spacing between inputs in this section.

inputHorizontalSpacing
number

Horizontal spacing for paired inputs in this section.

fieldVerticalSpacings
object

Per-field vertical spacing overrides, keyed by field.

style
stringDefaults to .inputs

.inputs for a section of input fields, or .summary for the section that shows the operation’s amounts. A capture or authorize form without a .summary section gets one. A .summary section with no title has the heading Payment. An .inputs section with no title has no heading.

cardFieldOrder
array[string]

Flat card field order, used only when cardSections is nil.

bankFieldOrder
array[string]

Flat ACH field order, used only when bankSections is nil.

hiddenValues
object

Values submitted with the form without rendering an editable field. The form also sends its ACH values and customerData with captures and authorizations. Its methodDescription replaces orderDescription on a charge.

accountHolderType
string

.personal or .business.

secCode
stringDefaults to .web

.ppd, .web, .tel, .ccd, or .boc.

deviceId
string
methodDescription
string
customerData
object

Default or hidden customer data, merged with any visible customer fields.

firstName
string
lastName
string
customerNumber
string
customerId
Int64
company
string
billingEmail
string
billingPhone
string
billingAddress1
string
billingAddress2
string
billingCity
string
billingState
string
billingZip
string
billingCountry
string
shippingAddress1
string
shippingAddress2
string
shippingCity
string
shippingState
string
shippingZip
string
shippingCountry
string
identifierFields
array[string]

Custom identifier fields, when the paypoint uses custom identifiers instead of name, email, or customer ID.

additionalData
object
options
object

Options sent when the form stores a payment method with .storePaymentMethod. These correspond to the options of Save a payment method.

achValidation
boolean
createAnonymous
boolean
forceCustomerCreation
boolean
temporary
boolean
customerData
object
firstName
string
lastName
string
customerNumber
string
customerId
Int64
company
string
billingEmail
string
billingPhone
string
billingAddress1
string
billingAddress2
string
billingCity
string
billingState
string
billingZip
string
billingCountry
string
shippingAddress1
string
shippingAddress2
string
shippingCity
string
shippingState
string
shippingZip
string
shippingCountry
string
identifierFields
array[string]

Custom identifier fields, when the paypoint uses custom identifiers instead of name, email, or customer ID.

additionalData
object
vendorData
object

vendorId and vendorNumber.

fallbackAuth
boolean
fallbackAuthAmount
number
methodDescription
string
source
string
subdomain
string
validation
object

Client-side validation, run before a request is sent. Same fields and defaults as validation in PayabliPayInRequestConfiguration. On a store form, validation in requestConfiguration replaces it.

labels
object

Title, subtitle, submit button text, field labels, and placeholders.

title
string

Form title. Unset by default, so the form shows no title.

subtitle
string
submitButton
string

Submit button text. Unset by default, so the button names the operation: Pay for .capture, Authorize for .authorize, and Save for .storePaymentMethod. While a submission runs, the button shows the operation in progress, such as Paying….

fieldLabels
object

Visible and accessibility label text, keyed by PayabliPayInField.

fieldPlaceholders
object

Placeholder text, keyed by PayabliPayInField.

total
stringDefaults to Total

Label on the payment summary’s Total row.

labelLayout
stringDefaults to .external

.external shows visible labels. .placeholder uses placeholder-first inputs.

showsFieldLabels
boolean

Global visible-label override. Leave unset to follow labelLayout.

hiddenFieldLabels
array[string]

Fields to hide the visible label for. Accessibility labels are unaffected.

formatting
objectDefaults to card spaces on, / separator, ACH masking on

Card number spacing, expiration separator, and ACH account masking.

insertsCardNumberSpaces
booleanDefaults to true

Adds visual card number grouping.

expirationSeparator
stringDefaults to /

Separator used in expiration entry. An empty string resolves to /.

masksAccountNumber
booleanDefaults to true

Masks ACH account number entry in the hosted field. The routing number isn’t masked.

inputSizing
objectDefaults to 52pt height, 14pt padding

Default and per-field input sizes. Height is clamped to the accessibility minimum touch target.

defaultSize
object

Default PayabliPayInInputSize: optional width, height (default 52), and horizontalPadding (default 14).

fieldSizes
object

Per-field PayabliPayInInputSize overrides, keyed by PayabliPayInField.

cardBrandIconPlacement
stringDefaults to .trailing

.leading, .trailing, or .hidden.

errorMessagePlacement
stringDefaults to .aboveSubmitButton

.top or .aboveSubmitButton. The form shows the payor a fixed message for the failure’s category, never the SDK’s error text. A failed save shows a message about saving. When Payabli rejects a specific field, the form marks that field instead of showing a message.

requiredFields
array[string]

Optional visible fields to require. .amount is always required.

showsBaseAmount
booleanDefaults to true

Whether the payment summary shows the Amount row.

paymentSummary
object

Text styles and spacing for the read-only amount and fee rows on capture and authorize forms. Forms that store a payment method leave the rows out. The row labels come from labels.fieldLabels for .amount, .serviceFee, and .surchargeFee, and the Total row’s label from labels.total. The Total row shows totalAmount, which already includes any surcharge. The Amount row shows totalAmount minus the service fee and the surcharge.

labelStyle
objectDefaults to subheadline, secondary color

Font and color for the label text.

valueStyle
objectDefaults to subheadline (semibold), primary color

Font and color for the value text.

rowSpacing
numberDefaults to 8
PayabliPayInField
enum

Card, ACH, customer, and payment-summary fields available for fields, cardFieldOrder, bankFieldOrder, requiredFields, and hiddenFieldLabels.

.cardholderName
case
Name on card. Card field.
.cardNumber
case
Card number. Card field.
.cardExpiration
case
Expiration. Card field.
.cardCvv
case
CVV. Card field.
.cardZip
case
Postal code. Card field.
.accountHolder
case
Account holder. ACH field.
.routingNumber
case
Routing number. ACH field.
.accountNumber
case
Account number. ACH field.
.accountType
case
Account type. ACH field.
.accountHolderType
case
Holder type. ACH field, or hidden value.
.secCode
case
SEC code. Hidden by default, and bankSections doesn’t render it.
.deviceId
case
Device. Optional ACH metadata.
.methodDescription
case
Description. Stored-method metadata.
.firstName
case
First name. Customer field.
.lastName
case
Last name. Customer field.
.customerNumber
case
Customer number. Customer field.
.billingEmail
case
Billing email. Customer field.
.billingZip
case
Billing postal code. Customer field.
.amount
case
Amount. Read-only payment summary field.
.serviceFee
case
Fee. Read-only payment summary field.
.surchargeFee
case
Surcharge. Read-only payment summary field.

Construct PayabliPayIn on the session, then render it with PayabliPayInForm:

val payIn = PayabliPayIn(session, entryPoint = "your-entry-point", scope = viewModelScope)

PayabliPayIn takes three values: the session, the paypoint’s entryPoint, and a CoroutineScope. Use a scope that survives configuration changes, such as a screen rotation. A ViewModel’s viewModelScope works. If your app creates PayabliPayIn again when the activity is re-created, the form loses the result of a submission that’s still running.

PayabliPayInForm takes these parameters:

payIn
PayabliPayInRequired

The PayabliPayIn component that the form submits through.

operation
PayabliPayInOperationRequired

The operation that the form runs when the payor submits it: StoreMethod(options), Capture(options), or Authorize(options). See Operations.

configuration
PayInFormConfigurationRequired

The form’s fields, sections, and layout, described later in this section.

modifier
ModifierDefaults to Modifier

A Compose Modifier for the form.

labels
PayInFormLabels

Title, subtitle, submit button text, field labels, and placeholders.

title
String

Form title. Unset by default, so the form shows no title.

subtitle
String
submitButton
String

Submit button text. Unset by default, so the button names the operation: Pay for Capture, Authorize for Authorize, and Save for StoreMethod. While a submission runs, the button shows the operation in progress, such as Paying….

fieldLabels
Map<PayInField, String>

Visible and accessibility label text, keyed by PayInField.

fieldPlaceholders
Map<PayInField, String>

Placeholder text, keyed by PayInField.

total
StringDefaults to Total

Label on the payment summary’s Total row.

style
PayInFormStyle

Overrides the form’s style. See Style.

onCompleted
(PayInSubmissionState.Succeeded) -> UnitRequired

Called when a submission succeeds. For Capture and Authorize, the value is Succeeded.Payment, and its result is a PayInResult. For StoreMethod, the value is Succeeded.Method, and its storedMethod is a PayInStoredMethod.

onFailed
(PayInSubmissionState.Failed) -> UnitRequired

Called when a submission fails. See Outcomes and errors.

onMethodChanged
(PayInMethodType) -> UnitRequired

Called when the payor switches between Card and BankAccount.

PayInFormConfiguration controls the form’s fields, sections, and layout for every operation. It takes these fields:

allowedMethods
List<PayInMethodType>Defaults to [Card, BankAccount]

Methods the payor can select. For Authorize, the form offers card only.

defaultMethod
PayInMethodTypeDefaults to Card

Initial selected method. If it isn’t in allowedMethods, the form selects the first allowed method.

cardSections
List<PayInFormSection>Defaults to defaultCardSections()

The card fields in each section, in order. defaultCardSections() returns cardholder name, card number, expiration, security code, and postal code. A summary section with the amounts follows them.

fields
List<PayInField>Required

Ordered PayInField values in this section.

title
String

Section title, for example Card Information.

style
PayInSectionStyleDefaults to Inputs

Inputs for a section of input fields, or Summary for the section that shows the operation’s amounts. A Summary section can list only Amount, ServiceFee, and SurchargeFee. A Summary section with no title, or a blank one, has the heading Payment. An Inputs section with no title, or a blank one, has no heading.

bankSections
List<PayInFormSection>Defaults to defaultBankSections()

The ACH fields in each section, in order. defaultBankSections() returns account holder, routing number, account number, and account type. A summary section with the amounts follows them.

fields
List<PayInField>Required

Ordered PayInField values in this section.

title
String

Section title, for example Card Information.

style
PayInSectionStyleDefaults to Inputs

Inputs for a section of input fields, or Summary for the section that shows the operation’s amounts. A Summary section can list only Amount, ServiceFee, and SurchargeFee. A Summary section with no title, or a blank one, has the heading Payment. An Inputs section with no title, or a blank one, has no heading.

requiredFields
Set<PayInField>

Optional visible fields to require. The form already requires every visible field except MethodDescription, CustomerNumber, DeviceId, and the summary fields.

labelLayout
PayInLabelLayoutDefaults to External

External shows labels above the fields. Placeholder uses Material floating labels.

hiddenFieldLabels
Set<PayInField>

Fields to hide the visible label for. Accessibility labels are unaffected.

formatting
PayInFormatting

Card number grouping, expiration separator, and ACH account masking.

groupsCardNumber
BooleanDefaults to true

Adds visual card number grouping.

expirySeparator
StringDefaults to /

Separator used in expiration entry. It can’t be empty, and it can’t contain digits.

masksAccountNumber
BooleanDefaults to true

Masks ACH account number entry. The routing number isn’t masked.

showsBaseAmount
BooleanDefaults to true

Whether the summary section shows the Amount row. The Amount row shows totalAmount minus the service fee and the surcharge. The Total row shows totalAmount, which already includes any surcharge.

The SDK checks a configuration when you build it. If the form couldn’t submit as configured, PayInFormConfiguration throws IllegalArgumentException. Common causes:

  • A card form is missing one of the card fields.
  • A summary section lists a field other than Amount, ServiceFee, or SurchargeFee.
  • A section lists a field that its payment method doesn’t use, such as RoutingNumber in a card section.
PayInField
enum

Card, ACH, customer, and payment summary fields available for sections, requiredFields, hiddenFieldLabels, and labels.

CardholderName
case
Name on card. Card field.
CardNumber
case
Card number. Card field.
CardExpiration
case
Expiration, entered with a month and year picker. Card field.
CardSecurityCode
case
Security code. Card field.
CardPostalCode
case
Postal code. Card field.
AccountHolder
case
Account holder. ACH field.
RoutingNumber
case
Routing number. ACH field.
AccountNumber
case
Account number. ACH field.
AccountType
case
Checking or savings. ACH field.
AccountHolderType
case
Personal or business. ACH field.
SecCode
case
SEC code. ACH field.
DeviceId
case
Device. Optional ACH field.
MethodDescription
case
Description. StoreMethod only.
FirstName
case
First name. Customer field.
LastName
case
Last name. Customer field.
CustomerNumber
case
Customer number. Customer field.
BillingEmail
case
Billing email. Customer field.
BillingPostalCode
case
Billing postal code. Customer field.
Amount
case
Amount. Read-only payment summary field.
ServiceFee
case
Fee. Read-only payment summary field.
SurchargeFee
case
Surcharge. Read-only payment summary field.

Request configuration

The request configuration carries the payment and customer data that each operation sends to Payabli:

PayabliPayInRequestConfiguration carries the request data for hosted capture and authorize forms. On a store form, its paymentDetails aren’t used. Its customerData is used ahead of options.customerData, and its validation replaces options.validation. The direct capture(_:) and authorize(_:) methods take a PayabliPayInRequest instead. Build it with PayabliPayInRequest(paymentMethod:options:): pass the card, bank account, or stored method as paymentMethod, and this configuration as options:

let result = try await payIn.capture(
PayabliPayInRequest(
paymentMethod: .card(.init(data: cardData)),
options: PayabliPayInRequestConfiguration(
paymentDetails: PayabliPayInPaymentDetails(totalAmount: 12.34),
orderId: "order-1001"
)
)
)
paymentDetails
objectRequired
totalAmount
numberRequired

The amount charged. It includes serviceFee and surchargeFee. Must be greater than 0 after rounding to two decimal places, so 0.001 is refused. serviceFee plus surchargeFee must be less than totalAmount.

serviceFee
number

Included in totalAmount. Must not be negative.

surchargeFee
number

Included in totalAmount. Must not be negative.

currency
string

For example, USD.

checkNumber
string
checkUniqueId
string
accountId
string
customerData
object

Defaults merged with form-entered customer data. A paypoint can require customer identifiers, such as customerNumber. If they’re missing, the paypoint refuses the charge with E7020. See the unified response codes reference.

firstName
string
lastName
string
customerNumber
string
customerId
Int64
company
string
billingEmail
string
billingPhone
string
billingAddress1
string
billingAddress2
string
billingCity
string
billingState
string
billingZip
string
billingCountry
string
shippingAddress1
string
shippingAddress2
string
shippingCity
string
shippingState
string
shippingZip
string
shippingCountry
string
identifierFields
array[string]

Custom identifier fields, when the paypoint uses custom identifiers instead of name, email, or customer ID.

additionalData
object
ipAddress
string
orderDescription
string
orderId
string

Your own order reference. Set it on every request so you can find the transaction in the Payabli Portal if the outcome is unknown. A retry must send the same orderId as the payment it repeats.

source
string
subdomain
string
subscriptionId
number
paymentReference
string

Your own identifier for this payment. The SDK doesn’t send it to Payabli. If you don’t set one, the SDK generates one and returns it with submissionInterrupted. A blank value is refused. The SDK creates and stores the idempotency key for every charge, so you never set one.

attempt
PayabliAttemptDefaults to .newPayment

.newPayment or .retry. Set .retry, with the same paymentReference, only to try again a payment whose outcome is unknown. See Retry a payment.

achValidation
boolean
forceCustomerCreation
boolean
validation
objectDefaults to card number and routing number checks on

Client-side validation, run before a request is sent.

requiresLuhnCheck
booleanDefaults to true

Runs a checksum on card numbers to catch typos before the request is sent.

validatesRoutingNumberChecksum
booleanDefaults to true

Runs an ABA checksum on ACH routing numbers.

PayInTransactionOptions carries the request data for Capture and Authorize forms. It isn’t used for StoreMethod. The direct capture and authorize methods take a PayInRequest instead, which pairs a required paymentMethod with these options.

paymentDetails
PayInPaymentDetailsRequired
totalAmount
BigDecimalRequired

The amount charged. It includes serviceFee and surchargeFee. Must be greater than 0 after rounding to two decimal places, so 0.001 is refused. serviceFee plus surchargeFee must be less than totalAmount.

serviceFee
BigDecimal

Included in totalAmount. Must not be negative.

surchargeFee
BigDecimal

Included in totalAmount. Must not be negative.

currency
String

For example, USD.

checkNumber
String
checkUniqueId
String
customerData
PayInCustomerData

Defaults merged with form-entered customer data. A paypoint can require customer identifiers, such as customerNumber. If they’re missing, the paypoint refuses the charge with E7020. See the unified response codes reference.

customerId
Long

Payabli’s internal customer ID, when the customer is already registered.

customerNumber
String
firstName
String
lastName
String
company
String
billingEmail
String
billingPhone
String
billingAddress1
String
billingAddress2
String
billingCity
String
billingState
String
billingZip
String
billingCountry
String
shippingAddress1
String
shippingAddress2
String
shippingCity
String
shippingState
String
shippingZip
String
shippingCountry
String
additionalData
Map<String, String>
accountId
String
ipAddress
String
orderId
String

Your own order reference. Set it on every request so you can find the transaction in the Payabli Portal if the outcome is unknown. A retry must send the same orderId as the payment it repeats.

orderDescription
String
source
String
subdomain
String
subscriptionId
Long
achValidation
Boolean

Checks a bank account before it’s debited, in addition to any check that the merchant’s settings already run. Setting this value to false doesn’t turn off that check.

forceCustomerCreation
Boolean

Applies only when the payor can’t be matched to an existing customer. When this value is true, each such payment creates a new customer record.

validation
PayInValidationOptionsDefaults to card number and routing number checks on

Client-side validation, run before a request is sent.

checksCardNumber
BooleanDefaults to true

Runs a checksum on card numbers to catch typos before the request is sent.

checksRoutingNumber
BooleanDefaults to true

Runs an ABA checksum on ACH routing numbers.

paymentReference
String

Your own identifier for this payment. The SDK doesn’t send it to Payabli. If you don’t set one, the SDK generates one and returns it in PayInException.Unsettled.paymentReference. A blank value is refused. The SDK creates and stores the idempotency key for every charge, so you never set one.

attempt
PayabliAttemptDefaults to NewPayment

NewPayment or Retry. Set Retry, with the same paymentReference, only to try again a payment whose outcome is unknown. See Retry a payment. PayabliAttempt is in com.payabli.sdk.core.model.

PayInStoreOptions carries the options for StoreMethod forms. The direct storeMethod method takes the same options in a PayInStoreRequest. These correspond to the options of Save a payment method.

customerData
PayInCustomerData
customerId
Long

Payabli’s internal customer ID, when the customer is already registered.

customerNumber
String
firstName
String
lastName
String
company
String
billingEmail
String
billingPhone
String
billingAddress1
String
billingAddress2
String
billingCity
String
billingState
String
billingZip
String
billingCountry
String
shippingAddress1
String
shippingAddress2
String
shippingCity
String
shippingState
String
shippingZip
String
shippingCountry
String
additionalData
Map<String, String>
vendorData
PayInVendorData

vendorNumber, name, ein, phone, and email.

methodDescription
String
source
String
subdomain
String
achValidation
Boolean
createAnonymous
Boolean
forceCustomerCreation
Boolean
temporary
Boolean
fallbackAuth
Boolean
fallbackAuthAmount
Int
validation
PayInValidationOptions

Client-side validation, run before a request is sent. Same fields and defaults as validation in PayInTransactionOptions.

Sheet presentation

On iOS, you can present the form in a sheet. On Android, you place the form in a container of your own:

PayabliPayInSheetConfiguration controls the sheet presentation for .payabliPayInSheet(...). The sheet wraps the same hosted form as PayabliPayInView, so configuration, requestConfiguration, and style still apply:

Button("Add Payment Method") {
isPresented = true
}
.payabliPayInSheet(
isPresented: $isPresented,
component: payIn,
configuration: configuration,
sheetConfiguration: PayabliPayInSheetConfiguration(
title: "Add Payment Method",
dismissButton: .close
),
onCompleted: { result in
// Store the ID with the customer record. Don't log it.
if let storedMethodId = result.storedPaymentMethod?.storedMethodId {
saveStoredMethodId(storedMethodId)
}
}
)
title
string

Sheet title. Falls back to the form’s labels.title when movesFormHeaderToSheetHeader is true.

subtitle
string

Sheet subtitle. Falls back to the form’s labels.subtitle when movesFormHeaderToSheetHeader is true.

dismissButton
stringDefaults to .close

.close, .back, or .hidden.

dismissesOnSuccess
booleanDefaults to true

Dismisses the sheet automatically after onCompleted fires.

detents
array[string]Defaults to [.medium, .large]

SwiftUI presentation detents. An empty set resolves to .large.

dragIndicatorVisibility
stringDefaults to .visible

SwiftUI drag indicator visibility.

contentInsets
objectDefaults to top 20, leading 20, bottom 24, trailing 20

Padding around the sheet’s content.

movesFormHeaderToSheetHeader
booleanDefaults to true

Moves the form’s title and subtitle into the sheet header instead of rendering them inline.

sizesToContentWhenPossible
booleanDefaults to true

Adds a detent sized to the form’s measured content height, when it fits.

expandsToLargeWhenContentDoesNotFit
booleanDefaults to true

Expands to .large if the form’s content doesn’t fit the selected detent.

The Android SDK doesn’t include a sheet. Render PayabliPayInForm in a container of your own, such as a Material ModalBottomSheet.

Response reference

A successful operation returns the transaction or the saved payment method:

PayabliPayInResult is a unified wrapper for both token-storage and transaction operations.

kind
string

.storedPaymentMethod or .transaction.

code
string

Stored-method result code, or transaction response code.

reason
string

Human-readable result or failure reason, when the service returns one.

explanation
string

Present for .transaction results. Additional detail beyond reason.

action
string

Present for .transaction results. Suggested next step, when the service returns one.

storedPaymentMethod
object

Present when kind is .storedPaymentMethod.

storedMethodId
string

nil when the service’s response doesn’t include an ID.

method
string

.card or .bankAccount.

methodReferenceId
string
resultCode
number
resultText
string
customerId
Int64
responseText
string
transaction
object

Present when kind is .transaction. Covers capture, authorize, and capture-authorized results.

paymentTransId
string

Optional, and can be absent even in a completed result. When it’s absent, the call still succeeded: a capture was charged, and an authorization placed a hold. Find the transaction by your orderId to get its ID. When it’s present, you can read the transaction with readTransaction(_:).

gatewayTransId
string
orderId
string

The order reference sent with the request, when present.

method
string
transStatus
number
status
PayabliPayInTransactionStatus

The transaction’s status, taken from transStatus. It’s nil when transStatus is absent. .captured means paid. .declined, .voided, and .blocked mean not paid. .initiated, .authorized, .failed, and .other(_:) mean that the outcome is unknown. Read the transaction again later before you act on it.

paypointId
number
totalAmount
number
netAmount
number
feeAmount
number
surchargeFee
number
settlementStatus
number
operation
string
responseData
object

Processor-level response detail. See Make a transaction (v2) for the underlying field semantics.

resultCode
string
resultCodeText
string
response
string
responseText
string
authCode
string
transactionId
string
avsResponse
string
avsResponseText
string
cvvResponse
string
cvvResponseText
string
orderId
string

The order reference the processor returned, when present.

responseCode
string
responseCodeText
string
customerVaultId
string
emvAuthResponseData
string
type
string
source
string
isValidatedACH
boolean
transactionTime
string
achSecCode
string
achHolderType
string
ipAddress
string
walletType
string
apiResponse
object

Present for .transaction results. The raw response the transaction fields above were parsed from.

code
string
reason
string
explanation
string
action
string
data
object

Same shape as transaction above.

token
string

A successful Capture or Authorize returns a PayInResult. A successful StoreMethod returns a PayInStoredMethod. readTransaction returns a PayInTransaction directly, not inside a PayInResult. A transaction that you read this way doesn’t include connectorName or customerId.

PayInResult
object
code
String

The service’s response code.

reason
String
explanation
String
action
String
transaction
PayInTransaction
paymentTransId
String

Optional, and can be absent even in a completed result. When it’s absent, the call still succeeded: a capture was charged, and an authorization placed a hold. Find the transaction by your orderId to get its ID.

gatewayTransId
String
orderId
String
method
String
transStatus
Int
status
PayInTransactionStatus

The transaction’s status, taken from transStatus. It’s null when the response has no status number. Captured means paid. Declined, Voided, and Blocked mean not paid. Initiated, Authorized, Failed, and Other mean that the outcome is unknown. Read the transaction again later before you act on it. Other carries the number in raw.

paypointId
Long
totalAmount
BigDecimal
netAmount
BigDecimal
feeAmount
BigDecimal
surchargeFee
BigDecimal
connectorName
String
customerId
Long
PayInStoredMethod
object
storedMethodId
String

The stored method’s ID. To charge it later, pass PayInPaymentMethod.Stored(method, storedMethodId) as the payment method.

method
PayInStoredMethodType

Card or BankAccount.

methodReferenceId
String
customerId
Long
resultCode
Int
resultText
String

Outcomes and errors

Every operation ends in an outcome that tells you whether the payor was charged and whether it’s safe to retry:

Every charge ends in one of three outcomes: charged, not charged, or unknown. Only not charged is safe to charge again as a new payment. To repeat a payment whose outcome is unknown, send it as a retry. See Retry a payment.

A success means something different for each call:

CallA success means
.capture, capture(_:)The payment was charged.
.authorize, authorize(_:)An amount is held on the card. Nothing is charged until you capture it.
captureAuthorizedTransaction(_:)The held amount was charged.
.storePaymentMethod, addCard(_:options:), addBankAccount(_:options:), addPaymentMethod(_:options:)The payment method was saved.
voidTransaction(_:)The transaction was voided.
readTransaction(_:)The transaction was read. Check its status.
ResultOutcomeWhat to do
The call returns a PayabliPayInResult, or onCompleted runsThe call succeeded, as the previous table describesStore the transaction ID or the stored method ID with your order.
PayabliPayInError.transactionFailed, for example a declineNot chargedYou can charge again as a new payment.
PayabliPayInError.invalidInput or .submissionInProgressNot charged. Refused before anything was sent.Fix the input, or wait for the running submission. A negative surcharge, or a service fee plus surcharge that isn’t less than the total, is refused this way.
A core PayabliError whose type is .paymentReferenceOpen (1023) or .retryNotSamePayment (1022)Not charged. Refused before anything was sent, because another call for this payment is still being sent or an earlier payment with this paymentReference is still unknown.Check that payment first. To try it again, send the same details as a retry. To charge a different payment, use a new paymentReference.
A core PayabliError whose type is .tokenProviderFailedNot charged. Your token provider failed.Fix the token provider.
A core PayabliError whose type is .tokenExpired (1002)Not charged. Payabli refused the token, and it also refused the new token that your provider returned.Fix the credential, such as a token for the wrong environment or a missing permission. Then call PayabliSession.initialize(config:) again to start a new session, and construct a new PayabliPayIn from it. A PayabliPayIn built on the old session keeps failing with 1002.
PayabliPayInError.submissionInterrupted, or a CancellationError from a canceled capture(_:), authorize(_:), captureAuthorizedTransaction(_:), or voidTransaction(_:)UnknownDon’t charge again until you’ve checked. A canceled call keeps its key. A CancellationError carries no paymentReference, so if your app cancels charges, set paymentReference on each new payment. A retry of capture(_:) or authorize(_:) with the same paymentReference resends the key, and so does calling captureAuthorizedTransaction(_:) or voidTransaction(_:) again with the same transaction ID. A canceled form submission that may have been sent ends in submissionInterrupted with type .userCancelled. The error includes a paymentTransId when Payabli returns one. Errors from capture(_:) or authorize(_:) also include the payment’s paymentReference. Read the transaction with readTransaction(_:) and check its status. Without a paymentTransId, find the transaction by orderId in the Payabli Portal after capture(_:) or authorize(_:), or read the transaction with the ID you passed after captureAuthorizedTransaction(_:) or voidTransaction(_:). If its type is .retryRefused (1021), the earlier attempt reached Payabli.
Another core PayabliError, such as a validation failure, a refused credential, or a rate limitNot chargedBranch on its type.
A core PayabliError from readTransaction(_:) whose type is .transactionNotFound (1020)The transaction isn’t visible yet. This doesn’t mean that no payment was made.Read again later. Don’t charge again. A .permissionDenied error means that your credentials don’t have inboundpayments_read.
PayabliPayInTokenStorageErrorThe payment method wasn’t saved.invalidInput was refused before sending. .missingAccessToken means there was no token, so nothing was sent. .saveFailed means that Payabli refused the save, and the error’s type is .paymentDeclined. For a failed HTTP status, you get the core PayabliError for that status instead. For a 400, the type is .validation, and Payabli’s explanation is in detail.
A core PayabliError from addCard, addBankAccount, or addPaymentMethod whose type is .networkError, .serverError, .decodingError, or .conflict (409), or a CancellationError after the call startsUnknown. The method may have been saved.Read the stored methods back before saving again. Get customer record returns the customer’s stored methods.

For voidTransaction(_:), transactionFailed means the void was refused. It doesn’t mean the original payment wasn’t charged.

Don’t show error.localizedDescription to the payor, and don’t log it. It names what the service rejected and can quote what was submitted. Show the payor a message for the error’s category instead, such as .declined, .retryLater, or .outcomeUnknown, and log (error as? any PayabliError)?.code. Check for submissionInterrupted before you check category. This error keeps the category of the error that caused it, so a rate-limit or credential error can arrive for a payment that Payabli processed. The form shows the payor its own message, so you don’t need to show one for form errors.

Every charge ends in one of three outcomes: charged, not charged, or unknown. Only not charged is safe to charge again as a new payment. To repeat a payment whose outcome is unknown, send it as a retry. See Retry a payment.

Every direct method returns a Kotlin Result. If the call is canceled, the method throws a CancellationException instead. A form reports its result through onCompleted and onFailed. A success means something different for each call:

CallA success means
Capture, captureThe payment was charged.
Authorize, authorizeAn amount is held on the card. Nothing is charged until you capture it.
captureAuthorizedTransactionThe held amount was charged.
StoreMethod, storeMethodThe payment method was saved.
voidTransactionThe transaction was voided.
readTransactionThe transaction was read. Check its status.

Check for PayInException.Unsettled before you branch on type or category. An Unsettled failure keeps the type and category of the error that caused it, such as TOKEN_EXPIRED. The category alone doesn’t tell you whether the payor might have been charged.

ResultOutcomeWhat to do
Result.success, or onCompleted runsThe call succeeded, as the previous table describesStore the transaction ID or the stored method ID with your order.
PayInException.Refused, for example a declineNot chargedYou can charge again as a new payment.
PayInException.InvalidInput or PayInException.AlreadySubmittingNot charged. Refused before anything was sent.Fix the named field, or wait for the running submission.
A core PayabliException whose type is PAYMENT_REFERENCE_OPEN (1023) or RETRY_NOT_SAME_PAYMENT (1022)Not charged. Refused before anything was sent, because another call for this payment is still being sent or an earlier payment with this paymentReference is still unknown.Check that payment first. To try it again, send the same details as a retry. To charge a different payment, use a new paymentReference.
A core PayabliException whose type is TOKEN_PROVIDER_FAILEDNot charged. Your token provider failed.Fix the token provider.
PayInException.Unsettled, or a cancellation after the call starts, for capture, authorize, captureAuthorizedTransaction, or voidTransactionUnknownDon’t charge again until you’ve checked. When paymentTransId is set, read the transaction with readTransaction and check its status. Otherwise, find the transaction by orderId in the Payabli Portal. After captureAuthorizedTransaction or voidTransaction, read the transaction with the ID you passed. If type is RETRY_REFUSED (1021), Payabli already has the earlier attempt, so read the transaction instead of retrying.
PayInException.Interrupted (form only)For a charge: not charged, because the form stopped before it sent anything. For StoreMethod: unknown, because the method may have been saved.Retry the charge. For StoreMethod, read the stored methods back before you store again.
Another core PayabliException, such as a refused credential or a rate limitNot charged, or not saved. A charge that fails before its request leaves the device reports its own error, such as NETWORK_ERROR. On a charge, an unknown outcome arrives as Unsettled instead.Branch on its type, or use its category to choose a remedy.
From readTransaction: a core PayabliException whose type is TRANSACTION_NOT_FOUND (1020)The transaction isn’t visible yet. This doesn’t mean that no payment was made.Read again later. Don’t charge again. A PERMISSION_DENIED failure means that your credentials don’t have inboundpayments_read.
From storeMethod only: PayInException.ServiceError, PayInException.Undecodable, a core PayabliException whose category is OUTCOME_UNKNOWN, or a cancellation after the call starts. For example: a network error or timeout, a 5xx response, a 409 conflict, an unexpected status, or a success response that the SDK can’t read.Unknown. The method may have been saved.Read the stored methods back before you store again. Get customer record returns the customer’s stored methods. On a charge, the service and decoding errors arrive as Unsettled instead.

For voidTransaction, a refusal means that the void was refused. It doesn’t mean that the original payment wasn’t charged.

If you call captureAuthorizedTransaction or voidTransaction again with the same transaction ID after an unknown outcome, the SDK resends the same key. If Payabli refuses that repeat, the failure is PayInException.Unsettled with type RETRY_REFUSED. Read the transaction instead of calling again.

When a form submission fails, PayInSubmissionState.Failed carries:

  • cause: The exception. It tells you whether a payment might still be outstanding. Check it first.
  • fieldErrors: The fields that the service refused, keyed by PayInField. It’s empty when the refusal names no field.

When cause is PayInException.Unsettled, its paymentReference names the payment to retry, and its paymentTransId names the transaction to read back when Payabli returned one.

After Payabli responds, the form clears the card number, expiration date, security code, routing number, and account number. If the submission is refused before Payabli can process it, such as for an amount that can’t be sent, the form keeps these values.

PayInException.Refused and PayInException.ServiceError carry failure, a PayInFailure with the service’s code, reason, explanation, action, and paymentTransId. Show reason, explanation, and action to the payor, but don’t log them, because they can repeat what was submitted. Log the exception’s code instead.

Retry a payment

When a payment’s outcome is unknown, you can send the same payment again as a retry. Payabli recognizes the repeat and doesn’t charge the payor twice:

Every charge sends an idempotency key that the SDK creates and stores, so you don’t set one. Name each new payment with paymentReference on the request’s options, or let the SDK name it. A charge whose outcome is unknown ends in submissionInterrupted, which carries that paymentReference.

Read the transaction first when you can. To repeat the same payment, set attempt: .retry and the same paymentReference on the options. The SDK resends that payment’s key, so Payabli recognizes the repeat and doesn’t charge twice:

let options = PayabliPayInRequestConfiguration(
paymentDetails: PayabliPayInPaymentDetails(totalAmount: 9.99),
orderId: "order-1001",
// The paymentReference that submissionInterrupted carried.
paymentReference: paymentReference,
attempt: .retry
)

A retry with no paymentReference is refused as invalid input and isn’t sent.

A retry follows these rules:

  • Same payment. A retry must have the same amount, service fee, surcharge, currency, and kind of payment method as the payment it repeats. If that payment set an orderId, the retry must set the same one. Otherwise, the call fails with .retryNotSamePayment (1022) and isn’t sent.
  • One call per payment at a time. While a call for a payment is still being sent, any other call for the same payment fails with .paymentReferenceOpen (1023) and isn’t sent. This applies to a retry, and to a capture or void of a transaction that’s still being captured or voided. A new payment that reuses the paymentReference of a payment whose outcome is unknown also fails with 1023. To repeat that payment, send it as a retry. A blank paymentReference is refused as invalid input.
  • Refused retry. If Payabli refuses the retry, the call ends in submissionInterrupted with type .retryRefused (1021). The earlier attempt reached Payabli, and its outcome is still unknown. Read the transaction before you try again. If Payabli refuses the retry because it matches an earlier payment, the type is .conflict.
  • Keys in memory, shared per entrypoint. The SDK stores each key in memory for a limited time after the latest send whose outcome is unknown. Every PayabliPayIn for the same entrypoint and environment shares the stored keys, so a retry from a new PayabliPayIn resends the key. The SDK stores at most 16 keys for each entrypoint and environment. A retry that Payabli refuses, or one that never leaves the device, doesn’t extend that time. A retry sends a new key, and can charge again, if that time has passed, if 16 keys were already stored when the payment was sent, or if your app restarted. In those cases, read the transaction instead of retrying.

captureAuthorizedTransaction(_:) and voidTransaction(_:) resend the stored key for their transaction automatically.

Every charge sends an idempotency key that the SDK creates and stores, so you don’t set one. Name each new payment with paymentReference, or let the SDK name it. A charge whose outcome is unknown fails with PayInException.Unsettled, which returns that paymentReference.

Read the transaction first when you can. To repeat the same payment, send it with the same paymentReference and attempt = PayabliAttempt.Retry. The SDK resends that payment’s key, so Payabli recognizes the repeat and doesn’t charge twice:

val options =
PayInTransactionOptions(
paymentDetails = PayInPaymentDetails(totalAmount = BigDecimal("9.99")),
orderId = "order-1001",
// The paymentReference that PayInException.Unsettled returned.
paymentReference = unsettled.paymentReference,
attempt = PayabliAttempt.Retry,
)

A retry with no paymentReference fails with PayInException.InvalidInput naming paymentReference, and isn’t sent.

A retry follows these rules:

  • Same payment. A retry must have the same amount, service fee, surcharge, currency, and kind of payment method as the payment it repeats. If that payment set an orderId, the retry must set the same one. Otherwise, the call fails with RETRY_NOT_SAME_PAYMENT (1022) and isn’t sent.
  • One call per payment at a time. While a call for a payment is still being sent, any other call for the same payment fails with PAYMENT_REFERENCE_OPEN (1023) and isn’t sent. This applies to a retry, and to a capture or void of a transaction that’s still being captured or voided. A new payment that reuses the paymentReference of a payment whose outcome is unknown also fails with 1023. To repeat that payment, send it as a retry.
  • Refused retry. If Payabli refuses the retry because it already has that payment, the failure is PayInException.Unsettled with type RETRY_REFUSED (1021). The earlier attempt reached Payabli, and its outcome is still unknown. Read the transaction before you try again.
  • Keys in memory, shared per entrypoint. The SDK stores each key in memory. Every PayabliPayIn for the same entrypoint and environment shares the stored keys, so a retry from a new PayabliPayIn resends the key. The SDK stores keys for up to 16 unknown payments for each entrypoint and environment.
  • Time limit. The SDK keeps a key for four minutes after the latest send whose outcome is unknown. A retry refused with RETRY_REFUSED, or one that never leaves the device, doesn’t restart the four minutes.
  • When a retry is a new payment. A retry sends a new key, and can charge again, if four minutes have passed, if your app restarted, or if 16 keys were already stored. In those cases, read the transaction instead of retrying.

captureAuthorizedTransaction and voidTransaction don’t take attempt. If you call either one again with the same transaction ID, the SDK resends the stored key.

Theming and diagnostics

Style the form to match your app, and use the SDK’s diagnostics when you need to debug.

Style

The form follows your app’s look by default. You can override its fonts, colors, shapes, and spacing:

Use PayabliPayInStyle to style the hosted form. Pass it directly to PayabliPayInView or .payabliPayInSheet(...), or inject it with .payabliPayInStyle(_:).

Style areaTypeCovers
Title and subtitlePayabliPayInTextStyleFont, color
Section titlesPayabliPayInTextStyleFont, color, per-section overrides
LabelsPayabliPayInTextStyleFont, color
InputsPayabliPayInInputStyleFont, uiFont for the text fields, text/placeholder color, background and focused background, border and focused border, corner radius, picker icon color
Submit buttonPayabliPayInSubmitButtonStyleFont, colors, corner radius, height, padding
Error messagePayabliPayInTextStyleFont, color
LayoutPayabliPayInLayoutStyleContent, header, field, and section spacing

To use a custom font:

1

Add the font to your app

Add the font file to your app target, then add its filename to UIAppFonts in Info.plist.

2

Reference it in your style

Use Font.custom(_:size:) for SwiftUI text, and UIFont(name:size:) for PayabliPayInInputStyle.uiFont.

The form uses the colors, typography, and shapes of your app’s MaterialTheme. Light mode, dark mode, and dynamic color work without extra setup. To change individual values, build a style from the defaults and your overrides:

PayabliPayInForm(
payIn = payIn,
operation = operation,
configuration = PayInFormConfiguration(),
style = PayabliPayInFormDefaults.style(
PayInFormStyleOverrides(fieldShape = RoundedCornerShape(12.dp)),
),
onCompleted = { },
onFailed = { },
onMethodChanged = { },
)

To apply one style to every form in a part of your UI, provide it through the LocalPayInFormStyle composition local. PayInFormStyleOverrides can set:

Style areaFieldCovers
Title and subtitletitle, subtitleCompose TextStyle
Section titlessectionTitleCompose TextStyle
Labelslabel, supportingCompose TextStyle for field labels, and for secondary text such as the card brand name
InputsfieldShape, fieldColorsInput shape, and Material TextFieldColors
Submit buttonNoneA Material Button that takes its colors and shape from your app’s MaterialTheme
Error messageerrorCompose TextStyle for field error messages
LayoutspacingPayInFormSpacing: content, header, field group, paired field, label, section, and section title spacing
Expiry pickerselectedContainer, selectedContentColors of the selected month and year
Card brandbrandMarkSize of the card brand mark in the card number field

If you draw your own payment summary, use PayInSummaryRows to get each row as the form shows it: labelText and totalLabelText for the labels, rowAmount and totalRowAmount for the amounts, and formattedAmount for an amount as text.

Diagnostics

Each platform gives you a different way to debug a failure. On Android, use a verbose log level only for local debugging or QA:

To debug a failure on iOS, log the error’s code and category. The iOS SDK has no diagnostics handler and no log level that you can set:

if let error = error as? any PayabliError {
print(error.code, error.category)
}

Don’t log localizedDescription, reason, or detail, because they can quote what was submitted. Give the code to Payabli support when you report a failure.

The Android SDK has no diagnostics handler. To debug, set the SDK’s log level with PayabliSession.setLogLevel. The SDK writes its log to Logcat. It writes messages at the level you set and at every more severe level. LogLevel.NONE turns logging off.

By default, debug builds log at DEBUG. Release builds log nothing unless you call setLogLevel, whichever environment the app uses. Use a verbose level only for local debugging or QA. Don’t ship it in production builds.

Android also filters each log tag, so DEBUG lines don’t appear until you turn on the tag. To see them, run adb shell setprop log.tag.<TAG> DEBUG for each tag you need: PayabliCore, PayabliAuth, PayabliNetwork, PayabliTokenization, PayabliTapToPay, or PayabliTelemetry.

import com.payabli.sdk.core.PayabliSession
import com.payabli.sdk.core.logging.LogLevel
PayabliSession.setLogLevel(LogLevel.DEBUG)

Example app

Each SDK repository includes an example app and a local token server that you can run against your sandbox paypoint:

The sdk-ios repository includes PayabliDemo, a SwiftUI example app that demonstrates PayabliPayIn and PayabliTTP (storing a payment method, card and ACH capture, and Tap to Pay), alongside a bundled local Node.js token server for testing.

1

Clone the repository

Clone sdk-ios at the release you’re integrating, and open the example project:

git clone --branch 0.2.0 https://github.com/payabli/sdk-ios.git
cd sdk-ios/Example/PayabliDemo
2

Configure your secrets

Copy the secrets template and the environments template. Copy ExtraEnvironments.swift without changes, because the app offers sandbox and production. Then fill in your sandbox identifiers and point the app at the bundled local token server:

cp App/Configuration/Secrets.swift.sample App/Configuration/Secrets.swift
cp SDK/ExtraEnvironments.swift.sample SDK/ExtraEnvironments.swift
Loading walkthrough content

Loading walkthrough...

Loading walkthrough...

/// Set your sandbox identifiers

In App/Configuration/Secrets.swift, set the sandbox entry in entryPoints to your sandbox entryPoint. There’s no App ID to set: the SDK reads it from the signed app, and the TapToPay tab shows the value to register as an authorized app. localNetworkHost is the fallback host a physical device uses when you don’t pass -PayabliTokenHost. Set it to the output of scutil --get LocalHostName on your Mac, followed by .local:

/// Point the app at the local token server

Both token endpoints ship pointing at a placeholder backend. Switch them to DemoConfiguration.TokenServer.accessTokenURL, which resolves to 127.0.0.1 in the Simulator, so the Save and Capture tabs work there without a real backend. The TapToPay tab needs a physical device, which also needs the server setup in the next step:

import Foundation
enum Secrets {
static let entryPoints: [String: String] = [
"sandbox": "your-sandbox-entry-point"
]
static let localNetworkHost = "your-mac-hostname.local"
static var partnerTokenEndpoint: URL { DemoConfiguration.TokenServer.accessTokenURL }
static var partnerPaymentMethodAccessTokenEndpoint: URL { DemoConfiguration.TokenServer.accessTokenURL }
static func fetchAccessToken() async throws -> String {
try await token(from: partnerTokenEndpoint)
}
static func fetchPaymentMethodAccessToken() async throws -> String {
try await token(from: partnerPaymentMethodAccessTokenEndpoint)
}
static func fetchPaymentCaptureAccessToken() async throws -> String {
try await fetchPaymentMethodAccessToken()
}
private static func token(from url: URL) async throws -> String {
var request = URLRequest(url: url)
request.httpMethod = "POST"
let (data, _) = try await URLSession.shared.data(for: request)
struct TokenResponse: Decodable {
let accessToken: String?
let access_token: String?
}
let response = try JSONDecoder().decode(TokenResponse.self, from: data)
guard let token = response.accessToken ?? response.access_token else {
throw URLError(.userAuthenticationRequired)
}
return token
}
}
3

Start the local token server

In a separate terminal, start the bundled LocalTokenServer. It needs Node.js 18 or later:

cd LocalTokenServer
cp .env.example .env

Edit .env and set PAYABLI_ACCESS_TOKEN to a short-lived sandbox access token, then start the server:

node server.mjs

The server binds only to 127.0.0.1 by default and doesn’t authenticate callers, so run it only on your own machine.

Tap to Pay requires a physical device. To test on one, the phone must reach the server over your network:

  1. Start the server on all interfaces. Do this only on a trusted network, and stop the server when you’re done:

    PAYABLI_LOCAL_TOKEN_SERVER_HOST=0.0.0.0 node server.mjs
  2. In Xcode, choose Product → Scheme → Edit Scheme → Run → Arguments and pass your Mac’s local network address, on the same network as the phone:

    -PayabliTokenHost 192.168.1.42
  3. Allow Local Network access when the app asks for it on the phone. See the LocalTokenServer README for the credential-exchange mode and physical-device networking notes.

4

Run the app

Open PayabliDemo.xcodeproj in Xcode and set DEVELOPMENT_TEAM on the project, not on a target, so every target signs with it. Select the PayabliDemo sandbox scheme, which picks the sandbox entry from Secrets.entryPoints, and run it. The Save and Capture tabs work in the Simulator. The TapToPay tab requires a physical device that meets the prerequisites.

The example app assumes a sandbox entryPoint with card, ACH, and Tap to Pay enabled. Contact your Payabli representative if your sandbox paypoint doesn’t have these enabled yet.

The sdk-android repository includes a Jetpack Compose example app that demonstrates PayabliPayIn and PayabliTTP (storing a payment method, card and ACH capture, and Tap to Pay), alongside a bundled local Node.js token server for testing.

1

Clone the repository

Clone sdk-android at the release you’re integrating:

git clone --branch 0.2.0 https://github.com/payabli/sdk-android.git
cd sdk-android

The build downloads the card reader library from Payabli’s Maven repository. Add the credentials that Payabli gave you to ~/.gradle/gradle.properties:

payabli.maven.user=<your Payabli Maven user>
payabli.maven.password=<your Payabli Maven password>
2

Configure your settings

Copy the settings template, then set your sandbox entrypoint:

cp example/secrets.properties.example example/secrets.properties
# example/secrets.properties
payabli.demo.entryPoint=<your sandbox entrypoint>
payabli.demo.environment=sandbox
payabli.demo.appId=com.payabli.example.app

secrets.properties holds no credentials, because the app gets its access token from the local token server. To check the signing certificate before device attestation runs, set payabli.demo.signingCertificate to the SHA-256 digest of the certificate the build is signed with.

3

Start the local token server

In a separate terminal, start the bundled token server. It needs Node.js 18 or later and has no dependencies:

cd example-server
cp .env.example .env

Edit .env and set PAYABLI_ACCESS_TOKEN to a short-lived sandbox access token, then start the server:

node server.mjs

The server binds only to 127.0.0.1 by default and doesn’t authenticate callers, so run it only on your own machine. How the app reaches it depends on where the app runs:

  • Emulator (Pay In only): The app reaches the server at 10.0.2.2:8787 with no setup.

  • Physical phone with USB debugging (Pay In only): Forward the port over USB:

    adb reverse tcp:8787 tcp:8787
  • Physical phone for Tap to Pay: Tap to Pay requires USB debugging and developer options to be turned off, so adb reverse isn’t available. The phone reaches the server over your network instead:

    1. On a trusted network only, start the server on all interfaces instead, and stop it when you’re done:

      PAYABLI_LOCAL_TOKEN_SERVER_HOST=0.0.0.0 node server.mjs
    2. In example/secrets.properties, set payabli.demo.tokenHost to your computer’s local network address and port, for example 192.168.1.42:8787.

    3. Add the same local network address to example/src/debug/res/xml/network_security_config.xml, because the app permits plain HTTP only to the addresses listed there.

See the example-server README for the credential exchange mode and other networking options.

4

Run the app

To run the Save and Capture tabs on an emulator or on a phone with USB debugging, install and launch the app from the repository root:

./gradlew :example:installDebug
adb shell am start -n com.payabli.example.app/.MainActivity

The TapToPay tab needs:

  • A physical phone that meets the prerequisites
  • The example app enrolled with Payabli for your computer
  • com.payabli.example.app registered as one of the paypoint’s authorized apps

To set up Android Tap to Pay, including enrolling your app with the card reader and testing in sandbox, contact Payabli support.

The build is signed with your computer’s Android debug key, so each developer needs their own enrollment. To enroll, run ./gradlew :example:signingReport and copy the SHA-256 value under Variant: debug. Send that value to your Payabli representative with the package name com.payabli.example.app.

Tap to Pay requires developer options to be turned off, so you can’t install this build with adb. Build the Android package (APK) instead:

./gradlew :example:assembleDebug

The APK is at example/build/outputs/apk/debug/example-debug.apk. Install it on the phone as a downloaded APK or through Firebase App Distribution. Google Play doesn’t accept a debug-signed APK, even on a testing track, and sandbox doesn’t require a Google Play install.

Turn off developer options and USB debugging before you install the app. If this device had them turned on before, restart it after you turn them off, then install the app.

The Config tab shows the values that the SDK uses, and checks whether the app can reach the token server.

The example app assumes a sandbox entryPoint with card, ACH, and Tap to Pay enabled. Contact your Payabli representative if your sandbox paypoint doesn’t have these enabled yet.

See these related resources to help you get the most out of Payabli.