Freedom Pay
  1. Merchant SDK
Freedom Pay
  • Overview
  • Gateway API
    • Overview
    • Sync API
      • Overview
      • Purchase
        • Overview
        • Create payment
        • Any amount
        • Card
        • 3DSecure
        • Recurrent
        • Cancel
        • Clearing
        • Refund
        • Status
      • Payout
        • Overview
        • Card
        • IBAN
        • Balance
        • Status
      • Transfer
        • Overview
        • Card
        • 3DSecure
        • Rates
        • Status
      • Card
        • Overview
        • Add
        • 3DSecure
        • List
        • Remove
        • Status
      • Token
        • Overview
        • Token Pay
        • Apple Pay
        • Google Pay
        • Token Payout
        • Status
    • Async API
      • Overview
      • create
        • create payment
      • read
        • read payment
        • read request
      • edit
        • edit payment.refund
        • edit payment.reverse
        • edit payment.clearing
  • Merchant API
    • Overview
    • Purchase
      • Overview
      • Checkout
      • Card token
        • Overview
        • Tokenize card
        • Delete token
        • Card token list
        • Create payment (with CVC)
        • Confirm payment (with CVC)
        • Create payment
        • Confirm payment
      • Create payment
      • Any amount
      • Cancel payment
      • Clearing
      • Refund payment
      • Status
    • Payout
      • Overview
      • Card token
        • Tokenize card
        • Delete token
        • Card token list
        • Create payment
      • Create payment
      • IBAN
      • Balance status
      • Status by order_id
      • Status by Payment ID
      • Status
    • Mobile balance
      • Overview
      • Init
      • Pay
      • Approve
      • Resend code
      • Status
    • Invoice
      • Overview
      • Init
      • Info
      • Pay
      • Status
    • SDK
      • JS SDK
      • Google Pay
      • Freedom QR
        • Reader SDK (Android)
        • Provider SDK (Android)
      • Payment SDK
        • iOS
        • Android
      • Merchant SDK
        • Android
    • CMS
      • Overview
      • Get Merchant ID and key
      • WordPress
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
        • Update
      • Tilda
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
      • InSales
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
      • Ecwid
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
      • Bitrix
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
      • PrestaShop
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
      • OpenCart
        • Overview
        • Installation
        • Configuration
        • Test
        • Live payments
    • Redirect back
      POST
    • Result notify
      POST
    • Payout notify
      POST
    • Check request
      POST
  • Card API
    • Overview
    • Payment Cards
      • Overview
      • Dictionaries
      • Bulk issue
      • Issue card
      • Issue plastic card
      • Activate card
      • Block card
      • Unblock card
      • Set PIN
      • Reset PIN counter
      • Close card
      • Update client
      • Card info
      • Balance
      • Secret data
      • Secret data (version 2)
      • Operations' list
      • Statement extended
      • Create client
      • Edit client
      • Сards' list
      • Request' status
      • Create transaction
      • Clearing transaction
      • Refund transaction
      • Transaction info
      • Cardholder validation
      • Set limits
      • Limits list
    • Gift Cards
      • Overview
      • List
      • Issue
      • Confirm
      • Resend
      • Resend code
      • Status
  • Partner API
    • Rates
      • Overview
      • Rates
    • Products
      • Overview
      • Dictionaries
      • Add client with product
      • Request status
      • Create terminal
    • E-Money
      • Overview
      • Add
      • Owner identification
      • Info
      • Close
      • Block
      • Balance
      • Statement
      • Request Status
    • Freedom ID
      • Overview
      • Design
      • iOS SDK
      • Android SDK
      • OAuth2
        • Authorization link
        • Token exchange
        • Token refresh
        • User info
        • Request profile
        • Get profile status
        • Create user
        • Update user
      • OIDC
        • Authorization endpoint
        • Token exchange
        • Userinfo
      • Error codes
      • Examples
        • Keycloak
    • Transfer
      • Overview
      • Get token
      • Refresh token
      • Get agents
      • Fees
      • Create person
      • Create business
      • Create transfer
      • Print application
      • Confirm
      • Search
      • Payout
      • Payout confirm
      • Cancel
      • Get person info
      • Get business info
      • Status
      • Info
    • Device ID
      • Android SDK
      • iOS SDK
    • Implement SuperApp
      • Overview
      • Pay
      • Refund
    • Account
      • Settlement
        • Overview
        • Create payment
        • Payment status
    • Invoice
      GET
  1. Merchant SDK

Android

Merchant SDK (Android, Kotlin)

 The Merchant SDK is a library that simplifies interaction with the Freedom Pay API. Supports Android 9 and above.


Table of Contents

