# Android SDK

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

<callout title="Beta Release" type="warning">

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](https://docs.google.com/forms/d/e/1FAIpQLSf8xRyyAp4_QIBCZisdzoMgoIyIlUuju387O6crTs63scdBag/viewform) . We'd love to hear from you.

</callout>

## Introduction

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

## Project requirements

Paystack Android SDK is designed to support [Android 6.0 (API level 23)](https://developer.android.com/tools/releases/platforms#6.0) 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

## Installation

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

<callout title="Latest dependency version" type="info">

You should check [Maven Central](https://central.sonatype.com/artifact/com.paystack.android/paystack-ui/versions) to get the latest version before installation.

</callout>

```groovy
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.

## Paystack 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:

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

```kotlin
import com.paystack.android.core.Paystack
```

</template>

<template v-slot:java="">

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

</template>
</code-tabs>

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

<table>
<thead>
  <tr>
    <th>
      Methods
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        setPublicKey("public-key")
      </code>
    </td>
    
    <td>
      This method is used to set the public key. Without a public key, you can’t complete a transaction.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        setLoggingEnabled(boolean)
      </code>
    </td>
    
    <td>
      This method determines if you get debug logs or not. By default, it’s set to <code>
        false
      </code>
      
       which means you won’t get any debug log.
    </td>
  </tr>
</tbody>
</table>

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

```kotlin
private val paystack = Paystack.builder()
    .setPublicKey("pk_domain_xxxxxxxx")
    .setLoggingEnabled(true)
    .build()
```

</template>

<template v-slot:java="">

```java
private final Paystack paystack = Paystack.builder()
        .setPublicKey("pk_domain_xxxxxxxx")
        .setLoggingEnabled(true)
        .build();
```

</template>
</code-tabs>

## Initialize 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](/api/transaction#initialize) endpoint from your server:

<request-response>
<template v-slot:curl="">

```bash
curl https://api.paystack.co/transaction/initialize \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "customer@email.com",
    "amount": 500000
  }' \
  -X POST
```

</template>

<template v-slot:js="">

```javascript
const https = require("https");

const params = JSON.stringify({
  "email": "customer@email.com",
  "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();
```

</template>

<template v-slot:php="">

```php
<?php
$fields = [
  "email" => "customer@email.com",
  "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;
?>
```

</template>

<template v-slot:response="">

```json
{
  "status": true,
  "message": "Authorization URL created",
  "data": {
    "authorization_url": "https://checkout.paystack.com/nkdks46nymizns7",
    "access_code": "nkdks46nymizns7",
    "reference": "nms6uvr1pl"
  }
}
```

</template>
</request-response>

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.

<callout title="Secret key safeguarding" type="danger">

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.

</callout>

## Payment 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:

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

```kotlin
import com.paystack.android.ui.paymentsheet.PaymentSheet
```

</template>

<template v-slot:java="">

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

</template>
</code-tabs>

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

<table>
<thead>
  <tr>
    <th>
      Arguments
    </th>
    
    <th>
      Example
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Activity
    </td>
    
    <td>
      <code>
        this
      </code>
    </td>
    
    <td>
      This is the reference to your Activity or Fragment
    </td>
  </tr>
  
  <tr>
    <td>
      Callback
    </td>
    
    <td>
      <code>
        paymentResult
      </code>
    </td>
    
    <td>
      This is the method that handles all post-payment processes. It’s argument has the type of <code>
        PaystackSheetResult
      </code>
    </td>
  </tr>
</tbody>
</table>

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

```kotlin
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
}
```

</template>

<template v-slot:java="">

```java
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
}
```

</template>
</code-tabs>

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.

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

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

</template>

<template v-slot:java="">

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

</template>
</code-tabs>

## Payment sheet result

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

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

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

private fun paymentComplete(paymentSheetResult: PaymentSheetResult) {

}
```

</template>

<template v-slot:java="">

```java
import com.paystack.android.ui.paymentsheet.PaymentSheetResult;

private void paymentComplete(PaymentSheetResult paymentSheetResult) {

}
```

</template>
</code-tabs>

The different state that the `PaymentSheetResult` exposes are:

<table>
<thead>
  <tr>
    <th>
      State
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Completed
    </td>
    
    <td>
      The customer completed the payment process. We return a <code>
        paymentCompletionDetails
      </code>
      
       that contains the transaction reference. You should use the transaction reference to verify the transaction status and amount on the server before providing value.
    </td>
  </tr>
  
  <tr>
    <td>
      Cancelled
    </td>
    
    <td>
      The customer cancelled the payment.
    </td>
  </tr>
  
  <tr>
    <td>
      Failed
    </td>
    
    <td>
      An error occurred during the payment process. This result contains an <code>
        error
      </code>
      
      . It may also contain a <code>
        reference
      </code>
      
       for the transaction.
    </td>
  </tr>
</tbody>
</table>

<code-tabs :labels="{"kotlin":"Kotlin","java":"Java"}">
<template v-slot:kotlin="">

```kotlin
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()
}
```

</template>

<template v-slot:java="">

```java
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();
}
```

</template>
</code-tabs>
