paypal payment gateway integration in php source code download

Today I am going to step by step integrate paypal payment gateway with core PHP with Mysql Database. Payment gateway are third party options that handle all the payment transaction between customer(Payer) and merchants .They have many more available parameter like as customer name, Payer email Address ,material name, material model no, material total cost, Payer country code ore more learn to step by step paypal payment gateway integration in php source code download.

PHP - Paypal Payment Gateway Integration
PHP – Paypal Payment Gateway Integration

I will integrate in our previous tutorial of core PHP shopping cart project .So if you have not setup it ,do visit this tutorial and follow all steps or if you have your own project ,it’s paypal payment gateway integration in php source code download.

Step 1 : Create a e-commerce project Shop Product Page

I have our main landing page in e-commerce php project like as a Therefor , first of all you cna open this file in your any PHP editor like as a sublime, notepad++ and update the following full code to the bottom of the web page.

	 
" />

Also Read: PayPal Payment Gateway with PHP MySQL Database

Check below how our complete thank_you_page.php page looks like


    
    
My Account
Name
Email
Contact
Address


query("SELECT * FROM materials p INNER JOIN cart c ON c.pid=p.pid WHERE c.mid='$mid' "); $n=1; $total=0; $model=''; $material_name=''; while($row=$r->fetch_assoc()){ $model.=" ".$row['model']; $material_name.=" ".$row['title']; ?>
Image Title Qty Sub Total
Net Total :
" />

Also Read: How to Integration PayPal Payment Gateway in PHP?

Step 2 : Added switch Case

in above full paypal payment gateway integration in php source code download i have a form action like as a main file name paypal.php. Find following this php file

admin_mail 	= EMAIL_ADD; 
$action 		= $_REQUEST["action"];

switch($action){
	case "process": 
		$mysqli->query("INSERT INTO gandhi_shops (invoice, material_id, material_name, material_quantity, material_amount, donor_fname, donor_address,donor_email, payment_status, posted_date) VALUES ('".$_POST["invoice"]."', '".$_POST["material_id"]."', '".$_POST["material_name"]."', '".$_POST["material_quantity"]."', '".$_POST["material_amount"]."', '".$_POST["donor_fname"]."','".$_POST["donor_address"]."','".$_POST["donor_email"]."', 'pending', NOW())");
		
		$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
		
		$p->add_field('business', PAYPAL_EMAIL_ADD); 
		$p->add_field('cmd', $_POST["cmd"]); 
		$p->add_field('upload', '1');
		$p->add_field('return', $this_script.'?action=success'); 
		$p->add_field('cancel_return', $this_script.'?action=cancel'); 
		$p->add_field('notify_url', $this_script.'?action=ipn'); 
		$p->add_field('currency_code', $_POST["currency_code"]);
		$p->add_field('invoice', $_POST["invoice"]);
		$p->add_field('item_name_1', $_POST["material_name"]);
		$p->add_field('item_number_1', $_POST["material_id"]);
		$p->add_field('quantity_1', $_POST["material_quantity"]);
		$p->add_field('amount_1', $_POST["material_amount"]);
		$p->add_field('first_name', $_POST["donor_fname"]);
 		$p->add_field('address1', $_POST["donor_address"]);
 		$p->add_field('email', $_POST["donor_email"]);
		$p->submit_paypal_post(); 
		//$p->dump_fields(); 
	break;
	
	case "success": 
		echo 'Payment Done Successfully';
		echo '
';		echo '
'; echo "

Payment Transaction Done Successfully

"; echo '

Click here to go My Account page

'; echo '
'; break; case "cancel": echo "

Transaction Cancelled "; break; case "ipn": $trasaction_id = $_POST["txn_id"]; $payment_status = strtolower($_POST["payment_status"]); $invoice = $_POST["invoice"]; $log_array = print_r($_POST, TRUE); $log_query = "SELECT * FROM paypal_log WHERE txn_id = '$trasaction_id'"; $log_check = $mysqli->query($log_query); if( $log_check->num_rows <= 0){ $mysqli->query("INSERT INTO paypal_log (txn_id, log, posted_date) VALUES ('$trasaction_id', '$log_array', NOW())"); }else{ $mysqli->query("UPDATE paypal_log SET log = '$log_array' WHERE txn_id = '$trasaction_id'"); } // Save and update the logs array $paypal_log_fetch = mysql_fetch_array($mysqli->query($log_query)); $paypal_log_fetch = $mysqli->query($log_query)->fetch_assoc(); ; $paypal_log_id = $paypal_log_fetch["id"]; if ($p->validate_ipn()){ $mysqli->query("UPDATE gandhi_shops SET trasaction_id = '$trasaction_id ', log_id = '$paypal_log_id', payment_status = '$payment_status' WHERE invoice = '$invoice'"); $subject = 'Instant Payment Notification - Recieved Payment'; $p->send_report($subject); }else{ $subject = 'Instant Payment Notification - Payment Fail'; $p->send_report($subject); } break; } ?>

In above php file 1st line it’s calling database config file, then on main included two php lines we have declared paypal merchant’e email address and notification email address. The first of all email address should be registered or signup with paypal as a main merchant account to accept here payment from online website .

here, i am in testing mode ( like as a sandbox account) ,Therefor we can put anything here .

After it handle Paypal payment process page .While on this phase it insert or added the form all the data in database mysql table ‘gandhi_shops’ and full process to the paypal live mode .

Also Read: PayPal Payment Gateway PHP Source Code

PayPal Standard Payment Gateway Integration in Vuejs
PayPal Standard Payment Gateway Integration in Vuejs

Step 3 : Crteate a Database Structure

in step number Three I am regarding a database Mysql table like name as a ‘gandhi_shops’ .Therefor , let’s make it , execute following the source code to sql on your phpmyadmin for your mysql database .

CREATE TABLE `gandhi_shops` (
  `id` int(10) NOT NULL auto_increment,
  `invoice` varchar(300) NOT NULL,
  `trasaction_id` varchar(600) NOT NULL,
  `log_id` int(10) NOT NULL,
  `material_id` varchar(300) NOT NULL,
  `material_name` varchar(300) NOT NULL,
  `material_quantity` varchar(300) NOT NULL,
  `material_amount` varchar(300) NOT NULL,
  `donor_fname` varchar(300) NOT NULL,
  `donor_lname` varchar(300) NOT NULL,
  `donor_address` varchar(300) NOT NULL,
  `donor_city` varchar(300) NOT NULL,
  `donor_state` varchar(300) NOT NULL,
  `donor_zip` varchar(300) NOT NULL,
  `donor_country` varchar(300) NOT NULL,
  `donor_email` text NOT NULL,
  `payment_status` varchar(300) NOT NULL,
  `posted_date` datetime NOT NULL,
  PRIMARY KEY  (`id`)
) 

Also Read: laravel paypal integration Tutorial from Scratch for Beginners

Step 4: Set Paypal IPN

here step Number four to create a file name as a PaypalController.php’ after that update below source code in it .Thisphp file provides clean as well as simple php method or way to validate the paid output with Paypal IPN

Also Read: paypal payment gateway integration in php

ipn_status = '';
		$this->admin_mail = null;
		$this->paypal_mail = null;
		$this->txn_id = null;
		$this->tax = null;
		$this->ipn_log = true;
		$this->ipn_response = '';
		$this->ipn_debug = false;
	}

	public function add_field($field, $value) {
		$this->fields["$field"] = $value;
	}



	public function submit_paypal_post() {

		$paypal_url = ($_GET['sandbox'] == 1) ? SSL_SAND_URL : SSL_P_URL;
		echo "\n";
		echo "Processing Payment...\n";
		echo "\n";
		echo "

Please wait, your order is being processed and you"; echo " will be redirected to the paypal website.

\n"; echo "
\n"; if (isset($this->paypal_mail))echo "paypal_mail\"/>\n"; foreach ($this->fields as $name => $value) { echo "\n"; } echo "

If you are not automatically redirected to "; echo "paypal within 5 seconds...

\n"; echo "\n"; echo "
\n"; echo "\n"; } public function validate_ipn() { $hostname = gethostbyaddr ( $_SERVER ['REMOTE_ADDR'] ); if (! preg_match ( '/paypal\.com$/', $hostname )) { $this->ipn_status = 'Validation post isn\'t from PayPal'; $this->log_ipn_results ( false ); return false; } if (isset($this->paypal_mail) && strtolower ( $_POST['receiver_email'] ) != strtolower(trim( $this->paypal_mail ))) { $this->ipn_status = "Receiver Email Not Match"; $this->log_ipn_results ( false ); return false; } if (isset($this->txn_id)&& in_array($_POST['txn_id'],$this->txn_id)) { $this->ipn_status = "txn_id have a duplicate"; $this->log_ipn_results ( false ); return false; } $paypal_url = ($_POST['test_ipn'] == 1) ? SSL_SAND_URL : SSL_P_URL; $url_parsed = parse_url($paypal_url); $post_string = ''; foreach ($_POST as $field=>$value) { $this->ipn_data["$field"] = $value; $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; } $post_string.="cmd=_notify-validate"; // append ipn command if (isset($_POST['test_ipn']) ) $fp = fsockopen ( 'ssl://www.sandbox.paypal.com', "443", $err_num, $err_str, 60 ); else $fp = fsockopen ( 'ssl://www.paypal.com', "443", $err_num, $err_str, 60 ); if(!$fp) { $this->ipn_status = "fsockopen error no. $err_num: $err_str"; $this->log_ipn_results(false); return false; } else { // Post the data back to paypal fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); fputs($fp, "Host: $url_parsed[host]\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $post_string . "\r\n\r\n"); while(!feof($fp)) { $this->ipn_response .= fgets($fp, 1024); } fclose($fp); } if (! eregi("VERIFIED",$this->ipn_response)) { $this->ipn_status = 'IPN Validation Failed'; $this->log_ipn_results(false); return false; } else { $this->ipn_status = "IPN VERIFIED"; $this->log_ipn_results(true); return true; } } private function log_ipn_results($success) { $hostname = gethostbyaddr ( $_SERVER ['REMOTE_ADDR'] ); $text = '[' . date ( 'm/d/Y g:i A' ) . '] - '; if ($success) $this->ipn_status = $text . 'SUCCESS:' . $this->ipn_status . "!\n"; else $this->ipn_status = $text . 'FAIL: ' . $this->ipn_status . "!\n"; $this->ipn_status .= "[From:" . $hostname . "|" . $_SERVER ['REMOTE_ADDR'] . "]IPN POST Vars Received By Paypal_IPN Response API:\n"; foreach ( $this->ipn_data as $key => $value ) { $this->ipn_status .= "$key=$value \n"; } $this->ipn_status .= "IPN Response from Paypal Server:\n" . $this->ipn_response; $this->write_to_log (); } private function write_to_log() { if (! $this->ipn_log) return; $fp = fopen ( LOG_FILE , 'a' ); fwrite ( $fp, $this->ipn_status . "\n\n" ); fclose ( $fp ); // close file chmod ( LOG_FILE , 0600 ); } public function send_report($subject) { $body .= "from " . $this->ipn_data ['donor_email'] . " on " . date ( 'm/d/Y' ); $body .= " at " . date ( 'g:i A' ) . "\n\nDetails:\n" . $this->ipn_status; mail ( $this->admin_mail, $subject, $body ); } public function print_report(){ $find [] = "\n"; $replace [] = '
'; $html_content = str_replace ( $find, $replace, $this->ipn_status ); echo $html_content; } public function dump_fields() { echo "

PaypalController->dump_fields() Output:

"; echo ""; ksort($this->fields); foreach ($this->fields as $key => $value) {echo "";} echo "
Field Name Value
$key".urldecode($value)." 

"; } private function debug($msg) { if (! $this->ipn_debug) return; $today = date ( "Y-m-d H:i:s " ); $myFile = ".ipn_debugs.log"; $fh = fopen ( $myFile, 'a' ) or die ( "Can't open mode of the debug file. Please manually make the 'debug.log' file and make it writable." ); $ua_simple = preg_replace ( "/(.*)\s\(.*/", "\\1", $_SERVER ['HTTP_USER_AGENT'] ); fwrite ( $fh, $today . " [from: " . $_SERVER ['REMOTE_ADDR'] . "|$ua_simple] - " . $msg . "\n" ); fclose ( $fh ); chmod ( $myFile, 0600 ); } }

and last step paypal payment gateway integration in php source code download to open thank_you_page.php on your any default browser Like as a Example URL: http://localhost/my_php/thank_you_page.php. and then imple Click button this text to ‘Pay now using Paypal’. after that It redirect to next page. and here Check or verify there if all form field required argyments data value are passing correctly. and then about 5 sec to it redirect to main offical website like as a paypal.com.you can also here Do check if all information like as a material name ,model as well as complete total cost are correct . well, best step by step learn to paypal sandbox ,means paypal provide for developer for test means sandbox integration on this mode.

Also Read: Laravel 5.4 Paypal integration – Paypal Payment Gateway

and you can successful integration, then Delete query string like as a ‘?sandbox=1’ from HTML form action on thank_you_page.php file and update working merchant email address in main paypal.php file .

Leave a Comment