NOTE

  • Getting Started
  • Installation Instructions
  • SDK integration
  • Integrating the PaymentView (Optional)
    • Adding PaymentView
    • Connecting PaymentView
    • Tracking Loading Progress
  • SDK Configuration
    • SdkConfiguration Overview
    • Applying the Configuration
  • Working with the SDK
    • Create Payment page/frame
    • Get Payment status
    • Make Clearing Payment
    • Make Cancel Payment
    • Make Revoke Payment
    • Add New Card
    • Get Added Cards
    • Remove Added Card
    • Create Card Payment
    • Confirm Card Payment
    • Confirm Direct Payment
  • Google Pay Integration
    • 1. Registering in Google Pay Business Console
    • 2. Integrating the Google Pay SDK into your project
    • 3. Initialization of PaymentsClient and PayButton
    • 4. Creating a Google Pay Transaction
    • 5. Confirming a Google Pay Transaction
  • Error Handling and Results
    • FreedomResult.Success<T>
    • FreedomResult.Error Sub-Types
  • Data Structures
  • Support

Getting Started

 Before you begin integrating the Freedom Merchant SDK into your Android app, ensure you have the following:

  • An Android app project with a minimum API level of 28.

Installation Instructions

1. Add JitPack repository

 Add JitPack to your project's settings.gradle.kts:

dependencyResolutionManagement {
  repositories {
    google()
    mavenCentral()
    maven { url = uri("https://jitpack.io") } // Add this line
  }
}

2. Add Dependency

dependencies {
    implementation("com.github.freedompay-global:merchant-sdk-android:${specifyTheLatestVersion}")
}

3. Sync the project


SDK integration

Initialize

 To initialize the Freedom Merchant SDK, call the create method of the FreedomAPI class. This method requires three parameters:

NOTE

  • Your merchant ID
  • Your merchant secret key
  • The payment region
val merchantId = "123456"
val secretKey = "123456789ABCDEF"
val region = Region.KZ
val freedomApi = FreedomAPI.create(merchantId, secretKey, region)

Table: Region

Enum ConstantDescription
KZKazakhstan region.
RURussia region.
UZUzbekistan region.
KGKyrgyzstan region.

Integrating the PaymentView (Optional)

Adding PaymentView

 Add the PaymentView to your activity's layout file:

<kz.freedompay.paymentsdk.api.view.PaymentView
   android:id="@+id/paymentView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Connecting PaymentView

 Pass the instance of your PaymentView to the SDK:

freedomApi.setPaymentView(paymentView)

Tracking Loading Progress (Optional)

 To track the loading progress of the payment page, use the onLoadingStateChanged listener:

paymentView.onLoadingStateChanged { isLoading: Boolean -> 
    // Handle loading state changes (e.g., show/hide a progress indicator)
}

SDK Configuration

 The SDK's behavior is controlled through its configuration, which you manage using the SdkConfiguration data class. This class acts as a central container, encapsulating two key components: UserConfiguration for customer-specific settings and OperationalConfiguration for general operational parameters.

SdkConfiguration Overview

The SdkConfiguration object is passed to the SDK via freedomApi.setConfiguration().

data class SdkConfiguration(
    val userConfiguration: UserConfiguration = UserConfiguration(),
    val operationalConfiguration: OperationalConfiguration = OperationalConfiguration(),
)

Table: UserConfiguration

 This data class holds customer-specific details.

PropertyTypeDescription
userPhoneString?Customer's phone number. If provided, it will be displayed on the payment page. If null, the user will be prompted to enter it.
userContactEmailString?Customer's contact email.
userEmailString?Customer's email address. If provided, it will be displayed on the payment page. If null, the user will be prompted to enter it.

Table: OperationalConfiguration

 This data class contains general operational settings for the SDK.

PropertyTypeDescriptionDefault Value
testingModeBoolean?Enables or disables test mode. If null, the value is inherited from the merchant's settings. A non-null value will override the merchant's setting.null
languageLanguage?Sets the language of the payment page. See Language enum for available options. If null, the value is inherited from the merchant's settings. A non-null value will override the merchant's setting.null
lifetimeIntDuration, in seconds, for which the payment page remains valid for completing a payment.1800
autoClearingBoolean?Activates automatic clearing of payments. If null, the value is inherited from the merchant's settings. A non-null value will override the merchant's setting.null
checkUrlString?URL to which the payment check will be sent.null
resultUrlString?URL to which the payment result will be sent.null
requestMethodHttpMethod?HTTP method used for requests to checkUrl or resultUrl. See HttpMethod enum. Defaults to GET if checkUrl or resultUrl is set.HttpMethod.GET (if checkUrl or resultUrl is not null, otherwise null)

Table: Language

Enum ConstantDescription
KZSDK uses the Kazakh language.
RUSDK uses the Russian language.
ENSDK uses the English language.

Table: HttpMethod

Enum ConstantDescription
GETSDK uses the HTTP GET method.
POSTSDK uses the HTTP POST method.

Applying the Configuration

 To apply your desired SDK configuration, create an instance of SdkConfiguration and pass it to the freedomApi.setConfiguration() method:

val myUserConfig = UserConfiguration(
    userPhone = "1234567890",
    userEmail = "user@example.com"
)

