Integrating mabiola/paystack-php-lib In Your PHP Projects – 1

A few weeks ago, I released a PHP Library or as one of my colleagues will call it, an SDK, for easily integrating Paystack in your PHP projects.

This is the first of a series of posts that will explain as simply as possible, how to use the library in your projects. Througout this series, we will be working with vanila PHP (A PHP project with no framework) so as not to restrict ourselves to a particular “box”.

In this first post, we’ll be setting up the sample project and doing the most basic operation you can do with Paystack – recieving payment from a client.

So to have a general idea of what we will be working on, we will create an order page, and when the user fills in their information and click a pay button, we redirect them to an authorization URL to provide their card details and make their payment. Paystack redirects back to a specified callback URL where we will verify payment and say thanks for a successful payment. Or not.

Creating the project

In this post, I won’t restrict you to my particular way of structuring my web projects, so i’m just going to say, create your project the way you will normally do. However, there are some important files we must both have.

1. A .env file
2. A composer.json file

Create these two files in your root directory and we are good to go.
In your .env file, copy and paste the following;
#PAYSTACK LIB MODE [test | live]
PAYSTACK_MODE = test
#YOUR PAYSTACK KEYS
PAYSTACK_LIVE_PUBLIC_KEY = my_paystack_live_public_keys
PAYSTACK_LIVE_SECRET_KEY = my_paystack_live_secret_key
PAYSTACK_TEST_PUBLIC_KEY = my_paystack_test_public_key
PAYSTACK_TEST_SECRET_KEY = my_paystack_test_secret_key

In your composer.json, add "mabiola/paystack-php-lib" : "~0.1" to your required dependencies

Add the end of this, your composer.json should look something like this;

composer.json

Now, do a composer install, which will download the required package(s). If you don’t have composer on your PC, look at this to see how to install composer.

After you composer install, check your project’s root, you should see a vendor folder where the dependencies your project required are installed.

Now, lets head over to https://paystack.co to sign up so we can replace those keys we placed in our .env.

After signing up, navigate to settings, then to the Developer/API tab to retrieve your API keys.

paystack-settings-page

Under the web hook section, update the Test Callback URL to your preferred call URL. For me in this tutorial, I’ll use http://localhost/paystacksample/payment_verification.php which is where I’ll be verifying if payment is successful or not.

Looks like we all set up and ready to go.

Create A Payment Order Page

On the index.php file, Add the following to create a payment form.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>Paystack Sample</title>

        <!-- Bootstrap Core CSS -->
        <link href="css/bootstrap.min.css" rel="stylesheet">

        <!-- Custom CSS -->
        <link href="css/full-width-pics.css" rel="stylesheet">

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
        <!-- Navigation -->
        <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            <div class="container">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">Paystack Sample</a>
                </div>
                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li>
                            <a href="#">About</a>
                        </li>
                        <li>
                            <a href="#">Services</a>
                        </li>
                        <li>
                            <a href="#">Contact</a>
                        </li>
                    </ul>
                </div>
                <!-- /.navbar-collapse -->
            </div>
        <!-- /.container -->
        </nav>
        <!-- Full Width Image Header with Logo -->
        <!-- Image backgrounds are set within the full-width-pics.css file. -->
        <header class="image-bg-fluid-height">

        </header>
        <!-- Content Section -->
        <section>
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="section-heading">Make Payment (Total Cost: N 200.00)</h1>
                    </div>
                    <div class="col-md-6">
                        <form class="form-horizontal" role="form" action="create_payment.php" method="post">
                            <div class="form-group">
                                <label class="control-label col-sm-2" for="email">Email:</label>
                                <div class="col-sm-10">
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-success">Pay</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>

        <!-- Footer -->
        <footer>
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <p>Copyright &copy; 2016</p>
                    </div>
                </div>
                <!-- /.row -->
            </div>
            <!-- /.container -->
        </footer>

        <!-- jQuery -->
        <script src="js/jquery.js"></script>

        <!-- Bootstrap Core JavaScript -->
        <script src="js/bootstrap.min.js"></script>
    </body>
</html>

Create A Transaction Generation Page

Now, we create a file (create_payment.php) that will handle our form action of generating an authorization url and redirecting to paystack when the pay button is clicked on our index page.

<?php
//Load composer autoload
require_once __DIR__ . '/vendor/autoload.php';
//load environment variables
(new \Dotenv\Dotenv(__DIR__))->load();

//get customer email
$customer_email = $_POST['email'];

//create paystack lib object
$paystack_lib_object = \MAbiola\Paystack\Paystack::make();

//create transaction
try {
    $authorization = $paystack_lib_object->startOneTimeTransaction('20000', $customer_email);
    //we should probably save the reference and email here so we can match/update records
    //redirect to payment authorization URL
    header('Location: ' . $authorization['authorization_url']);
} catch (Exception $e) {
    header("Location: error.php?error={$e->getMessage()}");
}

paystack-payment-page-after-redirect

Verifying Transaction
After the customers pays, they’ll be redirected from the Paystack payment page to our set redirect callback. This is where we’ll verify the transaction and if true, we’ll say thanks to our customer.

