PayPal Payment Gateway Integration in PHP

The is a significant change in the method we use to pay for goods we purchase now. Acceptance of digital payment is becoming more easy, and everyone tries to pay via digital channels. Today, there are several ways to pay, including cash, credit cards, and electronic payment systems like PayPal. Regardless of the payment option we choose, we anticipate a simple and rapid transaction. PayPal is useful in this situation.

PayPal is one of the most dependable online payment systems in the world, much like PHP for web development. Therefore, PayPal immediately comes to mind when thinking about various payment gateway integrations in a PHP-based framework.

Online payments are only possible through Paypal. It is used by millions of companies and company owners for everything from simple online payment acceptance to sophisticated online selling platforms. In more than 200 markets throughout the world, it provides an all-inclusive solution to link businesses and customers. Paypal integration has become a crucial component of any online business for a variety of reasons.

How to add a PayPal payment gateway to your PHP website?

As promised, let’s look at how to incorporate PayPal as a payment gateway in PHP right away. You need a merchant account connected to a PayPal business account in order to integrate PayPal into your PHP website. By following a few simple steps, you may link your PayPal account with your PHP website.

Let’s look at the features you want for a payment gateway on your website before we get started.

  1. Obtain credit card details.
  2. transfer credit card data safely.
  3. To handle incoming and outgoing requests to/from PayPal, use the Payment.php page.
  4. Process the charges after checking the card.
  5. Publish payment information to the database.

Integrating PayPal Payment Gateway in PHP Website: Step by Step Process

Step 1: Create a PayPal Account.

Registration for a PayPal account is the initial step. Visit PayPal and select SignUp. Further to access IPN, you must create a business account. You would have access to IPN after correctly configuring the PayPal account.

Look for the following options in your PayPal account’s “edit profile” section. Locate the “Getting Paid and Managing Risk” under “My Selling Preferences.”

  • The Instant Payment Notification Process should be opened
  • Activate the IPN Value
  • The IPN URL should be changed to point to the PHP page with the IPN code (http://www.example.com/payment.php).

Locate the “Getting Paid and Managing Risk” under “My Selling Preferences.”

  • Go to the Block Payments page.
  • Block the eCheque users’ payments to stop them from making them

Find “email” under “account details” by navigating there.

  • Type in your main email address. Users will be able to see this email, so act professionally.

Step 2: Add CSS to the header of your HTML form page.

<style>
body {
    font-family: Arial;
    line-height: 30px;
    color: #333;
}

#payment-box {
    padding: 40px;
    margin: 20px;
    border: #E4E4E4 1px solid;
    display: inline-block;
    text-align: center;
    border-radius: 3px;
}

#pay_now {
    padding: 10px 30px;
    background: #09f;
    border: #038fec 1px solid;
    border-radius: 3px;
    color: #FFF;
    width: 100%;
    cursor: pointer;
}

.txt-title {
    margin: 25px 0px 0px 0px;
    color: #4e4e4e;
}

.txt-price {
    margin-bottom: 20px;
    color: #08926c;
    font-size: 1.1em;
}
</style>

Step 3: Show your products in HTML format

Use Below Code To Create a Product Format

<div id="payment-box">
<img src="images/pizza.jpg" />
<h4 class="txt-title">Veggie Pizza</h4>
<div class="txt-price">$ 25.00</div>
</div>

Step 4: Develop an HTML Form With All Details

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
    <input type='hidden' name='business' value='PayPal Business Email'> 
    <input type='hidden' name='item_name' value='Veggie Pizza'> 
    <input type='hidden' name='item_number' value='PIZ#48'> 
    <input type='hidden' name='amount' value='25'> 
    <input type='hidden' name='no_shipping' value='1'> 
    <input type='hidden' name='currency_code' value='USD'> 
    <input type='hidden' name='notify_url' value='http://www.yourdomain.com/paypal-payment-gateway-integration-in-php/notify.php'>
    <input type='hidden' name='cancel_return' value='http://www.yourdomain.com/paypal-payment-gateway-integration-in-php/cancel.php'>
    <input type='hidden' name='return' value='http://www.yourdomain.com/paypal-payment-gateway-integration-in-php/return.php'>
    <input type="hidden" name="cmd" value="_xclick"> 
    <input type="submit" name="pay_now" id="pay_now" Value="Pay Now">
</form>

You must install a form on your website so that PayPal may receive the payee’s basic information. The following stage will include sending more private information, such as the price or name of a company.

Step 5: Submitting a Request.

The outbound request to PayPal and the incoming response following the processing of the payment will both be handled by the return.php page, as I previously explained.

Nevertheless, before delivering the parameters, you must build them up and feed them to PayPal using query strings.

  • Values that must be transmitted:
  • business: PayPal account email address
  • Item name: the item’s name
  • Amount: The merchandise’s cost
  • Return: return address following successful payment
  • If a transaction is canceled, the return address will be shown.
  • Notify url: your website’s payment.php page URL
  • Custom: Any other information you would like to provide to PayPal