val myOperationalConfig = OperationalConfiguration(
    testingMode = false,
    language = Language.EN, // Using the provided Language enum
    lifetime = 600, // 10 minutes
    autoClearing = true,
    resultUrl = "https://example.com/result",
    requestMethod = HttpMethod.POST // Using the provided HttpMethod enum
)

val sdkConfiguration = SdkConfiguration(
    userConfiguration = myUserConfig,
    operationalConfiguration = myOperationalConfig
)

freedomApi.setConfiguration(sdkConfiguration)

Working with the SDK

 This section details the primary methods available in the SDK for managing payments within your application.

Create Payment page/frame

 To initiate a new payment transaction and display the payment page, call the createPaymentPage or createPaymentFrame method on your FreedomAPI instance. This method handles the presentation of the payment page/frame within the previously configured PaymentView.

WARNING

These methods require that a PaymentView has been set using freedomApi.setPaymentView() prior to calling them.

 These methods accept several parameters to define the payment details:

ParameterTypeDescription
paymentRequestStandardPaymentRequestEssential details required to initiate a new payment. See StandardPaymentRequest model.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked upon the completion of the payment process. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
val paymentRequest = StandardPaymentRequest(
    amount = 123.45f,
    currency = Currency.KZT, // Using the provided Currency enum
    description = "Monthly Subscription",
    userId = "user12345",
    orderId = "SUB-2025-001",
)
freedomApi.createPaymentPage(
    paymentRequest = paymentRequest
) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Payment page processed successfully.
        }
        is FreedomResult.Error -> {
            // An error occurred during the payment process.
        }
    }
}

Get Payment status

 To retrieve the current status of a previously initiated payment, use the getPaymentStatus method.

 This method takes these parameters:

ParameterTypeDescription
paymentIdLongUnique identifier of the payment you want to check.
onResult(FreedomResult<Status>) -> UnitCallback function that will be invoked with the result of the payment status. See Status model.

 The process returns an FreedomResult<Status> object, which can be either:

  • Success: Contains a Status object.
  • Error: Specifies the type of error that occurred.
freedomApi.getPaymentStatus(paymentId = 123456L) { result: FreedomResult<Status> ->
    when (result) {
        is FreedomResult.Success -> {
            // Payment status retrieved successfully.
        }
        is FreedomResult.Error -> {
            // Failed to retrieve payment status.
        }
    }
}

Make Clearing Payment

INFO

This method is specifically designed for merchants who have auto-clearing disabled in their SDK configuration. Auto-clearing can be managed via the autoClearing property within the OperationalConfiguration of your SdkConfiguration.

 Use the makeClearingPayment method to explicitly initiate the clearing (final capture) of funds for a previously authorized payment. This method gives you the flexibility to clear an amount that may be different from the original amount specified when the payment was created (e.g., for partial captures).

 This method takes these parameters:

ParameterTypeDescriptionConstraints/Notes
paymentIdLongUnique identifier of the payment you want to clear.
amountFloat?Amount to be cleared. If null, the full amount of the original authorized payment will be cleared.Optional. Defaults to null. Must be between 0.01 and 99999999.00 if provided. Cannot exceed the authorized amount.
onResult(FreedomResult<ClearingStatus>) -> UnitCallback function that will be invoked with the result of the clearing operation. See ClearingStatus model.

 The process returns an FreedomResult<ClearingStatus> object, which can be either:

  • Success: Contains a ClearingStatus object.
  • Error: Specifies the type of error that occurred.
freedomApi.makeClearingPayment(paymentId = 123456L) { result: FreedomResult<ClearingStatus> ->
    when (result) {
        is FreedomResult.Success -> {
            // Handle the clearing status.
        }
        is FreedomResult.Error -> {
            // Failed to clear the payment.
        }
    }
}

Make Cancel Payment

INFO

This method is specifically designed for merchants who have auto-clearing disabled in their SDK configuration. Auto-clearing can be managed via the autoClearing property within the OperationalConfiguration of your SdkConfiguration.

 Use the makeCancelPayment method to reverse an authorized payment, effectively unblocking the amount on the customer's card. This ensures that the funds will not be charged.

 This method takes these parameters:

ParameterTypeDescription
paymentIdLongUnique identifier of the payment you want to cancel.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked with the result of the cancellation attempt. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
freedomApi.makeCancelPayment(paymentId = 123456L) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Cancellation attempt completed successfully.
        }
        is FreedomResult.Error -> {
            // Failed to cancel the payment.
        }
    }
}

Make Revoke Payment

 The makeRevokePayment method allows you to process a full or partial refund for a completed payment.

 This method takes these parameters:

ParameterTypeDescriptionConstraints/Notes
paymentIdLongUnique identifier of the payment you want to revoke (refund).
amountFloat?Amount of funds to return. If null, the full amount of the original debited payment will be refunded.Optional. Defaults to null. Must be between 0.01 and 99999999.00 if provided. Cannot exceed the authorized amount.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked with the result of the refund process. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
freedomApi.makeRevokePayment(paymentId = 123456L) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Refund process completed successfully.
        }
        is FreedomResult.Error -> {
            // Failed to process the refund.
        }
    }
}

