Pay
Pay with a card from the card fields, a redirect method, a saved method, or a Google Pay token, with 3DS and redirects shown over your activity.
checkout.pay() submits a payment for the checkout's session and returns the client-side result. It presents any required steps over your activity, including 3DS flows for cards and payment pages for redirect methods. Call it when the customer taps your pay button, with the card from the card fields, a method from checkout.paymentMethods(), or one of the customer's saved methods. The drop-in calls it for you.
pay is an extension function from pay-threeds, and a suspend function. Import it, and call it from a coroutine.
import com.pay.sdk.threeds.pay
val result: PayResult = checkout.pay(PayPaymentRequest.Card(card), activity)Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
request | PayPaymentRequest | Yes | What to pay with, using one of the payment requests below. |
activity | ComponentActivity | Yes | The activity that shows the 3DS challenge and redirects. Keep it alive until pay returns. |
Payment requests
PayPaymentRequest has one request for each way to pay.
| Request | Description |
|---|---|
PayPaymentRequest.Card(source, saveForFutureUse = false, termsAccepted = false) | The card typed into the SDK's card fields. Pass their PayCardController as source. saveForFutureUse asks Pay.com to save the card for the customer. A session created with setup_future_usage: on_session saves it anyway. In a setup session, paying saves the card and completes the session. termsAccepted indicates that the customer accepted your terms and conditions on your screen, and Pay.com records that on the payment and the customer. Leave it false unless you asked them. |
PayPaymentRequest.Alternative(type, data = emptyMap()) | A redirect payment method, by its type from checkout.paymentMethods(), for example paypal. data carries the fields the method asks for, if any. Most methods open their page in a Custom Tab. Some complete without one. |
PayPaymentRequest.SavedPaymentMethod(method, cvc = null) | One of checkout.savedPaymentMethods(). In a sale or authorization session, the saved method is charged. For a saved card, pass the PayCvcController with its CVV as cvc when checkout.requiresCvc(method) is true. A saved method that isn't a card may open the provider's page, as a redirect method does. In a setup session, the method becomes the customer's default payment method. |
PayPaymentRequest.GooglePay(paymentData, termsAccepted = false) | What Google Pay returned for checkout.googlePayPaymentDataRequest(), as PaymentData.toJson(). checkout.payWithGooglePay() shows the Google Pay sheet and pays for you. termsAccepted works as for Card. The Google Pay sheet doesn't show your terms. |
The drop-in shows no terms and conditions, so it never says the customer accepted them.
Returns
pay() returns a PayResult once the payment has an outcome the device can see, or once it stops waiting for one. Its PaymentIds identify the payment for your server.
| Result | What pay saw |
|---|---|
PayResult.Succeeded(ids) | The payment succeeded, or was authorized for a session created with capture: false. In a setup session, the payment method was saved. ids.transaction is its token's ID and ids.status is "tokenized". For a SavedPaymentMethod request in a setup session, the method became the customer's default. ids.paymentMethod is its id, and nothing else is set. |
PayResult.Processing(ids) | No final outcome yet. The payment method is pending (for example one the customer pays offline), the payment waits for a partial approval, the SDK stopped waiting for the status, or the session's client_secret stopped working before the result could be read. Your server decides. |
PayResult.Canceled | The customer closed the 3DS challenge, or came back from a redirect without finishing it, and no payment was seen. |
PayResult.Failed(error) | The payment failed. See Errors. |
Errors
pay() throws a PayError only when a call fails before sending a request:
| Error | When |
|---|---|
PayError.InvalidCardInput(fields) | The card fields of a Card request are incomplete or invalid. fields lists the invalid fields (NUMBER, EXPIRY, CVC, or NAME). For a SavedPaymentMethod request, the saved card requires a CVV and none was passed, or the CVV isn't valid. fields is [CVC]. |
PayError.PaymentInProgress | Another payment, or a removal, is running on this checkout. |
PayError.Unsupported(detail) | A SavedPaymentMethod request with a method that isn't one of this checkout's savedPaymentMethods(). |
Every other failure comes back as PayResult.Failed(error):
| Error | When |
|---|---|
PayError.Declined(decline) | The payment was declined. When decline.maxAttemptsReached is true, this was the session's last attempt, so your server creates a new session. |
PayError.PaymentEnded(status) | The payment ended without being paid, for example as failed or canceled. |
PayError.SessionAlreadyCompleted(status) | The session was already paid, or has no attempts left. |
PayError.AmountChanged(amount, currency) | The session's total changed. Nothing was charged. See When the amount changes. |
PayError.SessionExpired | The session expired, or Pay.com stopped accepting its client_secret. |
PayError.EncryptionUnavailable(detail) | clientSideEncryption is on and the card, or a saved card's CVV, couldn't be encrypted. It wasn't sent. |
PayError.RequestRejected(error) | Pay.com refused a request, for example card details it can't accept. |
PayError.Server(error) | Pay.com failed or timed out. |
PayError.Network(detail) | A request didn't reach Pay.com or the response didn't arrive, or the 3DS challenge or a redirect page couldn't open and the status showed nothing final. |
PayError.UnexpectedResponse(detail) | Pay.com returned a response this SDK version can't read. |
PayError.Unsupported(detail) | A GooglePay request's paymentData has no token, or an incomplete one. |
When the amount changes
In every session but a setup session, including one whose flow the SDK doesn't recognize, the SDK reads the amount and currency again right before it charges, and compares them with the values shown to the customer in checkout.session (or the request's total for Google Pay).
- If either changed, nothing is charged.
payreturnsPayResult.Failed(PayError.AmountChanged), andcheckout.sessionhas the new amount and currency. Show them, then let the customer pay again. - If they can't be read, nothing is charged either.
payreturnsPayResult.Failedwith that error.
When your server updates the session's amount, call refreshSession() and show checkout.session.amount before the customer pays.
What the SDK shows
Depending on the payment method, the SDK runs these steps over your activity.
| Step | What the SDK shows |
|---|---|
| 3DS Method | An invisible WebView, when the session runs the 3DS Method for the card. It ends when the issuer's page loads its notification URL, or after 10 seconds, and never fails the payment. |
| 3DS challenge | A full-screen dialog over the activity, with the challenge in a WebView, a title, and a Cancel button. Cancel and the back button end it as canceled. While it's open, the SDK reads the payment's status every 3 seconds and closes it once the status is final. It also closes it after challengeTimeoutMillis. |
| Redirect payment methods | A Custom Tab with the payment method's page. It ends when your app passes the return URL to PayCheckout.handleReturn(), or as canceled when the customer comes back to your app without one. |
After a challenge or a redirect, the SDK reads the payment's status until it's final, for up to 30 seconds after a challenge and 60 seconds after a redirect, then returns Processing. After a cancel, it reads the status for 5 more seconds, so a canceled challenge or redirect can still end as Succeeded, Failed, or Processing.
The challenge screen's title is a string resource you can translate. See pay-threeds.
Example
class CheckoutActivity : ComponentActivity() {
private val viewModel: CheckoutViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val card = remember { PayCardController() }
val state by card.state.collectAsState()
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
PayCardNumberField(card)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
PayExpiryField(card, Modifier.weight(1f))
PayCvcField(card, Modifier.weight(1f))
}
Button(onClick = { pay(PayPaymentRequest.Card(card)) }, enabled = state.isComplete) {
Text("Pay")
}
}
}
}
private fun pay(request: PayPaymentRequest) {
val checkout = viewModel.checkout.value ?: return
lifecycleScope.launch {
val result = try {
checkout.pay(request, this@CheckoutActivity)
} catch (e: PayError) {
return@launch showMessage(e) // Nothing was sent
}
when (result) {
is PayResult.Succeeded -> showReceipt(result.ids) // A hint: your server confirms first
is PayResult.Processing -> showPending(result.ids) // Your server decides
PayResult.Canceled -> Unit // The customer can try again
is PayResult.Failed -> showMessage(result.error)
}
}
}
private fun showMessage(error: PayError) {
val message = when (error) {
is PayError.InvalidCardInput -> "Check your card details."
is PayError.Declined ->
if (error.decline.maxAttemptsReached) "This payment can't be completed." else "Your card was declined. Try another card."
is PayError.Network -> "Check your connection and try again."
else -> "Something went wrong. Please try again."
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}Next steps
- Handle the return URL: Let redirect payment methods come back to your app.
- Refresh the session: Show a new total before the customer pays.
- Card fields: Collect the card you pay with.
- Pay with a saved payment method: Charge one of the customer's saved methods.
- Pay with Google Pay: Show Google Pay's sheet and pay with its token.
- Accept payments in your Android app: Take a first card payment, from the server to the app.