PayPal offers a variety of APIs for integrating a payment gateway into a web application. The Standard Payment Gateway is commonly used to accept PayPal payments online. Using PHP, you can quickly incorporate PayPal’s basic payment gateway into your website. However, PayPal Payments Pro is the best option for accepting credit card payments on your website. The PayPal Pro payment gateway enables you to take credit or debit card payments online.
The biggest benefit of using PayPal Payments Pro is that the consumer can pay with their credit card without having to have a PayPal account. Furthermore, the payment can be performed entirely within your website; the buyer does not need to leave it to complete the transaction. Using the PHP library, you can quickly incorporate the PayPal Pro payment gateway into your web application. PayPal Pro PHP library must be integrated into the CodeIgniter framework if your website is created with the CodeIgniter framework. We’ll teach you how to use the PayPal Pro payment gateway in CodeIgniter to take credit or debit card payments on your website in this tutorial.
Sign up for a PayPal Sandbox Account
Before going live with the PayPal payment gateway, make sure the payment procedure is working smoothly. With a demo PayPal account, you may test the transaction and payment process in the PayPal Sandbox environment. To begin, go to the PayPal Developer interface and create a PayPal Sandbox account. The API credentials can be found in your PayPal sandbox business account. Your company account must be a Website Payments Pro account in order to use the PayPal Pro payment gateway API. Upgrade your PayPal business account to Website Payments Pro if you want to accept credit card payments.
Create a PayPal website payment pro sandbox account using this detailed guide – Making a PayPal Sandbox Account and a Website Payments Pro Account
You’ll find the NVP/SOAP Sandbox API Credentials under the API Credentials tab after creating a PayPal business pro account.
When calling the PayPal Pro payment gateway API, the API credentials must be supplied. For later usage in the script, copy the API credentials (Username, Password, and Signature).
Take a look at the file structure before getting started with the PayPal Pro payment gateway in CodeIgniter.
codeigniter_paypal_pro_integration/ ├── application/ │ ├── controllers/ │ │ └── Products.php │ ├── libraries/ │ │ └── PaypalPro.php │ ├── models/ │ │ └── Product.php │ └── views/ │ └── products/ │ ├── index.php │ └── purchase.php └── assets/ ├── css/ │ └── style.css └── js/ ├── jquery.min.js └── creditCardValidator.js
Make a database table.
Two tables in the database must be built to store the items and transaction details.
The following SQL builds a products table in the MySQL database with some basic fields for storing product information.
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`number` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`price` float(10,2) NOT NULL,
`currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL builds an orders table in the MySQL database with some basic fields for recording payment information.
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`buyer_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`buyer_email` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
`card_num` bigint(20) NOT NULL,
`card_cvc` int(5) NOT NULL,
`card_exp_month` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
`card_exp_year` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
`paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`paid_amount_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`payment_txn_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`payment_status` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Specify the often used library (database) and helper (url) to load automatically in autoload.php.
$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');
paypal.php: This file contains the PayPal Pro library’s configuration variables. Specify your PayPal Business Pro account’s API credentials (Username, Password, and Signature).
sandbox – Choose between Sandbox and Live Environment (TRUE/FALSE).
paypal api username — Enter the PayPal Business Pro account’s API username.
paypal api password — Enter the PayPal Business Pro account’s API password.
paypal api signature — Set the PayPal Business Pro account’s API signature.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// ------------------------------------------------------------------------
// PayPalPro library configuration
// ------------------------------------------------------------------------
// PayPal environment, Sandbox or Live
$config['sandbox'] = TRUE; // FALSE for live environment
// PayPal API credentials
$config['paypal_api_username'] = 'PayPal_API_Username';
$config['paypal_api_password'] = 'PayPal_API_Password';
$config['paypal_api_signature'] = 'PayPal_API_Signature';
the library (PaypalPro.php)
The PaypalPro CodeIgniter Library allows you to incorporate the PayPal Pro payment gateway into your CodeIgniter 3 programme. A configuration file called paypal.php is required by this library. Place the PaypalPro.php and paypal.php files in the application/libraries/ and application/config/ directories, respectively. The PayPal Pro CodeIgniter library is included in the source code and does not need to be downloaded separately.
PaypalPro is a library class that is used to
Use an API signature to make the API call to PayPal.
Check the API response for errors.
In an associative array, save the API answer.
the supervisor (Products.php)
Using the PayPal Pro CodeIgniter library, the Products controller manages the product listing and payment process.
Load the Product model with __construct().
index() – Using the Product model’s getRows() function, retrieve product data from the database.
Pass data to the view for the web page’s product listing.
purchase() – Using the product ID, fetch particular product info from the database.
To display product details on the payment page, pass data to the view.
payment() — This method is called by an Ajax request, and it manages credit card payments using the PaypalPro PHP package.
Using the Product model’s getRows() function, retrieve product details depending on the ID.
From the POST method, get the buyer’s information (name, nation, city, and zip code).
The POST method can be used to get credit card information (Card Number, Card Type, Expiry Month, Expiry Date, and CVV number).
For CodeIgniter, load the PaypalPro library.
Call the PaypalPro class’s paypalCall() function and give the relevant data as an array ($paypalParams).
Insert the transaction data into the MySQL database if the charge is successful.
The payment status is returned to the Ajax request in JSON format.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
function __construct(){
parent::__construct();
// Load product model
$this->load->model('product');
}
function index(){
$data = array();
// Get products data from the database
$data['products'] = $this->product->getRows();
// Pass products data to the view
$this->load->view('products/index', $data);
}
function purchase($id){
// Get product data from the database
$data['product'] = $this->product->getRows($id);
// Pass product data to the view
$this->load->view('products/purchase', $data);
}
function payment($id){
$data = array();
// Get product data from the database
$product = $this->product->getRows($id);
if(!empty($product) && $_SERVER['REQUEST_METHOD'] == 'POST'){
// Buyer information
$name = $_POST['name_on_card'];
$nameArr = explode(' ', $name);
$firstName = !empty($nameArr[0])?$nameArr[0]:'';
$lastName = !empty($nameArr[1])?$nameArr[1]:'';
$city = 'Charleston';
$zipcode = '25301';
$countryCode = 'US';
// Card details
$creditCardNumber = trim(str_replace(" ","",$_POST['card_number']));
$creditCardType = $_POST['card_type'];
$expMonth = $_POST['expiry_month'];
$expYear = $_POST['expiry_year'];
$cvv = $_POST['cvv'];
// Load PaypalPro library
$this->load->library('paypalpro');
// Payment details
$paypalParams = array(
'paymentAction' => 'Sale',
'itemName' => $product['name'],
'itemNumber' => $product['number'],
'amount' => $product['price'],
'currencyCode' => $product['currency'],
'creditCardType' => $creditCardType,
'creditCardNumber' => $creditCardNumber,
'expMonth' => $expMonth,
'expYear' => $expYear,
'cvv' => $cvv,
'firstName' => $firstName,
'lastName' => $lastName,
'city' => $city,
'zip' => $zipcode,
'countryCode' => $countryCode,
);
$response = $this->paypalpro->paypalCall($paypalParams);
$paymentStatus = strtoupper($response["ACK"]);
if($paymentStatus == "SUCCESS"){
// Transaction info
$transactionID = $response['TRANSACTIONID'];
$paidAmount = $response['AMT'];
$currency = $response['CURRENCYCODE'];
// Insert the transaction data in the database
$txnData['product_id'] = $id;
$txnData['buyer_name'] = $name;
$txnData['buyer_email'] = '';
$txnData['card_num'] = $creditCardNumber;
$txnData['card_cvc'] = $cvv;
$txnData['card_exp_month'] = $expMonth;
$txnData['card_exp_year'] = $expYear;
$txnData['paid_amount'] = $paidAmount;
$txnData['paid_amount_currency'] = $currency;
$txnData['payment_txn_id'] = $transactionID;
$txnData['payment_status'] = $paymentStatus;
$insert = $this->product->insertOrder($txnData);
$data['status'] = 1;
$data['orderID'] = $transactionID;
}else{
$data['status'] = 0;
}
}
// Transaction status
echo json_encode($data);
}
}
Modeling (Product.php)
The Product model is in charge of database-related tasks (fetch and insert).
__construct() — This function defines the names of the database tables.
getRows() – Returns an array containing the records from the products table.
insertOrder() – Updates the orders table with payment and order information.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends CI_Model{
function __construct() {
$this->proTable = 'products';
$this->ordTable = 'orders';
}
/*
* Fetch products data from the database
* @param id returns a single record if specified, otherwise all records
*/
public function getRows($id = ''){
$this->db->select('*');
$this->db->from($this->proTable);
$this->db->where('status', '1');
if($id){
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('name', 'asc');
$query = $this->db->get();
$result = $query->result_array();
}
// return fetched data
return !empty($result)?$result:false;
}
/*
* Insert data in the database
* @param data array
*/
public function insertOrder($data){
if(empty($data['created'])){
$data['created'] = date("Y-m-d H:i:s");
}
if(empty($data['modified'])){
$data['modified'] = date("Y-m-d H:i:s");
}
$insert = $this->db->insert($this->ordTable, $data);
return $insert?true:false;
}
}
Consider this: (products)
The Product controller’s view files are located in the products/ directory.
products/index.php is the first page of the website.
All of the products are retrieved from the database and displayed on the webpage with a Buy button.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Products - PayPal Pro Integration in CodeIgniter</title>
<!-- stylesheet file -->
<link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>">
</head>
<body>
<div class="container">
<!-- List all products -->
<?php if(!empty($products)){ foreach($products as $row){ ?>
<div class="pro-box">
<h4>Product Number: <b><?php echo $row['number']; ?></b></h4>
<h4>Product Name: <b><?php echo $row['name']; ?></b></h4>
<h4>Price: <b>$<?php echo $row['price'].' '.$row['currency']; ?></b></h4>
<div class="buy">
<a href="<?php echo base_url('products/purchase/'.$row['id']); ?>">Purchase</a>
</div>
</div>
<?php } }else{ ?>
<p>Product(s) not found...</p>
<?php } ?>
</div>
</body>
</html>
2. purchase.php (Products/Purchase.php)
The buyer’s credit card information is captured on the purchase page and sent to the payment() method for payment processing via an Ajax request.
Form for Credit Card:
The details of the selected product are presented.
To provide credit card information, an HTML form is shown (Card Number, Expiration Date, CVC Number, and Card Holder Name).
<div class="card-payment">
<h3>PayPal Pro Integration in CodeIgniter</h3>
<!-- Card from -->
<div id="paymentSection">
<form method="post" id="paymentForm">
<h4>Item: <b><?php echo $product['name']; ?></b></h4>
<h4>Payable amount: <b>$<?php echo $product['price'].' '.$product['currency']; ?></b></h4>
<ul>
<li>
<label>Card Number</label>
<input type="text" placeholder="1234 5678 9012 3456" maxlength="20" id="card_number" name="card_number">
</li>
<li class="vertical">
<ul>
<li>
<label>Expiry Month</label>
<input type="text" placeholder="MM" maxlength="5" id="expiry_month" name="expiry_month">
</li>
<li>
<label>Expiry Year</label>
<input type="text" placeholder="YYYY" maxlength="5" id="expiry_year" name="expiry_year">
</li>
<li>
<label>CVV</label>
<input type="text" placeholder="123" maxlength="3" id="cvv" name="cvv">
</li>
</ul>
</li>
<li>
<label>Name on Card</label>
<input type="text" placeholder="John Doe" id="name_on_card" name="name_on_card">
</li>
<li>
<input type="hidden" name="card_type" id="card_type" value=""/>
<input type="button" name="card_submit" id="cardSubmitBtn" value="Proceed" class="payment-btn" disabled="true" >
</li>
</ul>
</form>
</div>
<div class="flink">
<a href="<?php echo base_url('products/'); ?>">Back to Products</a>
</div>
</div>
Include the jQuery and credit card validator plugin libraries for card form validation.
<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<!-- Card validation library -->
<script src="<?php echo base_url('assets/js/creditCardValidator.js'); ?>"></script>
To validate the credit card number, the creditCardValidator jQuery plugin is utilised. jQuery’s cardFormValidate() function allows you to validate card data.
/* Credit card validation code */
function cardFormValidate(){
var cardValid = 0;
// Card number validation
$('#card_number').validateCreditCard(function(result) {
var cardType = (result.card_type == null)?'':result.card_type.name;
if(cardType == 'Visa'){
var backPosition = result.valid?'2px -163px, 260px -87px':'2px -163px, 260px -61px';
}else if(cardType == 'MasterCard'){
var backPosition = result.valid?'2px -247px, 260px -87px':'2px -247px, 260px -61px';
}else if(cardType == 'Maestro'){
var backPosition = result.valid?'2px -289px, 260px -87px':'2px -289px, 260px -61px';
}else if(cardType == 'Discover'){
var backPosition = result.valid?'2px -331px, 260px -87px':'2px -331px, 260px -61px';
}else if(cardType == 'Amex'){
var backPosition = result.valid?'2px -121px, 260px -87px':'2px -121px, 260px -61px';
}else{
var backPosition = result.valid?'2px -121px, 260px -87px':'2px -121px, 260px -61px';
}
$('#card_number').css("background-position", backPosition);
if(result.valid){
$("#card_type").val(cardType);
$("#card_number").removeClass('required');
cardValid = 1;
}else{
$("#card_type").val('');
$("#card_number").addClass('required');
cardValid = 0;
}
});
// Card details validation
var cardName = $("#name_on_card").val();
var expMonth = $("#expiry_month").val();
var expYear = $("#expiry_year").val();
var cvv = $("#cvv").val();
var regName = /^[a-z ,.'-]+$/i;
var regMonth = /^01|02|03|04|05|06|07|08|09|10|11|12$/;
var regYear = /^2017|2018|2019|2020|2021|2022|2023|2024|2025|2026|2027|2028|2029|2030|2031$/;
var regCVV = /^[0-9]{3,3}$/;
if(cardValid == 0){
$("#card_number").addClass('required');
$("#card_number").focus();
return false;
}else if(!regMonth.test(expMonth)){
$("#card_number").removeClass('required');
$("#expiry_month").addClass('required');
$("#expiry_month").focus();
return false;
}else if(!regYear.test(expYear)){
$("#card_number").removeClass('required');
$("#expiry_month").removeClass('required');
$("#expiry_year").addClass('required');
$("#expiry_year").focus();
return false;
}else if(!regCVV.test(cvv)){
$("#card_number").removeClass('required');
$("#expiry_month").removeClass('required');
$("#expiry_year").removeClass('required');
$("#cvv").addClass('required');
$("#cvv").focus();
return false;
}else if(!regName.test(cardName)){
$("#card_number").removeClass('required');
$("#expiry_month").removeClass('required');
$("#expiry_year").removeClass('required');
$("#cvv").removeClass('required');
$("#name_on_card").addClass('required');
$("#name_on_card").focus();
return false;
}else{
$("#card_number").removeClass('required');
$("#expiry_month").removeClass('required');
$("#expiry_year").removeClass('required');
$("#cvv").removeClass('required');
$("#name_on_card").removeClass('required');
$('#cardSubmitBtn').prop('disabled', false);
return true;
}
}
Payment processing with jQuery and Ajax: An Ajax request is sent to PayPal Pro CodeIgniter Library to validate and process the card transaction.
Ajax is used to send the provided card information to the payment() method of the Products controller.
The transaction status is returned after the given charge is created.
The user gets presented order information or an error message based on the response.
/* Submit card details and make payment */
$(document).ready(function(){
// Initiate validation on input fields
$('#paymentForm input[type=text]').on('keyup',function(){
cardFormValidate();
});
// Submit card form
$("#cardSubmitBtn").on('click',function(){
$('.status-msg').remove();
if(cardFormValidate()){
var formData = $('#paymentForm').serialize();
$.ajax({
type:'POST',
url:'<?php echo base_url('products/payment/'.$product['id']); ?>',
dataType: "json",
data:formData,
beforeSend: function(){
$("#cardSubmitBtn").prop('disabled', true);
$("#cardSubmitBtn").val('Processing....');
},
success:function(data){
if(data.status == 1){
$('#paymentSection').html('<p class="status-msg success">The transaction was successful. Order ID: <span>'+data.orderID+'</span></p>');
}else{
$("#cardSubmitBtn").prop('disabled', false);
$("#cardSubmitBtn").val('Proceed');
$('#paymentSection').prepend('<p class="status-msg error">Transaction has been failed, please try again.</p>');
}
}
});
}
});
});
Activate the PayPal Pro Payment Gateway
Make the PayPal Pro payment gateway live for production use once the payment flow testing is completed and the transaction is performing well in the Sandbox environment. To enable the PayPal Pro payment gateway in your CodeIgniter application, do the following adjustments.
In the file application/config/paypal.php, make the following changes:
Set the PayPal sandbox environment to FALSE.
Change the API credentials to match your PayPal Business Pro account (paypal api username, paypal api password, and paypal api signature).