Add New Card

 The addNewCard method facilitates the secure tokenization and addition of a new payment card to a customer's profile. This process allows future payments to be made without requiring the customer to re-enter their card details.

WARNING

This method requires that a PaymentView has been set using freedomApi.setPaymentView() prior to calling it, as it will display a web-based form within the PaymentView for the customer to securely enter their card details.

 This method takes these parameters:

ParameterTypeDescriptionConstraints/Notes
userIdStringIdentifier for a user to associate this new card with.Must contain 1-50 characters. Also, must match regex ^[a-zA-Z0-9_-]+$.
orderIdString?Unique identifier for this order within your system.Optional. Defaults to null. Must contain 1-50 characters.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked upon the completion of the card addition process. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
freedomApi.addNewCard(
    userId = "user12345",
    orderId = "CARDADD-SESSION-XYZ" // Optional tracking ID
) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Card addition process completed successfully.
        }
        is FreedomResult.Error -> {
            // Failed to add the card.
        }
    }
}

Get Added Cards

 The getAddedCards method allows you to retrieve a list of payment cards that have been previously added and tokenized for a specific user.

 This method takes these parameters:

ParameterTypeDescriptionConstraints/Notes
userIdStringIdentifier of the user whose added cards you wish to retrieve.Must contain 1-50 characters. Also, must match regex ^[a-zA-Z0-9_-]+$.
onResult(FreedomResult<List<Card>>) -> UnitCallback function that will be invoked upon the completion of the card retrieval operation. See Card model.

 The process returns an FreedomResult<List<Card>> object, which can be either:

  • Success: Contains a list of Card objects.
  • Error: Specifies the type of error that occurred.
freedomApi.getAddedCards(userId = "user12345") { result: FreedomResult<List<Card>> ->
    when (result) {
        is FreedomResult.Success -> {
            // List of added cards retrieved successfully.
        }
        is FreedomResult.Error -> {
            // Failed to retrieve added cards.
        }
    }
}

Remove Added Card

 removeAddedCard method allows you to securely remove a previously tokenized payment card associated with a specific user.

 This method takes these parameters:

ParameterTypeDescriptionConstraints/Notes
userIdStringIdentifier of the user from whom the card will be removed.Must contain 1-50 characters. Also, must match regex ^[a-zA-Z0-9_-]+$.
cardTokenStringUnique token of the card to be removed. This token is obtained when the card is added (via addNewCard or retrieved using getAddedCards.Must contain 1 or more characters.
onResult(FreedomResult<RemovedCard>) -> UnitCallback function that will be invoked upon the completion of the card removal operation. See RemovedCard model.

 The process returns an FreedomResult<RemovedCard> object, which can be either:

  • Success: Contains a RemovedCard object.
  • Error: Specifies the type of error that occurred.
freedomApi.removeAddedCard(
    userId = "user12345",
    cardToken = "card-token-123abc"
) { result: FreedomResult<RemovedCard> ->
    when (result) {
        is FreedomResult.Success -> {
            // Card removal process completed successfully.
        }
        is FreedomResult.Error -> {
            // Failed to remove the card.
        }
    }
}

Create Card Payment

 The createCardPayment method is used to initiate a payment using a previously tokenized (saved) card.

INFO

A payment initiated with createCardPayment is a two-stage process. After successfully calling this method, the created payment must be confirmed using either the confirmCardPayment or confirmDirectPayment method to finalize the transaction.

 This method takes these parameters:

ParameterTypeDescription
paymentRequestTokenizedPaymentRequestEssential details required to initiate a new payment with previously tokenized card. See TokenizedPaymentRequest model.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked with the result of the payment initiation. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
val paymentRequest = TokenizedPaymentRequest(
    amount = 123.45f,
    currency = Currency.KZT,
    description = "Monthly Subscription",
    cardToken = "card-token-123abc",
    userId = "user12345",
    orderId = "SUB-2025-001",
)
freedomApi.createCardPayment(
    paymentRequest = paymentRequest
) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Payment initiation completed successfully.
        }
        is FreedomResult.Error -> {
            // Failed to initiate payment with SDK.
        }
    }
}

Confirm Card Payment

 The confirmCardPayment method is used to finalize a payment that was previously initiated with a saved card using createCardPayment.

WARNING

This method requires that a PaymentView has been set using freedomApi.setPaymentView() prior to calling it, as it will display a web-based form within the PaymentView for CVC entry and 3DS authentication.

 This method takes these parameters:

ParameterTypeDescription
paymentIdLongUnique identifier of the payment to confirm. This paymentId is obtained from the createCardPayment method.
onResult(FreedomResult<ConfirmPaymentStatus>) -> UnitCallback function that will be invoked with the result of the refund process. See ConfirmPaymentStatus model.

 The process returns an FreedomResult<ConfirmPaymentStatus> object, which can be either:

  • Success: Contains a ConfirmPaymentStatus object.
  • Error: Specifies the type of error that occurred.
