Sign in

Developer Tools

Flutter SDK

View as Markdown

In a nutshell

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

Warning

The Flutter SDK is currently in beta. If you encounter any issues or have suggestions, you can create an issue or open a PR.

Copy linkIntroduction

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.

Copy linkProject 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

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.

Copy linkGetting started

To add the Paystack Flutter SDK to your project, run the command below in your terminal:

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:

import 'package:paystack_flutter_sdk/paystack_flutter_sdk.dart';

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 linkPaystack 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.

final _paystack = Paystack();

The Paystack class exposes the following methods:

  • initialize()
  • launch()

Copy linkinitialize()

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

ParameterTypeRequiredDescription
publicKeyStringYesThe public key from your Paystack Dashboard. It should match the secret key used to initialize the transaction
enableLoggingBooleanNoIndicates whether you'd like to get Android and iOS logs
Future<bool> initialize(String publicKey, bool enableLogging)

Here’s an example of using the initialize method:

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!);
}

Copy linklaunch()

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:

ParameterTypeRequiredDescription
accessCodeStringYesThe access_code returned from transaction initialization
Future<TransactionResponse> launch(String accessCode)

Here’s an example of using the launch method:

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.

Copy linkTransactionResponse

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:

FieldTypeDescription
statusStringState of the transaction. Possible values are success, cancelled, and failed
messageStringA short description of the transaction status
referenceStringA unique identifier for post-payment processes. It is only returned when status is success

Copy linkPaystackException

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

FieldTypeDescription
codeStringIndicates the category of error
messageStringA short description of the error
detailsStringCurrently returns nil, but may include more troubleshooting details in future versions

This means you can parse any exception as shown below:

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:

Error codeDescription
INVALID_ARGUMENTRequired parameter values were not provided
INITIALIZATION_ERRORThe SDK could not be initialized with the values passed
UNSUPPORTED_VERSIONThe project does not conform to the SDK requirements
MISSING_VIEWThe SDK can't find a view controller on iOS or an Activity on Android to attach to
LAUNCH_ERRORThe payment UI could not be loaded
Was this page helpful?