<?php
//Load composer autoload
require_once __DIR__ . '/vendor/autoload.php';
//load environment variables
(new \Dotenv\Dotenv(__DIR__))->load();


try {
    //create paystack lib object
    $paystack_lib_object = \MAbiola\Paystack\Paystack::make();
    $verification = $paystack_lib_object->verifyTransaction($_GET['trxref']);
    //if verification successful
    if ($verification) {
        //update customer records in db, probably add authorization for next time

        //redirect to a thank you page
        header('Location: thank_you.php');
    } else {
        header('Location: error.php');
    }

} catch (Exception $e) {
    header("Location: error.php?error={$e->getMessage()}");
}

Conclusion

That basically covers using the library. The full source code of the tutorial can be found on Github here.

Please don’t hesitate to comment below.

Thank you.

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someoneShare on Reddit

Nigerian Software Developer. APIs' Aficionado.

  • Tunde Ifafore

    Thank you malik…impressive!!! We Nigerian developers need to start doing more stuffs like this.

    • Malik Aibola

      Thank you. 🙂

  • chima

    i got this error “Transaction Reference Not Generated.”

  • chike ozulumba

    please keep up the good work

  • chike ozulumba

    im still having problems integrating paystack. would u be kind to point me in the right direction. thank you

  • Emmanuel Ezeofor

    please i have downloaded the code from https://github.com/MalikAbiola/PaystackSample but it does not seem to be working,its throwing this error :Parse error: syntax error, unexpected T_OBJECT_OPERATOR in C:xampphtdocsmainPaystackpayment_verification.php on line 11.please can anybody help me.

    • Malik Aibola

      Hi. first i hope you are using the latest version of the library (1.0.1). if not please update it in your composer.json and run a composer update.

      Also what version of php are you using?

      Anyways, split line 11 to;
      “`
      $dovEnvConfig = new DotenvDotenv(__DIR__);
      $dotEnvConfig->load();
      “`
      Should resolve the issues.

  • Emmanuel Ezeofor

    please i need a quick reply my boss is on my neck on the integration of this payment gateway to our site.please can some one offer me help in this ???

  • Edimaobong U. Matthew

    Hi, I have a big challenge. After successful payment, it has refused to redirect me to the thank you page. How can I fix this up?

  • Emmyz Dot Gold

    Hi Malik, please i will like to know if Paystack can be integrated into a drupal 7 website and if yes; How? Thanks

  • David Ugoagbara

    Hello Malik thanks for this Lib. However, I’m getting this fata error response when I tried to test-run it on my system.
    Fatal error: Uncaught exception ‘DotenvExceptionInvalidPathException’ with message ‘Unable to read the environment file at C:xampphtdocs1dailytaskstrategy.env.’ in C:xampphtdocs1dailytaskstrategyvendorvlucasphpdotenvsrcLoader.php:75 Stack trace: #0 C:xampphtdocs1dailytaskstrategyvendorvlucasphpdotenvsrcLoader.php(52): DotenvLoader->ensureFileIsReadable() #1 C:xampphtdocs1dailytaskstrategyvendorvlucasphpdotenvsrcDotenv.php(91): DotenvLoader->load() #2 C:xampphtdocs1dailytaskstrategyvendorvlucasphpdotenvsrcDotenv.php(48): DotenvDotenv->loadData() #3 C:xampphtdocs1dailytaskstrategycreate_payment.php(5): DotenvDotenv->load() #4 {main} thrown in C:xampphtdocs1dailytaskstrategyvendorvlucasphpdotenvsrcLoader.php on line 75

    • Malik Aibola

      Hi, I believe this is because the dotenv library could not locate your .env file.
      Best bet to fix this is to change the `__DIR__` in `(new DotenvDotenv(__DIR__))->load();` to the path of your .env file

      • David Ugoagbara

        Thanks a lot. I Appreciate the help.

  • Omesu Chinedu

    please am getting a message like this….Fatal error: Class ‘MAbiolapaystackpaystack’ not found in C:xampphtdocsAfreshcreate_payment.php, a little help will be appreciated

  • Sanjula Madumal
  • Joel || GetAvenue

    Can you explain. create_payment.php line 18 especially the authorization_url part

    • Malik Aibola

      When you start a one time transaction, Paystack returns an authorization url where payment (i.e. entering card details, etc) is actually made. Hence the need to redirect to that page.

      • Joel || GetAvenue

        I don’t get, are we suppose to hard code the url, how does it look like, can you give a spinet example. thank you.

        • Malik Aibola

          The URL is not hard coded, it is generated by Paystack and returned via that function. If you take a look at the image right after the code block, you will notice the URL is a Paystack’s URL different from the localhost.

          The flow is simply this;

          1. you start a one time transaction which sends that request to Paystack
          2. Paystack returns a bunch of data, including an authorization URL. This authorization URL is a Paystack’s secured page where the user peforms the transaction, i.e. enters the card details and pay.
          3. after the user pays, you are redirected back to the page you set up in your Paystack callback URL on your dashboard settings, with the transaction reference in the $_GET data.

  • Fikayo Adinlewa

    thanks, your explanation was spot on