freedomApi.confirmCardPayment(paymentId = 123456L) { result: FreedomResult<ConfirmPaymentStatus> ->
    when (result) {
        is FreedomResult.Success -> {
            // Card payment successfully confirmed.
        }
        is FreedomResult.Error -> {
            // Failed to confirm payment.
        }
    }
}

Confirm Direct Payment

 The confirmDirectPayment method is used to finalize a payment that was previously initiated with a saved card using createCardPayment.

 This method takes these parameters:

ParameterTypeDescription
paymentIdLongUnique identifier of the payment to confirm. This paymentId is obtained from the createCardPayment method.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked with the result of the refund process. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
freedomApi.confirmDirectPayment(paymentId = 123456L) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Direct payment successfully confirmed.
        }
        is FreedomResult.Error -> {
            // Failed to confirm direct payment.
        }
    }
}

Google Pay Integration

 These methods facilitate integrating Google Pay into your application through the SDK. Our SDK's methods bridge your Google Pay implementation with our payment gateway, handling the transaction processing.

 Before you begin, you must register and configure your application in the Google Pay Business Console.

  • 1. Registering in Google Pay Business Console
  • 2. Integrating the Google Pay SDK into your project
  • 3. Initialization of PaymentsClient and PayButton
  • 4. Creating a Google Pay Transaction
  • 5. Confirming a Google Pay Transaction

1. Registering in Google Pay Business Console

NOTE

  • Sign Up for Google Pay Business Console: Visit the Google Pay Business Console, sign in with a Google account, and click "Get Started".
  • Create a Project & Set Up Android Integration: Create a new project, navigate to "Google Pay API", and select "Create new integration". Enter your app's details, including the app name, "Android" as the platform, package name, and the SHA-1 certificate fingerprint.
  • Configure Android Integration: On the "Google Pay API → Android Integration" page, verify the package name and SHA-1 fingerprint to ensure the project is correctly linked to your app.
  • Submit App Screenshots for Approval: Google requires screenshots of your payment flow for review. You must upload screenshots of the item selection, pre-purchase confirmation, payment method selection with the Google Pay option, the Google Pay checkout screen, and the post-purchase confirmation. After uploading, click "Submit for approval" and await Google's review.
  • Go Live with Google Pay: Once approved, switch from test to production mode and test real transactions to ensure smooth payments.

2. Integrating the Google Pay SDK into your project

 After registering, integrate the Google Pay SDK into your app by adding the following dependency to your build.gradle.kts file:

implementation("com.google.android.gms:play-services-wallet:19.2.1")

 Next, update your AndroidManifest.xml to enable the Google Pay API:

<application>
    ...
    <!-- Enables the Google Pay API -->
    <meta-data android:name="com.google.android.gms.wallet.api.enabled"
        android:value="true" />
</application>

 Add PayButton to your XML layout file where you want it to appear:

<com.google.android.gms.wallet.button.PayButton
    android:id="@+id/buttonPaymentByGoogle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

3. Initialization of PaymentsClient and PayButton

 To initialize the payment button and the Google Pay PaymentsClient in your activity:

val googlePayButton: PayButton = findViewById(R.id.buttonPaymentByGoogle)
googlePayButton.initialize(
    ButtonOptions.newBuilder()
        .setButtonType(ButtonType.CHECKOUT)
        .setButtonTheme(ButtonTheme.LIGHT)
        .build()
)

val googlePaymentsClient = Wallet.getPaymentsClient(
    this,
    Wallet.WalletOptions.Builder()
        .setEnvironment(WalletConstants.ENVIRONMENT_PRODUCTION)
        .setTheme(WalletConstants.THEME_LIGHT)
        .build()
)

 The Wallet.getPaymentsClient method is used to get an instance of PaymentsClient. It has the following environments:

ParameterValue
ENVIRONMENT_PRODUCTIONProduction environment
ENVIRONMENT_TESTTest environment

4. Creating a Google Pay Transaction

Step 4.1. Create Google Payment

 The createGooglePayment method is the first step in processing a payment via Google Pay using the SDK. This method initiates a Google Pay payment.

 This method takes these parameters:

ParameterTypeDescription
paymentRequestStandardPaymentRequestEssential details required to initiate a new payment. See StandardPaymentRequest model.
onResult(FreedomResult<GooglePayment>) -> UnitCallback function that will be invoked with the result of the Google payment initiation. See GooglePayment model.

 The process returns an FreedomResult<GooglePayment> object, which can be either:

  • Success: Contains a GooglePayment object.
  • Error: Specifies the type of error that occurred.
val paymentRequest = StandardPaymentRequest(
    amount = 123.45f,
    currency = Currency.KZT,
    description = "Google Pay Purchase",
    userId = "user12345",
)

