Integrating Paystack with PHP
Tags: webdev, api, php, paystack
Published: 2022-09-23 19:54:18

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

> **Highlight**: I built a better alternative to AbokiFX, you can check it out [here](https://monierate.com).

This guide is a new and updated version of the previous [post](https://dev.to/ijsucceed/how-to-integrate-paystack-payment-system-with-php-5a8m) which has been read more than 25,000 times. There is now a [code repl](https://replit.com/@ijsucceed/paystack-integeration-php?v=1) where you can see all code samples for you to fork and play with.

Paystack is a Modern online and offline payments for Africa.

*Before you can start integrating Paystack, you will need a [Paystack account](https://dashboard.paystack.co/#/signup). Create a [free account](https://dashboard.paystack.co/#/signup) now if you haven't already done so.*

The [Paystack API](https://paystack.com/docs/payments) gives you access to pretty much all the features you can use on your account dashboard and lets you extend them for use in your application. It strives to be RESTful and is organized around the main resources you would be interacting with - with a few notable exceptions.

After creating an account, the next thing is to sign in to your new Paystack account. On your dashboard, you will find your ***public*** and ***secret*** key. We'll make use of the ***public*** and ***secret*** key for this guide.

## Let Dive In

Paystack has two major steps to successfully integrate their API and collect payments on your website: 

1. Initialize a Transaction
2. Verify a Transaction

Successfuly implementing both steps is all you need to move money from your customer to your Paystack account (an eventually to your bank account).

## <a id="initialize"></a> Step 1: Initialize a transaction
Each time your users needs to pay, you'll need to first initialize a transaction. To do this, you either use the Paystack Popup or Paystack Redirect.

Let's initialize a payment with Paystack Popup. Paystack Popup provides a simple and convinient payment flow by displaying a Checkout right on your website; your user make payment without leaving your website - no redirects.

Now, the code below displays a Paystack pay button:

```html
<script src="https://js.paystack.co/v1/inline.js"></script>
<button type="button" onclick="payWithPaystack()"> Pay </button> 
```
The pay button is yet to do what you expect. So if you click on it, nothing will happen. For it to work you need to add the `payWithPaystack()` Javascript function below the button.

Here is the `payWithPaystack()` function provided by Paystack:

```javascript
<script>
  function payWithPaystack(){
    var handler = PaystackPop.setup({
      key: 'paste your key here',
      email: 'customer@email.com',
      amount: 10000,
      ref: ''+Math.floor((Math.random() * 1000000000) + 1), // generates a pseudo-unique reference. Please replace with a reference you generated. Or remove the line entirely so our API will generate one for you
      metadata: {
         custom_fields: [
            {
                display_name: "Mobile Number",
                variable_name: "mobile_number",
                value: "+2348012345678"
            }
         ]
      },
      callback: function(response){
          alert('success. transaction ref is ' + response.reference);
      },
      onClose: function(){
          alert('window closed');
      }
    });
    handler.openIframe();
  }
</script>
```

You need to replace the **key: value 'paste your key here'** with the ***public key*** on your [Paystack account settings](https://dashboard.paystack.com/#/settings/developer).

> Please note that the key to use with Paystack Popup is the ***public key*** and not the **secret key**. You will need the ***secret key*** for verification in step 2.

If you did it correctly and preview your code, on the click of the pay button, a nice looking Paystack Checkout will pop out.

![Paystack Checkout](https://res.cloudinary.com/practicaldev/image/fetch/s----xMo72e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://ijsucceed.com/uploads/paystack_ui.png)

Since you're testing the payment API, you should use a test card. For test cards to work, you use a ***test public key*** instead. And don't forget to replace the test public key with the ***live public key*** on a live website.

![Paystack Test Card in Checkout](https://res.cloudinary.com/practicaldev/image/fetch/s--YREm20aX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://ijsucceed.com/uploads/paystack_integration_ui_testcard.png)

When the payment is successful, your browser will show an alert, indicating a successful transaction, with a reference key.

This leads us to the next step.

## <a id="verify"></a> Step 2: Verifying a transaction

Unless you are not giving any sort of value to a customer, you will have to verify that the transaction is from a real user and not a fraud (or duplicates) before giving value.

In the `payWithPaystack()` function notice the `callback` and `onClose` object key. The `callback` is where you control the user experience if the payment is successful e.g Crediting their balance, redirecting to a success page, etc.

The right thing do within the `callback` method is verify the transaction to confirm the *status*.

To do this, you have to set up a route or page on your server that you pass the transaction reference to. Then from your server, you call the Paystack verify endpoint to confirm the status of the transaction, and then return the response to your frontend.

There are 2 ways you can handle the verification from the callback function:

### 1. Make an AJAX request
This way you make an Ajax request in the `callback` to the endpoint on your backend that handles the transaction verification:

```javascript
callback: function(response){
    console.log('success. ref is ' + response.reference);

    let data = {reference: response.reference};
        
    fetch("ijsucceed.replit.com/paystack-integeration/verify-response.php", {
        method: "POST", 
        body: JSON.stringify(data)
    }).then(res => {
        console.log("Request complete! response:", res);
        alert("Payment complete!")
    });
},
```

The above sends a POST request with `reference` in JSON to a verification endpoint. 

We get the `reference` and make a call to the Paystack Verify Transaction Endpoint to get the status of the transaction. A response is then returned to the frontend: if successful, an alert is fired notifying the user the payment is complete.

You can see the backend verification code for the ajax call on the [code repl](https://replit.com/@ijsucceed/paystack-integeration-php?v=1#verify-redirect.php). 

### 2. Redirect to a server page
This way you redirect the user by setting a `window.location` in the `callback` to the URL where you verify the transaction from Paystack and probably display a success message if the transaction was successful.

```
callback: function(response) {
  window.location = "https://ijsucceed.replit.com/paystack-integeration-php/verify-redirect.php?reference=" + response.reference;
},
```

You can see the verification code for the redirects on the [code repl](https://replit.com/@ijsucceed/paystack-integeration-php?v=1#verify-redirect.php).

Using any of the two ways to verify a transaction depends on how your website is structure or how you want to handle the user experience.

## Handling Webhook
Something may happen during the verification process and your user may not get value (like their balance not updating). This may be their device shutting down or internet failing to connect. Handling Webhook ensure you are still able to provide value to your user irrespective of what happen on the user end.

In some APIs, to manage issues like this, you have to setup a polling system that keeps making request to the Resource server to see if the transaction was successful or not. But polling system has scaling issues and require extra development. 

However, you can fully rely on Paystack Webhook. Just after a transaction is made Paystack sends updates to your server when the status of your request changes. You'll only have to listen to these updates on your backend.

To do this you have create a POST route or page on your backend that recieve the event payload, verify the event is from Paystack, and verify the transaction.

You can find a webhook code on the [project repls](https://replit.com/@ijsucceed/paystack-integeration-php?v=1#webhook.php).

Finally, you'll then need to add your Webhook URL on your [Paystack dashboard](https://dashboard.paystack.com/#/settings/developer). If you are using `.htaccess` on your server, kindly remember to add the trailing `/` to the URL.

## 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 purpose. While the public is for testing purpose.

To enable live mode on paystack, you'll need activate your Paystack account by submiting your business details.

### Conclusion
If you follow the steps, then Congratulation, you just integrated paystack into your website.

Paystack is great payment system with rich set of APIs. I have been integrating Paystack in multiple projects since 2018. In 2020, total combined known value my clients and previous company processed with Paystack is > $2M.