SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

A quick guide on integration Omnipay on PHP projects

If you are in the market for a payment gateway for your PHP project, Omnipay is an easy-to-integrate option that really streamlines the entire process.

Omnipay is a multi-gateway PHP processing library for payment gateways. Omnipay API offers access to 26 official PHP payment integration APIs including PayPal and Stripe. In addition, the API enables 23 third-party PHP payment API integrations including AliPay and CardGate. The best thing about Omnipay is that you can create your own payment gateway API using the library.

In this tutorial, I will discuss the integration of the Omnipay API in a simple project. I will create a separate payment class for verifying credit card information. Next, I will make a payment using Stripe payment gateway. Make sure that you have a valid account on Stripe payment gateway because I will use Stripe API key to make payments through Omnipay.

Install Omnipay package

Create a new folder in the localhost root directory and name it omnipay. In this folder, create a new file and name it composer.json. Now paste the following code in this file:

{
    "require": {
        "omnipay/omnipay": "~2.0"
    },
}

Once done, run the command

composer install

on the command line to install Omnipay package.

Create the Payment Class

The next step is the creation of the Payment class which carries out two important actions:

  • Verify credit card information.
  • Make payment using Omnipay gateway.

In the same directory, create a new folder and name it payment. Inside this folder, create a new file and name it payment.php. Paste the following code in it.

namespace Payment;
use Omnipay\Omnipay;
use Omnipay\Common\CreditCard;
 
class Payment
{
    private $pay;
    private $card;
    function setcard($value){
 
        try{
            $card = [
                'number' => $value['card'],
                'expiryMonth' => $value['expiremonth'],
                'expiryYear' => $value['expireyear'],
                'cvv' => $value['cvv']
            ];
            $ccard = new CreditCard($card);
            $ccard->validate();
            $this->card = $card;
            return true;
        }
        catch(\Exception $ex){
            return $ex->getMessage();
        }
 
    }
 
    function makepayment($value){
        try{
 
            // Setup payment Gateway
            $pay = Omnipay::create('Stripe');
            $pay->setApiKey('YOUR API KEY');
            // Send purchase request
            $response = $pay->purchase(
                [
                    'amount' => $value['amount'],
                    'currency' => $value['currency'],
                    'card' => $this->card
                ]
            )->send();
 
            // Process response
            if ($response->isSuccessful()) {
 
                return "Thankyou for your payment";
 
            } elseif ($response->isRedirect()) {
 
                // Redirect to offsite payment gateway
                return $response->getMessage();
 
            } else {
               // Payment failed
               return $response->getMessage();
            }
        }
        catch(\Exception $ex){
            return $ex->getMessage();
        }
    }
}

Pause for a moment and understand the above code.

First, I declared the namespace Payment and then included other namespaces required by the Omnipay.

?

namespace Payment;
use Omnipay\Omnipay;
use Omnipay\Common\CreditCard;

After that, I created the function setcard($value) to verify and set the credit card. This function takes the credit card information and validates it using $ccard->validate(). If validation fails, an exception is thrown.

function setcard($value){
 
    try{
        $card = [
                'number' => $value['card'],
            'expiryMonth' => $value['expiremonth'],
            'expiryYear' => $value['expireyear'],
            'cvv' => $value['cvv']
    ];
        $ccard = new CreditCard($card);
        $ccard->validate();
        $this->card = $card;
        return true;
    }
    catch(\Exception $ex){
        return $ex->getMessage();
    }
 
}

After verifying the user’s credit card, the function makepayment($value) is used to make the payment. This function uses the array $value ( this array has two important values; the amount of transaction in float format and the currency in which the payment is being made).

function makepayment($value){
    try{
 
        // Setup payment Gateway
        $pay = Omnipay::create('Stripe');
        $pay->setApiKey('Your Stripe API key');
        // Send purchase request
        $response = $pay->purchase(
                [
                    'amount' => $value['amount'],
                'currency' => $value['currency'],
            'card' => $this->card
    ]
    )->send();
 
        // Process response
        if ($response->isSuccessful()) {
 
            return "Thankyou for your payment";
 
        } else {
            // Payment failed
            return $response->getMessage();
        }
    }
    catch(\Exception $ex){
        return $ex->getMessage();
    }
}

The code checks whether the information is in correct format and throws an exception if there is a problem. If everything is in order, the code forwards the payment request. If all goes through, a success message is returned.

I will now add the namespace to the composer autoload. To do this, open composer.json file and add the following code in it after require:

?

{
    "require": {
    "omnipay/omnipay": "~2.0"
},
    "autoload": {
    "psr-4": {
        "Payment\\" : "payment"
    }
}
}

Now on the command line, run the following command:

composer dump-autoload

This will add a reference for the namespace in the composer.

I will now make a payment using this class.

In the omnipay directory, create a new file, index.php and paste the following code in it.

require "vendor/autoload.php";
use Payment\Payment;
$pay = new Payment();
$card['card'] = '4242424242424242';
$card['expiremonth'] = '12';
$card['expireyear'] = '2017';
$card['cvv'] = '123';
$check = $pay->setcard($card);
 
if($check === true){
    $amount['amount'] = "100.00";
    $amount['currency'] = "USD";
    echo $pay->makepayment($amount);
}else{
    echo $check;
}

In the above code, I included the namespace after including vendor/autoload.php.

require "vendor/autoload.php";
use Payment\Payment;

Next, I verified credit card information and then made the payment. In the event of successful execution of the code, you will get the success message, Thank you for your payment.

As you could see, integrating Omnipay package and processing a payment through it is a piece of cake. In just a few lines of code, I have setup a basic payment method.

The End

In this tutorial, I demonstrated how to set up and integrate Omnipay API for credit card payment processing, using Stripe as an example. You could also setup two-step checkout process using Omnipay. On the first page, verify the credit card information and on the second, make the payment. If you have any questions about the code or would like to contribute to the discussion, please leave a comment below.

If you have any questions about the code or would like to contribute to the discussion, please leave a comment below.