PHP Payment Gateway Integration with Rapyd
Tags: payments, fintech, api, php
Published: 2022-07-25 21:37:45


By Samuel Torimiro


Collecting payment online is pretty much a given for any modern businesses, especially those operating internationally. However, integrating a payment gateway to offer online payment can be very complex and requires significant resources to implement from scratch. 

[Rapyd](https://www.rapyd.net/) is a Fintech-as-a-Service platform that helps your company handle payment collection, payment disbursements, and card issuing. It’s integrated into businesses in more than a hundred countries across the globe. With all the services Rapyd provides, you can think of Rapyd as the AWS for fintech.

This tutorial focuses on how to collect payment using the Rapyd Collect API. If you have a PHP application that you want to integrate with a payment gateway, then this tutorial is for you.

## Rapyd Collection API

Rapyd provides a very fast, easy, and secure way to accept payment. Rapyd Collect allows you to accept hundreds of different payment methods globally using the following categories:

- Bank transfer
- Card
- Local e-wallet
- Bank redirect
- Cash
- Rapyd wallet

Using Rapyd, you can choose which country and payment methods you want to accept. With all the different payment options available through Rapyd, you can reach a wider range of customers, thereby increasing sales.

Rapyd is certified as a Level 1 service provider and has also earned the British Standard Institution (BSI) information security certificate. Adherence to these industry security standards ensures that the Rapyd platform is very safe when handling sensitive information.

Subscription billing and invoicing are also possible using the Rapyd Collect API. However, since this tutorial explains how to build a payment gateway with Rapyd, the focus here is on checkout.

Using Rapyd’s checkout page—be it hosted or as a toolkit integration—you can quickly start accepting payment from customers using a variety of methods. The hosted integration redirects your customers to a page hosted on Rapyd servers, while the toolkit integration is embedded in your website as an iframe. This tutorial focuses on the former.

## Implementing Payment in a PHP Application with Rapyd

In the example used in this tutorial, you’ll integrate a payment gateway to collect payment for the online purchase of a book. The step-by-step section below will guide you through how to create a Rapyd Account, how to bootstrap a new PHP application, and how to create and customize a Rapyd checkout page. 

### Step 1: Create a Rapyd Account

Open your browser and navigate to [Rapyd signup](https://dashboard.rapyd.net/sign-up), fill out the form, check your email to verify your account, and log in with your SMS verification code.

![Rapyd client portal](https://imgur.com/rwDYxAi.png)

After logging in, you’ll be presented with the Rapyd Client Portal. In Rapyd, there are two environments: production and sandbox. The sandbox environment is provided for testing purposes. So, you should activate the sandbox environment by clicking the button on the bottom left corner.

![Rapyd sandbox environment](https://imgur.com/BlBt7Sx.png)

### Step 2: Create a New PHP Application

There are many ways to bootstrap a PHP application. This tutorial uses [XAMPP](https://www.apachefriends.org/). Go ahead and [download the latest version of XAMPP](https://www.apachefriends.org/download.html) for your operating system, install the software and open it. Select the **Apache** and **MySQL** modules.

![XAMPP software](https://imgur.com/yo8XNpx.png)

Next, navigate to your drive C on a Windows machine, which is also known as the local disk (either HDD or SSD), or the equivalent if you’re using a Mac or Linux machine. Inside this disk, open the `xampp` folder, then inside it, open the `htdocs` folder. This is where XAMPP expects us to create a PHP project. 

Create a new folder called `Octopus`, and inside this folder, create three new files: `index.php`, `utilities.php`, and `beginners.php`. You should then open this folder in your favorite text editor.

Inside the `index.php` file, add the following code:

```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.0">
    <title>Samuel Torimiro | Software Developer & Technical Writer</title>
</head>
<body>
    <div>
        <h1>Hi! 👋 Welcome to my website</h1>
        <p>My name is Samuel Torimiro. I'm a software developer engineer and technical writer.</p>
        <hr>
        <h1>Checkout my latest books</h1>
        <section>
            <div>
                <h3>PHP for Beginners</h3>
                <p>This book introduces you the basic concepts of the PHP language.</p>
                <bold>$100</bold>
                <br>
                <a href="beginners.php">See more</a>
            </div> 
        </section>
    </div>
</body>
</html>
``` 

Navigate to [http://localhost/octopus/](http://localhost/octopus/), and you should see the following screen.

![Index page](https://imgur.com/DkshPLC.png)

You can see that there’s a welcome page and a link to the book that you want your users to buy.

Inside the `beginners.php` file, add the following code:

```php
<?php

?>

<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.0">
    <title>PHP for Beginners</title>
</head>
<body>
    <div>
        <h1>PHP for Beginners</h1>
        <p>This book introduces you the basic concepts of the PHP language.</p>
        <bold>$100</bold>
        <br>
        <form method="post">
            <input type="hidden" name="amount" value="100">
            <input type="submit" value="Purchase" name="submit">
        </form>
    </div>
</body>
</html>
```

Navigate to [http://localhost/octopus/beginners.php](http://localhost/octopus/beginners.php) or click on the **See more** link on the homepage, and you should see the following screen.

![Beginners page](https://imgur.com/zhJbWTH.png)

This screen displays details about the book and a link to purchase the book. Additionally, you should note that the code above has two sections: the PHP tags and the HTML tags. The PHP tags are currently empty, and this is where you will write the logic to process the payment.

> In the HTML tags, there’s a hidden form that holds the price of the book. Here, you make a POST request to the same file to process the form for us.

### Step 3: Customize the Checkout Page

Navigate back to your [Rapyd client portal](https://dashboard.rapyd.net/home) and make sure you're still in the sandbox environment. At the bottom left corner, click **Settings**, then navigate to **Branding**.

![Rapyd Checkout page 1](https://imgur.com/hr1u4Wz.png)

This is where you can customize your hosted Rapyd checkout page’s look and feel.

![Rapyd Checkout page 2](https://imgur.com/FtSME4M.png)

You can change the logo to reflect your company's logo. Additionally, you can change the color and text of the call to action button. 

There’s also a redirect URL, which specifies where the checkout page sends the user if a transaction is completed or canceled but the necessary URL is not in the code. Therefore, in most cases, this should be your root website URL. Additionally, for this tutorial change the accepted payment method to card payment only.

![Rapyd Checkout page 3](https://imgur.com/dbnw5WZ.png)

### Step 4: Connecting your PHP Application to the Rapyd Server

Inside the `utilities.php` file, add the following code:

```php
<?php
function generate_string($length=12) {
    $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return substr(str_shuffle($permitted_chars), 0, $length);
}


// make_request method - Includes the logic to communicate with the Rapyd sandbox server.
function make_request($method, $path, $body = null) {
    $base_url = 'https://sandboxapi.rapyd.net';
    $access_key = '<your-access-key>';     // The access key received from Rapyd.
    $secret_key = '<your-secret-key>'; //     // Never transmit the secret key by itself.

    $idempotency = generate_string();      // Unique for each request.
    $http_method = $method;                // Lower case.
    $salt = generate_string();             // Randomly generated for each request.
    $date = new DateTime();
    $timestamp = $date->getTimestamp();    // Current Unix time.

    $body_string = !is_null($body) ? json_encode($body,JSON_UNESCAPED_SLASHES) : '';
    $sig_string = "$http_method$path$salt$timestamp$access_key$secret_key$body_string";

    $hash_sig_string = hash_hmac("sha256", $sig_string, $secret_key);
    $signature = base64_encode($hash_sig_string);

    $request_data = NULL;

    if ($method === 'post') {
        $request_data = array(
            CURLOPT_URL => "$base_url$path",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body_string
            
        );
    } else {
        $request_data = array(
            CURLOPT_URL => "$base_url$path",
            CURLOPT_RETURNTRANSFER => true,
        );
    }

    $curl = curl_init();
    curl_setopt_array($curl, $request_data);

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json",
        "access_key: $access_key",
        "salt: $salt",
        "timestamp: $timestamp",
        "signature: $signature",
        "idempotency: $idempotency"
    ));

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

    if ($err) {
        throw new Exception("cURL Error #:".$err);
    } else {
        return json_decode($response, true); 
    }
}
?>
```

Before you can send HTTPS REST requests, Rapyd’s [Request Signatures](https://docs.rapyd.net/build-with-rapyd/reference/message-security#request-signatures) require that you include specified header parameters, which verify and secure the requests. 

You created a `utilities.php` for this purpose, which must be referenced whenever you want to communicate with Rapyd from your code, so they know who you are and that you have a secure connection.

In the above code, take note of the `make_request` function. It receives a `method`, `path`, and `body` as parameters. Inside this function, you have two variables called `access_key` and `secret_key`, which you can retrieve from your [Rapyd client portal](https://dashboard.rapyd.net/home). Once you have retrieved the keys from your client portal, you should also retrieve the `access_key` and `secret_key` from your sandbox environment. You should note that there are two sets of keys, one for production and one for the sandbox.

![Rapyd client portal credentials](https://imgur.com/FWlMQJx.png)

Furthermore, each request has a signature, which is a hash of some concatenated string. Once Rapyd receives the signature from the request, it performs the same calculation and only accepts the request if the signature matches.

### Step 5: Creating the Checkout Page

Inside the `beginners.php` file, in the PHP tags, add the following code:

```php
if(isset($_POST['submit'])) {

    $amount;
    $cancel_checkout_url = "http://example.com/cancel";
    $complete_checkout_url = "http://example.com/complete";
    $country = "US";
    $currency = "USD";
    $language = "en";

    if((int)($_POST['amount']) === 100) {
        $amount = (int)$_POST['amount'];

        $path = "utilities.php";
        include($path);

        $body = [
            "amount" => $amount,
            "complete_checkout_url" => $complete_checkout_url,
            "country" => $country,
            "currency" => $currency,
            "cancel_checkout_url" => $cancel_checkout_url,
            "language" => $language,
                
        ];
        
        try {
            $object = make_request('post', '/v1/checkout', $body);
            $redirect_url = $object["data"]["redirect_url"];
            header("Location: $redirect_url");      
        
        } catch(Exception $e) {
            echo "Error =>$e";
        }
    }
}
```

This code checks if the form was submitted. If it was, you’re ready to make the payment. First, you create several variables, which can be sent as part of the request body. You’re also checking if the actual amount of the book is the same as the amount stated in the hidden input field. Then, you’re linking to the `utilities.php` file in order to gain access to the `make_request` function.

The required parameters Rapyd expects when creating a checkout page are `amount`, `country`, and `currency`. There are also some optional parameters, including `cancel_checkout_url`, `language`, and `complete_checkout_url`, which, as the name implies, is the link your customers will be redirected to after a successful transaction. The  `complete_checkout_url` parameter does not support localhost URLs, so, here you use a hosted domain. 

> For more information, see [Checkout Page Object](https://docs.rapyd.net/en/create-checkout-page.html), where you can find the other fields you can use to configure your checkout page.

Next, you make a POST request to Rapyd to create the checkout page. This will return some data as shown below. 

![Rapyd Checkout API response](https://i.imgur.com/SFsLAep.png) 

However, you’re only retrieving the `redirect_url`. Then, you redirect the user to the hosted checkout page.

Navigate to [http://localhost/octopus/beginners.php](http://localhost/octopus/beginners.php), click on **Purchase**, and you'll be redirected to the hosted checkout page.

![Rapyd hosted checkout page](https://imgur.com/Gi8KY4I.png)

> In the screenshot above, a test sample card is used for the card number (4111 1111 1111 1111), while the other fields can hold any value. However, the expiry date should be a future value.

In this example, the page is only accepting cards, as you specified earlier in the tutorial. To see the payment you just made, navigate back to the Client Portal, go to **Collect**, and in that section, click **Payments**, as shown below.

![Rapyd payment dashboard](https://imgur.com/U1OaEYq.png)

> With the payment received, you can now give customers access to the book, maybe through a link or by some other means.

## Conclusion

This tutorial introduced Rapyd and demonstrated how to use the Rapyd Collect API to implement a Rapyd checkout page and start receiving payments. You learned how to customize this checkout page and how to integrate it into a PHP application.

[Rapyd](https://www.rapyd.net/) is a solution that can power local and cross-border commerce for your business. It’s designed to be a fast and reliable solution for implementing and accepting hundreds of payment methods worldwide. 

You can also find the [complete code](https://github.com/Samuel-2626/php-payment-gateway-using-rapyd) for this tutorial on GitHub.