# Flutter SDK

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

<callout type="warning">

The Flutter SDK is currently in beta. If you encounter any issues or have suggestions, you can [create an issue](https://github.com/PaystackOSS/paystack_flutter/issues) or [open a PR](https://github.com/PaystackOSS/paystack_flutter/pulls).

</callout>

## Introduction

The Paystack Flutter SDK provides methods that let developers build a secure and convenient payment flow for Flutter applications. Integration is a two-step process:

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

This keeps your secret key away from the client side, which is a secure standard practice.

## Project requirements

When building with the Flutter SDK, ensure your project meets these requirements:

- Flutter >= 3.0.0
- iOS >= 13
- Android minimum SDK 23 and compile SDK 34

<callout type="warning">

Flutter 3.3.0 and below use `FlutterActivity` as the Android base class. Because `FlutterActivity` does not inherit from `ComponentActivity`, you should change it to `FlutterFragmentActivity` in `MainActivity` inside the `android` folder of your project.

</callout>

## Getting started

To add the [Paystack Flutter SDK](https://pub.dev/packages/paystack_flutter_sdk) to your project, run the command below in your terminal:

```bash
flutter pub add paystack_flutter_sdk
```

This command adds the `paystack_flutter_sdk` to your package’s dependencies in the `pubspec.yaml` file and installs it for usage in your project. To use the library, import it in your `.dart` file as shown below:

```dart
import 'package:paystack_flutter_sdk/paystack_flutter_sdk.dart';
```

## 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 type="danger" title="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.

</callout>

## Paystack class

The `Paystack` class provides methods for managing payments in your app. With the SDK imported into your project, initialize this class before using it.

```dart
final _paystack = Paystack();
```

The `Paystack` class exposes the following methods:

- `initialize()`
- `launch()`

### initialize()

This method configures how the SDK operates. It is asynchronous, returns a boolean, and accepts the following parameters:

<table>
<thead>
  <tr>
    <th>
      Parameter
    </th>
    
    <th>
      Type
    </th>
    
    <th>
      Required
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        publicKey
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      Yes
    </td>
    
    <td>
      The public key from your Paystack Dashboard. It should match the secret key used to initialize the transaction
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        enableLogging
      </code>
    </td>
    
    <td>
      Boolean
    </td>
    
    <td>
      No
    </td>
    
    <td>
      Indicates whether you'd like to get Android and iOS logs
    </td>
  </tr>
</tbody>
</table>

```dart
Future<bool> initialize(String publicKey, bool enableLogging)
```

Here’s an example of using the `initialize` method:

```dart
String publicKey = "pk_domain_xxxxxx";

try {
  final response = await _paystack.initialize(publicKey, true); // allow logging
  if (response) {
    log("Successfully initialised the SDK");
  } else {
    log("Unable to initialise the SDK");
  }
} on PlatformException catch (e) {
  log(e.message!);
}
```

### launch()

This method completes the transaction that you initialized on your server and returns a `TransactionResponse`. It loads the payment UI used by your customer and accepts the following parameter:

<table>
<thead>
  <tr>
    <th>
      Parameter
    </th>
    
    <th>
      Type
    </th>
    
    <th>
      Required
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        accessCode
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      Yes
    </td>
    
    <td>
      The <code>
        access_code
      </code>
      
       returned from transaction initialization
    </td>
  </tr>
</tbody>
</table>

```dart
Future<TransactionResponse> launch(String accessCode)
```

Here’s an example of using the `launch` method:

```dart
String reference = "";

try {
  final response = await _paystack.launch(_accessCode);
  if (response.status == "success") {
    reference = response.reference;
    log(reference);
  } else if (response.status == "cancelled") {
    log(response.message);
  } else {
    log(response.message);
  }
} on PlatformException catch (e) {
  log(e.message!);
}
```

When your integration is done right, you need to handle the `TransactionResponse` model. However, there are cases where you could experience some integration bugs. Exceptions are used for handling integration errors in the `Paystack` class methods, all consolidated into the `PaystackException` model. The sections below describe how to handle both the `TransactionResponse` and `PaystackException`.

## TransactionResponse

The `TransactionResponse` model is returned when the SDK is integrated correctly and the payment UI completes its flow. It's tied to the transaction lifecycle and has the following parameters:

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Type
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        status
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      State of the transaction. Possible values are <code>
        success
      </code>
      
      , <code>
        cancelled
      </code>
      
      , and <code>
        failed
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        message
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      A short description of the transaction status
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        reference
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      A unique identifier for post-payment processes. It is only returned when <code>
        status
      </code>
      
       is <code>
        success
      </code>
    </td>
  </tr>
</tbody>
</table>

## PaystackException

`PaystackException` is used for handling integration errors and maps to Flutter's platform-specific `FlutterError` model:

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Type
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        code
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      Indicates the category of error
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        message
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      A short description of the error
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        details
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      Currently returns <code>
        nil
      </code>
      
      , but may include more troubleshooting details in future versions
    </td>
  </tr>
</tbody>
</table>

This means you can parse any exception as shown below:

```dart
try {
  final response = await _paystack.launch(_accessCode);
  // rest of code
} on PlatformException catch (e) {
  log(e.code);
  log(e.message!);
}
```

The following error codes can be returned by `PaystackException`:

<table>
<thead>
  <tr>
    <th>
      Error code
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        INVALID_ARGUMENT
      </code>
    </td>
    
    <td>
      Required parameter values were not provided
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        INITIALIZATION_ERROR
      </code>
    </td>
    
    <td>
      The SDK could not be initialized with the values passed
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        UNSUPPORTED_VERSION
      </code>
    </td>
    
    <td>
      The project does not conform to the SDK requirements
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MISSING_VIEW
      </code>
    </td>
    
    <td>
      The SDK can't find a view controller on iOS or an <code>
        Activity
      </code>
      
       on Android to attach to
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        LAUNCH_ERROR
      </code>
    </td>
    
    <td>
      The payment UI could not be loaded
    </td>
  </tr>
</tbody>
</table>
