Speed up your coding career with in depth case studies and coding tutorials from proven coders.

Paystack Standard: How to integrate paystack with PHP

by Jeremiah Succeed on October 14, 2019
Paystack Standard: How to integrate paystack with PHP

In this guide, you’ll learn how to integrate Paystack payment system on your website with PHP.

I tried to make it as comprehensive as possible; I am open to your feedback and questions.

If you read the introduction of the Paystack Master Series, then you should have a paystack account by now.

Just a reminder;

Before you can start integrating Paystack, you will need a Paystack account. Create a free account now if you haven’t already done so.

Let Dive In

Paystack has some approaches to integrate their API and collect payments on your websites. But this guide explains the Paystack Standard with PHP.

Paystack Standard

This is the standard approach of collecting payments on your web app. The standard approach is a better and secure way to integrate within your PHP web app.

Now, for this approach to work on your server you need to confirm that your server can conclude a TLSv1.2 connection. Most up-to-date servers have this capability. If you’re on a web server, you contact your service provider for guidance if you have any SSL errors.

For this approach, you’ll need to create two new files.

   initialize.php
   callback.php

Initialize a transaction

Paste the following code inside the initialize.php

<?php
$curl = curl_init();

$email = "your@email.com";
$amount = 30000;  //the amount in kobo. This value is actually NGN 300

// url to go to after payment
$callback_url = 'myapp.com/pay/callback.php';  

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'amount'=>$amount,
    'email'=>$email,
    'callback_url' => $callback_url
  ]),
  CURLOPT_HTTPHEADER => [
    "authorization: Bearer sk_test_36658e3260b1d1668b563e6d8268e46ad6da3273", //replace this with your own test key
    "content-type: application/json",
    "cache-control: no-cache"
  ],
));

$response = curl_exec($curl);
$err = curl_error($curl);

if($err){
  // there was an error contacting the Paystack API
  die('Curl returned error: ' . $err);
}

$tranx = json_decode($response, true);

if(!$tranx->status){
  // there was an error from the API
  print_r('API returned error: ' . $tranx['message']);
}

// comment out this line if you want to redirect the user to the payment page
print_r($tranx);
// redirect to page so User can pay
// uncomment this line to allow the user redirect to the payment page
header('Location: ' . $tranx['data']['authorization_url']);

The initialize.php will initialize your user transaction with the paystack API and redirect the user to a Paystack payment page.

On a live web server, replace the test key with your own live secret key. Look for the line with comment ‘replace this with your own test key’ and remove the sk_test_xxxxxxxxx to your secretkey.

Note that, the $email and $amount are the user’s email address and the amount they are to pay while the $callback_url is the URL the user will be redirected to after payment.

$email and $amount are compulsory parameters. If your app don’t collect user email, then you can set your own default email.

Bringing the user back to your site is an important part of the standard approach, so don’t forget to change the $callback_url to that of your app.

The email and amount can be collected through forms or whatever way you intended.

The $amount is in Nigeria Kobo, so always add double zeros on any amount you are charging the user. e.g 100000 for 1000

You can use this money tool for accuracy on the complicated amount.

When the users enter their card details, Paystack will validate and charge the card. When successful, it will then redirect back to your callback_url set when initializing the transaction or on your dashboard at https://dashboard.paystack.co/#/settings/developer .

If your callback_url is not set, your customers see a “Transaction was successful” message without any redirect.

Verify the Transaction

Now, since the callback is specified in your code, you need to set the callback.php. This enables you to verify the user transaction before giving any sort of value, like recording the transaction to a database.

Enter the code below inside the callback.php

<?php

$curl = curl_init();
$reference = isset($_GET['reference']) ? $_GET['reference'] : '';
if(!$reference){
  die('No reference supplied');
}

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($reference),
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "accept: application/json",
    "authorization: Bearer sk_test_36658e3260b1d1668b563e6d8268e46ad6da3273",
    "cache-control: no-cache"
  ],
));

$response = curl_exec($curl);
$err = curl_error($curl);

if($err){
    // there was an error contacting the Paystack API
  die('Curl returned error: ' . $err);
}

$tranx = json_decode($response);

if(!$tranx->status){
  // there was an error from the API
  die('API returned error: ' . $tranx->message);
}

if('success' == $tranx->data->status){
  // transaction was successful...
  // please check other things like whether you already gave value for this ref
  // if the email matches the customer who owns the product etc
  // Give value
  echo "<h2>Thank you for making a purchase. Your file has bee sent your email.</h2>";
}

If you follow the steps correctly. You will get the following result.

Showing result in gif

In case you run into the error below.

API returned error: Transaction reference not found

Then make sure the SECRET_KEY in callback.php is the same as the one used in the initialize.php and the callback URL should be a live domain.

Congratulation, you just integrated paystack payment into your web app.

Hints

Go to dashboard > settings > webhook/keys to get your public and secret key for both the live and test.

The live keys are used for production. While the test keys are for testing purposes.

Note, for your app to process more than 2 million Naira payment, you’ll need to verify your business.

Support

I’d like to thank SitePoint for sponsoring this site. They provide fresh monthly Web design and development books and videos from experts like Chris Coyier and Tiffany Brown for a small fee of $9 monthly. They’ve been my favourite learning resource for years now, I’d certainly recommend them.

Reply

Thank you for taking the time to read. If you want to reply to this post, kindly reply the thread on Twitter.