googlePayButton.setOnClickListener {
    freedomApi.createGooglePayment(
      paymentRequest = paymentRequest
    ) { result: FreedomResult<GooglePayment> ->
        when (result) {
            is FreedomResult.Success -> {
                val googlePayment = result.value
                // Initiates the payment data loading using Google Pay.
                AutoResolveHelper.resolveTask(
                    googlePaymentsClient.loadPaymentData(createPaymentDataRequest()),
                    this,
                    REQUEST_CODE
                )
            }
            is FreedomResult.Error -> {
                // Failed to initiate Google Payment with SDK
            }
        }
    }
}

companion object {
  // The request code that will be used when calling.
  const val REQUEST_CODE = 123
}

NOTE

  • createPaymentDataRequest() is a method that returns a PaymentDataRequest object. This object defines the parameters and requirements for the payment data request, such as payment methods, shipping address, and more.
  • loadPaymentData() initiates an asynchronous task to load payment data using the provided request.
  • AutoResolveHelper.resolveTask<PaymentData>()is used to handle the payment data loading task.
  • REQUEST_CODE is a request code used to identify the result of the task in the onActivityResult method.

Step 4.2. createPaymentDataRequest() implementation

 Here is an example implementation of createPaymentDataRequest():

private fun createPaymentDataRequest(): PaymentDataRequest {
  
    // Creating a new request builder.
    val request = PaymentDataRequest.newBuilder()
        // Setting transaction information.
        .setTransactionInfo( 
            TransactionInfo.newBuilder()
                .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL) // Total price status
                .setTotalPrice("12.00") // Total payment amount.
                .setCurrencyCode("KZT") // Currency code (e.g., 'KZT').
                .build()
        )
        // Specify the payment methods.
        .addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
        .addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
    
        // Setting requirements for the bank card.
        .setCardRequirements(
            CardRequirements.newBuilder()
                // Allowed card networks.
                .addAllowedCardNetworks(
                    Arrays.asList(
                        WalletConstants.CARD_NETWORK_VISA,
                        WalletConstants.CARD_NETWORK_MASTERCARD
                    )
                )
                .build()
        )
  
    // Setting payment method tokenization parameters.
    val params = PaymentMethodTokenizationParameters.newBuilder()
        // Tokenization type (in this case, payment gateway).
        .setPaymentMethodTokenizationType(
          WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY
        )
        // Parameters for the payment gateway (e.g., 'gateway', 'gatewayMerchantId').
        .addParameter("gateway", "yourGateway")
        .addParameter("gatewayMerchantId", "yourMerchantIdGivenFromYourGateway")
        .build()
  
    // Passing tokenization parameters into the request.
    request.setPaymentMethodTokenizationParameters(params)
  
    return request.build()
}

NOTE

  • PaymentDataRequest.newBuilder() creates a new builder for the payment data request.
  • setTransactionInfo() sets transaction information, such as the total payment amount and currency code.
  • PaymentMethodTokenizationParameters.newBuilder() creates a builder for the payment method tokenization parameters.
  • setPaymentMethodTokenizationType() sets the tokenization type (e.g., a payment gateway).
  • addParameter() adds parameters for the payment gateway, such as gateway and gatewayMerchantId.
  • setPaymentMethodTokenizationParameters() sets the tokenization parameters in the payment data request.

Step 4.3. Handling the onActivityResult

 The result of the Google Pay task is handled in the onActivityResult method:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_CODE -> {
            when (resultCode) {
                Activity.RESULT_OK -> {
                    if (data == null) return

                    val googlePayToken = paymentData?.paymentMethodToken?.token ?: return
                    // After receiving the token, we confirm the payment by calling confirmGooglePayment.
                }
                AutoResolveHelper.RESULT_ERROR -> {
                    if (data == null) return

                    val status = AutoResolveHelper.getStatusFromIntent(data)
                    // Handle the error status...
                }
                else -> {}
            }
        }
        else -> {}
    }
}

NOTE

  • onActivityResult is used to handle the results returned by the Google Pay integration activity.
  • data is the object containing the data returned by the activity.
  • Activity.RESULT_OK indicates the successful completion of the operation.
  • AutoResolveHelper.RESULT_ERROR indicates that an error occurred while resolving the request.

5. Confirming a Google Pay Transaction

 The confirmGooglePayment method is the final step in processing a Google Pay transaction with the SDK. After you have successfully obtained the Google Pay token from the Google Pay API (e.g., from PaymentData in onActivityResult), you pass this token along with the googlePayment received from createGooglePayment to this method to finalize the transaction.

 This method takes these parameters:

ParameterTypeDescription
paymentGooglePaymentPayment previously obtained from a successful call to createGooglePayment. See GooglePayment model.
tokenStringEncrypted payment token received from the Google Pay API. This token contains the sensitive card data securely.
onResult(FreedomResult<PaymentResponse>) -> UnitCallback function that will be invoked with the final result of the Google Pay transaction confirmation. See PaymentResponse model.

 The process returns an FreedomResult<PaymentResponse> object, which can be either:

  • Success: Contains a PaymentResponse object.
  • Error: Specifies the type of error that occurred.
sdk.confirmGooglePayment(
    payment = googlePayment,
    token = googlePayToken
) { result: FreedomResult<PaymentResponse> ->
    when (result) {
        is FreedomResult.Success -> {
            // Google Pay payment confirmation successful
        }
        is FreedomResult.Error -> {
            // Failed to confirm Google Pay payment with SDK
        }
    }
}

Error Handling and Results

 All asynchronous operations in the SDK (methods with an onResult callback) return their outcome encapsulated within a FreedomResult sealed interface.

 The FreedomResult interface has two primary states: Success for successful completion and Error for any failures.

Mind Map of Freedom Result

FreedomResult.Success<T>

  • Description: Represents a successful completion of the SDK operation.
  • value: T: Holds the actual result data of the operation. The type T will vary depending on the specific method called (e.g., Payment, List, ConfirmPaymentStatus, Unit).

FreedomResult.Error Sub-Types

 The Error interface is a sealed hierarchy itself, providing distinct types of errors for more precise handling.

1. ValidationError

 Indicates that one or more inputs provided to the SDK method were invalid or did not meet specified constraints (e.g., amount out of range, userId format mismatch).

  • errors: List<ValidationErrorType>: A list detailing all specific validation errors that occurred. For a comprehensive list of types, refer to the ValidationErrorType table.

2. PaymentInitializationFailed

 Indicates a general failure during the initial setup or preparation of a payment, before it reaches the transaction processing stage.

3. Transaction

 Represents an error encountered by the payment gateway during the transaction processing (e.g., card declines, insufficient funds, 3D Secure failures).

  • errorCode: Int: A numerical code representing a specific transaction error. You can find an up-to-date reference of error codes here.
  • errorDescription: String?: A human-readable description of the transaction error, if available.

4. NetworkError

 Represents errors related to network connectivity or API responses. This is a sealed interface with several specific network error types:

  • Protocol: Indicates an issue with the communication protocol or an unexpected response from the API.

    • code: Int: An HTTP status code or an internal protocol error code.
    • body: String?: The raw response body or a human-readable description of the protocol error, if available.
  • Connectivity: Indicates problems related to the device's network connection. This sealed interface includes the following specific errors:

    • ConnectionFailed: The network connection could not be established.
    • ConnectionTimeout: The network request timed out.
    • Integrity: An issue with the integrity of the network connection (e.g., SSL/TLS certificate issues).
  • Unknown: A general network error occurred that does not fall into more specific categories.

5. InfrastructureError

 Represents errors related to the internal state, configuration, or core components of the SDK. This is a sealed interface with several specific infrastructure error types:

  • SdkNotConfigured: The SDK methods were called before freedomApi.setConfiguration() was successfully invoked.
  • SdkCleared: The SDK methods were called after the SDK's internal state was cleared, preventing further operations.
  • ParsingError: An error occurred while parsing data (e.g., a response from the server could not be deserialized).
  • WebView: Errors specifically related to the internal WebView component used for displaying payment pages or frames. This sealed interface includes the following specific errors:
    • PaymentViewIsNotInitialized: A method requiring PaymentView was called, but freedomApi.setPaymentView() has not been called or the view is not ready.
    • Failed: A general error occurred during the payment process within the WebView, without a more specific cause.

Data Structures

 This section provides detailed descriptions of the data classes and enums used throughout the SDK, particularly in the results of various method calls.

StandardPaymentRequest Structure

 The StandardPaymentRequest data class encapsulates the essential details required to initiate a new payment transaction.

ParameterTypeDescriptionConstraints/Notes
amountFloatTotal amount of the payment.Must be between 0.01 and 99999999.00.
currencyCurrency?Currency of the payment. See Currency enum for available options.Optional. Defaults to null.
descriptionStringDescription of the payment.
userIdString?Identifier for the user making the payment.Optional. Defaults to null. Must contain 1-50 characters. Also, must match regex ^[a-zA-Z0-9_-]+$.
orderIdString?Unique identifier for this payment order within your system.Optional. Defaults to null. Must contain 1-50 characters.
extraParamsHashMap<String, String>?Optional map of additional key-value pairs to pass custom data with the payment.Optional. Defaults to null.

TokenizedPaymentRequest Structure

 The TokenizedPaymentRequest data class is used to create payments with a previously saved and tokenized card, requiring the card's unique token along with standard payment details.

ParameterTypeDescriptionConstraints/Notes
amountFloatTotal amount of the payment to be charged to the saved card..Must be between 0.01 and 99999999.00.
currencyCurrency?Currency of the payment. See Currency enum for available options.Optional. Defaults to null.
descriptionStringDescription of the payment.
cardTokenStringUnique token representing the saved card that will be used for this payment. This token is obtained from addNewCard or getAddedCards.Must contain 1 or more characters.
userIdStringIdentifier for the user making the payment.Must contain 1-50 characters. Also, must match regex ^[a-zA-Z0-9_-]+$.
orderIdStringUnique identifier for this payment order within your system.Must contain 1-50 characters.
extraParamsHashMap<String, String>?Optional map of additional key-value pairs to pass custom data with the payment.Optional. Defaults to null.

