Sign in

Developer Tools

Android SDK

View as Markdown

In a nutshell

Use the Paystack Android SDK to accept payments in your Android app.

Beta Release

The Android SDK is currently a beta release. If you encounter any issues or have suggestions while using it, don't hesitate to reach out . We'd love to hear from you.

Copy linkIntroduction

The Android SDK is collection of methods and interfaces that allow developers to build a secure, and convenient payment flow for their Android applications. Integration is a two-step process:

  1. Initiate the transaction on the server
  2. Complete it on the SDK

Copy linkProject requirements

Paystack Android SDK is designed to support Android 6.0 (API level 23) and above. We don't support OS versions below Android 6.0. Before using the SDK, you need to ensure your app meets the following requirements:

  • Android 6.0 (API level 23) and above
  • Android Gradle Plugin 7.2 and above
  • Gradle 7.1.3 and above
  • AndroidX

Copy linkInstallation

To use the SDK, add the paystack-ui in the dependencies block of your app-level build file:

Latest dependency version

You should check Maven Central to get the latest version before installation.

dependencies {
  implementation 'com.paystack.android:paystack-ui:1.0.0'
}

Ensure you sync the project to download the SDK into your project. On successful installation, you’d have access to the UI components and methods to accept payment in your Android app.

Copy linkPaystack builder

The Paystack class uses a builder pattern to handle housekeeping and foundational tasks before the UI components can be used. It's part of the core library:

import com.paystack.android.core.Paystack
import com.paystack.android.core.Paystack;

The table below shows the methods available in the Paystack class:

MethodsDescription
setPublicKey("public-key")This method is used to set the public key. Without a public key, you can’t complete a transaction.
setLoggingEnabled(boolean)This method determines if you get debug logs or not. By default, it’s set to false which means you won’t get any debug log.
private val paystack = Paystack.builder()
    .setPublicKey("pk_domain_xxxxxxxx")
    .setLoggingEnabled(true)
    .build()
private final Paystack paystack = Paystack.builder()
        .setPublicKey("pk_domain_xxxxxxxx")
        .setLoggingEnabled(true)
        .build();

Copy linkInitialize transaction

The SDK requires an access_code to display the UI component that accepts payment. To get the access_code, make a POST request to the Initialize Transaction endpoint from your server:

POSTapi.paystack.co/transaction/initialize

curl https://api.paystack.co/transaction/initialize \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "amount": 500000
  }' \
  -X POST
const https = require("https");

const params = JSON.stringify({
  "email": "[email protected]",
  "amount": 500000
});

const options = {
  hostname: "api.paystack.co",
  port: 443,
  path: "/transaction/initialize",
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
};

const req = https.request(options, (res) => {
  let data = "";
  res.on("data", (chunk) => {
    data += chunk;
  });
  res.on("end", () => {
    console.log(res.statusCode, JSON.parse(data));
  });
});

req.on("error", (error) => {
  console.error(error);
});

req.write(params);
req.end();
<?php
$fields = [
  "email" => "[email protected]",
  "amount" => 500000,
];

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($fields),
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . getenv("PAYSTACK_SECRET_KEY"),
    "Content-Type: application/json",
    "Cache-Control: no-cache",
  ),
));
$response = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . " " . $response;
?>
{
  "status": true,
  "message": "Authorization URL created",
  "data": {
    "authorization_url": "https://checkout.paystack.com/nkdks46nymizns7",
    "access_code": "nkdks46nymizns7",
    "reference": "nms6uvr1pl"
  }
}

On a successful initialization of the transaction, you get a response that contains an access_code. You need to return this access_code back to your mobile app.

Secret key safeguarding

Don't make an API request to the Initialize Transaction endpoint directly on your mobile app because it requires your secret key. Your secret key should only be used on your server where stronger security measures can be put in place.

Copy linkPayment sheet

The PaymentSheet is the UI component that contains the payment form and the available payment channels. It's part of the UI library that can be imported as shown below:

import com.paystack.android.ui.paymentsheet.PaymentSheet
import com.paystack.android.ui.paymentsheet.PaymentSheet;

