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 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 toRapyd signup, fill out the form, 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 on the bottom left corner.
Step 2: Create a New PHP Application
There are many ways to bootstrap a PHP application. This tutorial usesXAMPP. Go ahead anddownload the latest version of XAMPP for your operating system, install the software and open it. Select theApache andMySQL 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 thexampp
folder, then inside it, open thehtdocs
folder. This is where XAMPP expects us to create a PHP project.
Create a new folder calledOctopus
, and inside this folder, create three new files:index.php
,utilities.php
, andbeginners.php
. You should then open this folder in your favorite text editor.
Inside theindex.php
file, add the following code:
<htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="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><ahref="beginners.php">See more</a></div></section></div></body></html>
Navigate tohttp://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 thebeginners.php
file, add the following code:
<?php?><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="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><formmethod="post"><inputtype="hidden"name="amount"value="100"><inputtype="submit"value="Purchase"name="submit"></form></div></body></html>
Navigate tohttp://localhost/octopus/beginners.php or click on theSee 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 yourRapyd client portal and make sure you're still in the sandbox environment. At the bottom left corner, clickSettings, then navigate toBranding.
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 theutilities.php
file, add the following code:
<?phpfunctiongenerate_string($length=12){$permitted_chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';returnsubstr(str_shuffle($permitted_chars),0,$length);}// make_request method - Includes the logic to communicate with the Rapyd sandbox server.functionmake_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=newDateTime();$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){thrownewException("cURL Error #:".$err);}else{returnjson_decode($response,true);}}?>
Before you can send HTTPS REST requests, Rapyd’sRequest Signatures require that you include specified header parameters, which verify and secure the requests.
You created autilities.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 themake_request
function. It receives amethod
,path
, andbody
as parameters. Inside this function, you have two variables calledaccess_key
andsecret_key
, which you can retrieve from yourRapyd client portal. Once you have retrieved the keys from your client portal, you should also retrieve theaccess_key
andsecret_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 thebeginners.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 theutilities.php
file in order to gain access to themake_request
function.
The required parameters Rapyd expects when creating a checkout page areamount
,country
, andcurrency
. There are also some optional parameters, includingcancel_checkout_url
,language
, andcomplete_checkout_url
, which, as the name implies, is the link your customers will be redirected to after a successful transaction. Thecomplete_checkout_url
parameter does not support localhost URLs, so, here you use a hosted domain.
For more information, seeCheckout 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 theredirect_url
. Then, you redirect the user to the hosted checkout page.
Navigate tohttp://localhost/octopus/beginners.php, click onPurchase, 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 toCollect, and in that section, clickPayments, 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 thecomplete code for this tutorial on GitHub.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse