How to Call Virtually Any Payment API With the Omnipay SDK

Integrating payment gateways is an essential stage of any project that sells products, services, or both. A reliable, easy-to-integrate and manage payment gateway is an essential part of the PHP developers’ arsenal.

A recent entry on the scene of payment gateways is Omnipay. Omnipay is a PHP processing library that supports 26 reputable payment gateways, including PayPal and Stripe. To further sweeten the pot, Omnipay supports 23 third-party PHP payment API integrations created by other users, including AliPay and CardGate. In addition, you can create and set up a customized payment gateway API using Omnipay.

Before getting started with Omnipay make sure you have a XAMPP, WAMP, or an equivalent custom stack running on your local machine.

To highlight Omnipay’s capabilities, I’ll create a class that first verifies a customer’s credit card information and then uses the SDK for making a payment through a Stripe payment gateway. Before proceeding further, make sure that you have a valid Stripe payment gateway account If you don’t have one, click here to register. Once you have created an account on Stripe go to your Stripe dashboard. On your dashboard select account settings by clicking on the Your Account drop-down menu.

Now click on API Keys.

We are going to use test Secret key in this blog.

Installing Omnipay

The first step of the project is the installation of Omnipay. For this, create a new folder where your PHP codes are running from; for XAMPP, that’s htdocs and for WAMP, its www. Name it Omnipay.

Next, create a file in the folder and name it composer.json. Open the file in your preferred text editor (Sublime, Atom, emacs, etc.) and paste in the following code:

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

The basic setup is now complete. To finalize the installation, run the command composer install to install all the required dependencies.

Creating the Payment Class

Once the installation is successful, you’re ready to create the Payment class, which forms the bulk of the code. This class performs two important functions. The first function is the verification of the customer’s credit card information. The second function is the mechanism that makes the actual payment using the Omnipay gateway.

To make the class, create a new folder in the Omnipay folder and name it Payment. Inside the payment folder, create a file with the name payment.php. Open the file in your editor and paste in the following code:

<?php
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();
      }
  }
}
?>

Analysis of the Payment Class

The first step of the class’s code declares the namespaces. I use Payment (my own namespace) and Omnipay (the class made available in the library)  

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

The function setcard($value) first verifies the credit card information and then saves the credit card information in variable. This function uses $ccard->validate() for validation of the credit card information. If the credit card information fails validation, the function throws an exception:

    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();
      }
      
  }

Next, turn to the function makepayment($value). This function, as the name suggests, makes the payment. The important parameter is the array $value, which has the total amount of transaction as a float value and the currency in which the payment is being made. The code also throws an exception in case of any problems. If there are none, the code forwards the payment request and returns a success message.

  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();
      }
  }

Automating the Process

The next step is the addition of the namespace to the composer autoload. This step is essential to the autoloading of the Payment class.

Open the composer.json file in your editor and add the following code after the label require:

,
  "autoload": {
    "psr-4": {
        "Payment\\" : "payment"
    }  
  }

Your new file will look like this:

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

At the command line, run composer dump-autoload to add a reference for the namespace in the composer.

Making the Payment

Next is to make a payment based on the class.

In the Omnipay folder, create a new file and name it index.php. Open the file in the editor and paste in the following code:

<?php
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;
}

Analyzing the Payment Code

I started index.php with the inclusion of the namespace:

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

Next is the verification of the customer’s credit card information. If all goes well, the payment is accepted and the customer is notified accordingly. To check the status of the payment, go to your Stripe dashboard; it shows if the payment has indeed been made.

Have a few thoughts about the Omnipay API? Be sure to leave and comment and tell us what you think.

Ahmed Khan is the PHP Community Manager at Cloudways and writes about MySQL and PHP. An experienced professional in PHP related topics, Ahmed loves to spend his free time watching The Flash, Game of Thrones and reading DC Comics. Follow him on Twitter and Facebook to keep up with his work and insights on PHP hosting.
 

Comments