The PaymentSheet class is initialized in the onCreate method of your Activity or Fragment with two arguments:

ArgumentsExampleDescription
ActivitythisThis is the reference to your Activity or Fragment
CallbackpaymentResultThis is the method that handles all post-payment processes. It’s argument has the type of PaystackSheetResult
private lateinit var paymentSheet: PaymentSheet

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)

  // library initialization code snippets and others go here

  paymentSheet = PaymentSheet(this, ::paymentComplete)

  // more snippet
}
private PaymentSheet paymentSheet;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // library initialization code snippets and others go here

  paymentSheet = new PaymentSheet(this, this::paymentComplete);

  // other code snippet
}

The PaymentSheet comes with a launch method that allows you trigger the display of the component. The launch method takes the access_code from a previously initialized transaction.

fun makePayment() {
  // Pass access_code from transaction initialize call on the server
  paymentSheet.launch(paystack, "ACCESS_CODE")
}
private void makePayment() {
  // Pass access_code from transaction initialize call on the server
  paymentSheet.launch(paystack, "ACCESS_CODE");
}

Copy linkPayment sheet result

The PaymentSheetResult exposes the different states of a transaction. It's the argument type for the PaymentSheet callback:

import com.paystack.android.ui.paymentsheet.PaymentSheetResult

private fun paymentComplete(paymentSheetResult: PaymentSheetResult) {

}
import com.paystack.android.ui.paymentsheet.PaymentSheetResult;

private void paymentComplete(PaymentSheetResult paymentSheetResult) {

}

The different state that the PaymentSheetResult exposes are:

StateDescription
CompletedThe customer completed the payment process. We return a paymentCompletionDetails that contains the transaction reference. You should use the transaction reference to verify the transaction status and amount on the server before providing value.
CancelledThe customer cancelled the payment.
FailedAn error occurred during the payment process. This result contains an error. It may also contain a reference for the transaction.
private fun paymentComplete(paymentSheetResult: PaymentSheetResult) {
  val message = when (paymentSheetResult) {
    PaymentSheetResult.Cancelled -> "Cancelled"
    is PaymentSheetResult.Failed -> {
      Log.e("Something went wrong", paymentSheetResult.error.message.orEmpty(), paymentSheetResult.error)
      // If there's a reference, verify the transaction on your server. The payment may still complete.
      paymentSheetResult.reference?.let { Log.d("Payment reference", it) }
      paymentSheetResult.error.message ?: "Failed"
    }

    is PaymentSheetResult.Completed -> {
      // Verify the transaction on your server with this reference before giving value
      Log.d("Payment successful", paymentSheetResult.paymentCompletionDetails.reference)
      "Successful"
    }
  }

  Toast.makeText(this, "Payment $message", Toast.LENGTH_SHORT).show()
}
private void paymentComplete(PaymentSheetResult paymentSheetResult) {
  String message;

  if (paymentSheetResult instanceof PaymentSheetResult.Cancelled) {
    message = "Cancelled";
  } else if (paymentSheetResult instanceof PaymentSheetResult.Failed) {
    PaymentSheetResult.Failed failedResult = (PaymentSheetResult.Failed) paymentSheetResult;
    Log.e("Payment failed",
        failedResult.getError().getMessage() != null ? failedResult.getError().getMessage() : "Failed",
        failedResult.getError());
    // If there's a reference, verify the transaction on your server. The payment may still complete.
    if (failedResult.getReference() != null) {
      Log.d("Payment reference", failedResult.getReference());
    }
    message = failedResult.getError().getMessage() != null ? failedResult.getError().getMessage() : "Failed";
  } else if (paymentSheetResult instanceof PaymentSheetResult.Completed) {
    // Verify the transaction on your server with this reference before giving value
    Log.d("Payment successful",
        ((PaymentSheetResult.Completed) paymentSheetResult).getPaymentCompletionDetails().getReference());
    message = "Successful";
  } else {
    message = "You shouldn't be here";
  }

  Toast.makeText(this, "Payment " + message, Toast.LENGTH_SHORT).show();
}
Was this page helpful?