PaymentResponse Structure

 The PaymentResponse data class represents a successful payment transaction.

PropertyTypeDescription
statusStringStatus of the operation.
paymentIdLongUnique identifier for this payment.
merchantIdStringID of the merchant associated with the payment.
orderIdString?Order ID provided during payment creation.

Status Structure

 Provides comprehensive details about the current state of a payment.

PropertyTypeDescription
statusStringStatus of the operation.
paymentIdLongUnique identifier for this payment.
orderIdString?Order ID provided during payment creation.
currencyStringCurrency code of the payment.
amountFloatOriginal amount of the payment.
canRejectBoolean?Indicates if the payment can still be cancelled.
paymentMethodString?Method used for payment.
paymentStatusString?Current status of the payment.
clearingAmountFloat?Total amount that has been cleared (captured) for this payment.
revokedAmountFloat?Total amount that has been cancelled for this payment.
refundAmountFloat?Total amount that has been refunded.
cardNameString?Name on the card used for the payment.
cardPanString?Masked Primary Account Number (PAN) of the card.
revokedPaymentsList<RevokedPayment>?List of individual cancelled transactions associated with this payment.
refundPaymentsList<RefundPayment>?List of individual refund transactions associated with this payment.
referenceLong?System-generated reference number for the payment.
capturedBoolean?Indicates if the funds for the payment have been captured.
createDateStringDate and time when the payment was created.
authCodeInt?Authorization code for the payment.

RevokedPayment Structure

 Details of an individual cancelled transaction.

PropertyTypeDescription
paymentIdLong?ID of the cancelled payment.
paymentStatusString?Status of the cancelled payment.

RefundPayment Structure

 Details of an individual refund transaction.

PropertyTypeDescription
paymentIdLong?ID of the refund payment.
paymentStatusString?Status of the refund payment.
amountFloat?Amount that was refunded in this transaction.
createDateString?Date and time of the refund.
referenceLong?System-generated reference number for the refund.

ClearingStatus Structure

 Represents the status of a clearing operation.

TypeDescription
Success(val amount: Float)Indicates that the clearing operation was successful. amount: The amount that was successfully cleared.
ExceedsPaymentAmountIndicates that the requested clearing amount exceeded the originally authorized payment amount.
FailedIndicates that the clearing operation failed.

Card Structure

 Represents a single tokenized payment card associated with a user.

PropertyTypeDescription
statusString?Status of the operation.
merchantIdString?ID of the merchant.
recurringProfileIdString?ID assigned to a user's recurring payment profile
cardTokenString?Token used to reference this card for future payments.
cardHashString?Masked Primary Account Number (PAN) of the card.
createdAtString?Date and time when the card was added.

RemovedCard Structure

 Represents the outcome of an attempt to remove a stored card.

PropertyTypeDescription
statusString?Status of the operation.
merchantIdString?ID of the merchant.
cardHashString?Masked Primary Account Number (PAN) of the card.
deletedAtString?Date and time when the card was deleted.

ConfirmPaymentStatus Structure

 Represents the basic outcome of confirming a card payment.

TypeDescription
SuccessIndicates that the card payment confirmation process was completed successfully.
FailureIndicates that the card payment confirmation process failed.

GooglePayment Structure

 The response received after initiating a Google Pay transaction.

PropertyTypeDescription
paymentIdStringUnique identifier for the initiated Google Pay transaction.

ValidationErrorType Structure

Enum ConstantDescription
INVALID_MERCHANT_IDProvided merchant ID is invalid or missing.
INVALID_SECRET_KEYProvided secret key is invalid or missing.
INVALID_PAYMENT_AMOUNTPayment amount is outside the allowed range (0.01 - 99999999.00).
INVALID_ORDER_IDProvided order ID does not meet the specified length constraints.
INVALID_USER_IDProvided user ID does not meet the specified format or length constraints.
INVALID_CARD_TOKENProvided card token does not meet the specified length constraints.

Currency Structure

 The Currency enum defines all supported currency codes that can be used when specifying payment amounts.

Enum ConstantDescription
KZTKazakhstani tenge.
RUBRussian ruble.
USDUS dollar.
UZSUzbek sum.
KGSKyrgyzstani som.
EUREuro.
HKDHong Kong dollar.
GBPBritish pound.
AEDUnited Arab Emirates dirham.
CNYChinese yuan.
KRWSouth Korean won.
INRIndian rupee.
THBThai baht.
UAHUkrainian hryvnia.
AMDArmenian dram.
BYNBelarusian ruble.
PLNPolish złoty.
CZKCzech koruna.
AZNAzerbaijani manat.
GELGeorgian lari.
TJSTajikistani somoni.
CADCanadian dollar.
MDLMoldovan leu.
TRYTurkish lira.

Support

INFO

If you have questions or need help, feel free to reach out! 👋

  • Email: support@freedompay.kz
Modified at 2025-08-13 10:05:30
Previous
Android
Next
Overview