PHP Payment Gateway Integration with Rapyd

Community_Team
Mon, 25 Jul 2022 17:30:35 +0000
👓 Blog

By Samuel Torimiro
Photo by Sergey Zolkin

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 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, fill out the form, be sure and tick the ‘I’m a developer’ box, check your email to verify your account, and log in with your SMS verification code.

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 in the bottom left corner.

Step 2: Create a New PHP Application

There are many ways to bootstrap a PHP application. This tutorial uses XAMPP. Go ahead and download the latest version of XAMPP for your operating system, install the software and open it. Select the Apache and MySQL modules.

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:






Samuel Torimiro | Software Developer & Technical Writer



Hi! 👋 Welcome to my website
My name is Samuel Torimiro. I'm a software developer engineer and technical writer.

Checkout my latest books


PHP for Beginners
This book introduces you the basic concepts of the PHP language.
$100

See more






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

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 for Beginners



PHP for Beginners
This book introduces you the basic concepts of the PHP language.
$100









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

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 and make sure you’re still in the sandbox environment. At the bottom left corner, click Settings, then navigate to Branding.

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

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.

Step 4: Connecting your PHP Application to the Rapyd Server

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

<?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 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. 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.

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:

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, 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.

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, click on Purchase, and you’ll be redirected to the hosted checkout page.

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.

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 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 for this tutorial on GitHub.

5 posts - 2 participants