Skip to main content

Command Palette

Search for a command to run...

Paystack Payment Integration in Flutter App

Payment integration in flutter app using paystack

Updated
4 min read
Paystack Payment Integration in Flutter App
A

I’m a Software Engineer with over 5+ years of experience in Technology with a track record in building web applications, mobile applications and Technical Writing. Readily available to explore innovations in ICT and creatively use them to build solutions. Advancing my career in software engineering and contributing to the growth of tech communities around the world. I’m also passionate about working with organizations especially tech, security experts and airline industries to learn and also make contributions that will be a legacy.

Tech is Easy to Learn - https://amazon.com/dp/B0B8T838K

In this article, we'll be looking at card payment integration using Paystack package called flutter_paystack

Paystack is a Modern online and offline payments for Africa

Paystack helps businesses in Africa get paid by anyone, anywhere in the world

Head over to Paystack Login to access the dashboard.

If you don't have an account you can create an account here

In your flutter project head over to pubspec.yaml and require the following packages

  flutter_paystack:
 async: ^2.5.0

Please ensure it's properly aligned as shown in the image

pubspec1.png

Run

flutter pub get

Head over to Paystack settings page and click on API keys & Webhook to get the public key for testing

https://dashboard.paystack.com/#/settings/profile

For the purpose of having a clean code the PayButton widget is in button.dart' under the widgets folder and imported at the top of the main.dart file.

Here's is the code for the PayButton widget

import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class PayButton extends StatelessWidget {
  const PayButton({this.callback});

  final VoidCallback callback;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: 45,
        child: ButtonTheme(
          minWidth: MediaQuery.of(context).size.width,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.all(10),
              primary: Colors.blueAccent,
              elevation: 5,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16.0)),
            ),
            onPressed: callback,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Pay Now!!!',
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Here's the link to the PayButton widget file

Next go to main.dart file and add the snippet

Kindly note that the whole code was done in a page feel free to customize it according to your project approach (cubit, bloc, services, etc..)

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_paystack/flutter_paystack.dart';
//PayButton widget import below
import 'package:flutter_paystack_integration/widgets/button.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: PaystackCardMethod());
  }
}

class PaystackCardMethod extends StatefulWidget {
  @override
  _PaystackCardMethodState createState() => _PaystackCardMethodState();
}

class _PaystackCardMethodState extends State<PaystackCardMethod> {
  String publicKeyTest =
      'pk_test_ieu49ej839u984urenewuwe06eishra'; //pass in the public test key obtained from paystack dashboard here

  final plugin = PaystackPlugin();

  @override
  void initState() {
    //initialize the publicKey
    plugin.initialize(publicKey: publicKeyTest);
    super.initState();
  }

  //a method to show the message
  void _showMessage(String message) {
    final snackBar = SnackBar(content: Text(message));
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  //used to generate a unique reference for payment
  String _getReference() {
    var platform = (Platform.isIOS) ? 'iOS' : 'Android';
    final thisDate = DateTime.now().millisecondsSinceEpoch;
    return 'ChargedFrom${platform}_$thisDate';
  }

  //async method to charge users card and return a response
  chargeCard() async {
    var charge = Charge()
      ..amount = 10000 *
          100 //the money should be in kobo hence the need to multiply the value by 100
      ..reference = _getReference()
      ..putCustomField('custom_id',
          '846gey6w') //to pass extra parameters to be retrieved on the response from Paystack
      ..email = 'tutorial@email.com';

    CheckoutResponse response = await plugin.checkout(
      context,
      method: CheckoutMethod.card,
      charge: charge,
    );

    //check if the response is true or not
    if (response.status == true) {
      //you can send some data from the response to an API or use webhook to record the payment on a database
      _showMessage('Payment was successful!!!');
    } else {
      //the payment wasn't successsful or the user cancelled the payment
      _showMessage('Payment Failed!!!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Paystack Integration",
        ),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Container(
          padding: EdgeInsets.all(10),
          child: Center(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              padding: const EdgeInsets.all(15),
//PayButton widget is imported at the top of this file
              child: PayButton(
                //call the chargeCard method
                callback: () => chargeCard(),
              ),
            ),
          )),
    );
  }
}

Next

flutter run

paystack_launch1.png

Click the pay now button

paystack_launch2.png

Card details for testing payments

test card.png

More card details for testing can be found here

Snackbar message when the payment is canceled

paystack snackbar message.png

Here's the link to this tutorial's repository

** Article research credits **

Kindly share with your network and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles
K

Thanks for this tutorial. It works just fine. I'm however having a little challenge in the e-commerce app I'm building while trying to pass the total amount of the cart to Paystack "amount". Whenever I do so, the Paystack popup payment window does not open. Please what could be wrong? Here is my code

chargeCard(BuildContext context) async { var cartItems = Provider.of<CartProvider>(context, listen: false); cartItems.fetchCartItems(); var charge = Charge() ..amount = (cartItems.totalAmount * 100) as int ..reference = _getReference() ..putCustomField('custom_id','846gey6w') //to pass extra parameters to be retrieved on the response from Paystack ..email = 'support@jumbocheap.com';

1
A

Hello Kings, thanks for reaching out. Definitely, something is missing somewhere probably the details from your cartItems are not accessible.

What i could suggest if you've not done so

->Display the details of the cartItems before passing it into the charge function

->Check the value type of the totalAmount if it's an int

->Hardcode an amount to the charge function and give it a try

->Check your network and console for errors

->Relaunch the application

->Check the paystack public key initialization

->Review the state management .... CartProvider

please feel free to reach out if it doesn't work.

Regards

G

Hey there! you did a great job turning those scary codes on other blog to something simple and intuitive... Thanks alot.

1
A

Thanks for the feedback!!!