Step 6: Incoming Response

The return.php page we created will now read the answer that PayPal sends and display it.

This code must be included to the otherwise clause of the return.php script. Before adding the money to the database, it will check to see if this transaction has previously been handled.

The response’s verifiability will be checked by the verifyTransaction function. After being called, the function takes the information from PayPal and verifies it by sending a curl request to PayPal with the transaction information.

We will receive the VERIFIED message as well as know every detail is in order if the answer is the same. A database entry will then be made for the payment.

Additionally, we may call checkTxnid. The code simply determines if our database already contains the PayPal txn id value.

It is a good practice to run this procedure after you have confirmed the payment to see whether you have already entered the transaction to the database.

You can include as many checks as you’d like here. This is the chance to check the different components of the payment.

Step 7: PHP code to check all responses of PayPal and add all transaction details in database

<?php
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 1);
define("LOG_FILE", "ipn.log");
// Read POST data
// reading posted data directly from $_POST causes serialization
// issues with array data in POST. Reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
	$keyval = explode ('=', $keyval);
	if (count($keyval) == 2)
		$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
	$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
	if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
		$value = urlencode(stripslashes($value));
	} else {
		$value = urlencode($value);
	}
	$req .= "&$key=$value";
}
// Post IPN data back to PayPal to validate the IPN data is genuine
// Without this step anyone can fake IPN data
if(USE_SANDBOX == true) {
	$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
	$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
	return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
	{
	if(DEBUG == true) {	
		error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
	}
	curl_close($ch);
	exit;
} else {
		// Log the entire HTTP response if debug is switched on.
		if(DEBUG == true) {
			error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
			error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
		}
		curl_close($ch);
}
// Inspect IPN validation result and act accordingly
// Split response headers and payload, a better way for strcmp
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp ($res, "VERIFIED") == 0) {
	// assign posted variables to local variables
	$item_name = $_POST['item_name'];
	$item_number = $_POST['item_number'];
	$payment_status = $_POST['payment_status'];
	$payment_amount = $_POST['mc_gross'];
	$payment_currency = $_POST['mc_currency'];
	$txn_id = $_POST['txn_id'];
	$receiver_email = $_POST['receiver_email'];
	$payer_email = $_POST['payer_email'];
	
	include("DBController.php");
	$db = new DBController();
	
	// check whether the payment_status is Completed
	$isPaymentCompleted = false;
	if($payment_status == "Completed") {
		$isPaymentCompleted = true;
	}
	// check that txn_id has not been previously processed
	$isUniqueTxnId = false; 
	$param_type="s";
	$param_value_array = array($txn_id);
	$result = $db->runQuery("SELECT * FROM payment WHERE txn_id = ?",$param_type,$param_value_array);
	if(empty($result)) {
        $isUniqueTxnId = true;
	}	
	// check that receiver_email is your PayPal email
	// check that payment_amount/payment_currency are correct
	if($isPaymentCompleted) {
	    $param_type = "sssdss";
	    $param_value_array = array($item_number, $item_name, $payment_status, $payment_amount, $payment_currency, $txn_id);
	    $payment_id = $db->insert("INSERT INTO payment(item_number, item_name, payment_status, payment_amount, payment_currency, txn_id) VALUES(?, ?, ?, ?, ?, ?)", $param_type, $param_value_array);
	    error_log(date('[Y-m-d H:i e] '). "Vdddddddddddderified IPN: $req ". PHP_EOL, 3, LOG_FILE);
	} 
	// process payment and mark item as paid.
	
	
	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
	}
	
} else if (strcmp ($res, "INVALID") == 0) {
	// log for manual investigation
	// Add business logic here which deals with invalid IPN messages
	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
	}
}
?>

Adding the payment to the database is the last step after validating the payment and performing the further checks.

To store the payment information in the database system, we will develop a payment table.

The function must then be configured to call addPayment.

Step 8: Testing

Finally, we’ll make sure the integration was carried out successfully and is operating as it should. Similar to PayPal and offering all of its features is PayPal Sandbox. Sandbox, however, allows you to employ fictitious attributes in place of actual ones.

You may make fictitious accounts for vendors and buyers. Establish the test site and run the PayPal integration stage-by-stage. So is free to create Sandbox accounts, and you may do it through the PayPal Developer website. 

The code that is offered in the article is tailored for the Sandbox. The request contains the URL www.sandbox.paypal.com. The value of $enableSandbox must be changed from true to false. The PayPal URLs in the code will be updated as a result.

Conclusion

Integration of payment gateways into PHP websites is more difficult to achieve than it sounds, especially if you are not a developer. On your website, the payment gateway must function properly. As a result, you ought to work with skilled PHP developers.

We suggest getting in touch with us if you need to hire developers. We have a fully functional staff of PHP developers with experience integrating PayPal and other payment gateways. Therefore, we guarantee that your PHP-based website will seamlessly integrate a payment gateway.