Monday, April 7, 2014

Step by step implementation of PayPal Pay-Flow-Pro Advance


Implementation of paypal pay-flow-pro payment gateway is very easy in php. First of all you will have to be need two thing to implement payflow pro advance -

1-Pay-flow pro advance sdk
2-A testing account on paypal manager (https://manager.paypal.com/)

1- Pay-flow pro advance sdk -  To implement pay-flow-pro .You need two file. PayflowNVPAPI.php and index.php . You just need to create a folder with name "PayFlowTest" and save both of file PayflowNVPAPI.php and index.php togeather into the "PayFlowTest" folder .After that locate your folder in you local host directory or on your server.You can simply test it by entering test credit card number 4111111111111111 and expiry date .Expiry date much be greter than current date.

Note:  After testing successfully don't forgot to change my test account paypal credential with your own.






Now get set and go to implement payflow pro. Just copy the entire below code and  paste in your PayflowNVPAPI.php file.After that you need to create another file index.php


PayflowNVPAPI.php


<?php
//// Helper functions
if (!function_exists('pre')) {
function pre($arr, $heading = NULL) {  
if (!empty($heading)) {    
echo "<p><b>$heading</b></p>";  
}  
echo "<pre><code>\n" . print_r($arr,true) . "\n</pre></code>";
}
}
if (!function_exists('script_url')) {
function script_url() {
 return (@$_SERVER['HTTPS'] ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
}
// Set this to "live" for the live server, "pilot" for the test server, or "sandbox"
// for Payflow accounts created through a Website Payments Pro account on the Sandbox. global $environment;
if (!isset($environment)) $environment = 'pilot';
// parse_payflow_string: Parses a response string from Payflow and returns an
// associative array of response parameters.
function parse_payflow_string($str) {    
$workstr = $str;    
$out = array();         
while(strlen($workstr) > 0) {        
$loc = strpos($workstr, '=');        
if($loc === FALSE) {            
// Truncate the rest of the string, it's not valid            
$workstr = "";            
continue;        
}                 
$substr = substr($workstr, 0, $loc);        
$workstr = substr($workstr, $loc + 1);
// "+1" because we need to get rid of the "="                 
if(preg_match('/^(\w+)\[(\d+)]$/', $substr, $matches)) {            
// This one has a length tag with it.  Read the number of characters            
// specified by $matches[2].            
$count = intval($matches[2]);                         
$out[$matches[1]] = substr($workstr, 0, $count);            
$workstr = substr($workstr, $count + 1);
// "+1" because we need to get rid of the "&"        
} else {            
// Read up to the next "&"            
$count = strpos($workstr, '&');            
if($count === FALSE) {
// No more "&"'s, read up to the end of the string                
$out[$substr] = $workstr;                
$workstr = "";            
} else {
$out[$substr] = substr($workstr, 0, $count);                
$workstr = substr($workstr, $count + 1);
// "+1" because we need to get rid of the "&"            
}        
}    
}         
return $out;
}
// run_payflow_call: Runs a Payflow API call.$params is an associative array of
// Payflow API parameters.  Returns FALSE on failure, or an associative array of response
// parameters on success.
function run_payflow_call($params) {    
global $environment;         
$paramList = array();   
foreach($params as $index => $value) {        
$paramList[] = $index . "[" . strlen($value) . "]=" . $value;    
}        
$apiStr = implode("&", $paramList);         
// Which endpoint will we be using?    
if($environment == "pilot" || $environment == "sandbox")     
$endpoint = "https://pilot-payflowpro.paypal.com/";   
else $endpoint = "https://payflowpro.paypal.com";     
// Initialize our cURL handle.    
$curl = curl_init($endpoint);         
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);         
// If you get connection errors, it may be necessary to uncomment    
// the following two lines:    
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);   
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);         
curl_setopt($curl, CURLOPT_POST, TRUE);    
curl_setopt($curl, CURLOPT_POSTFIELDS, $apiStr);         
$result = curl_exec($curl);    
if($result === FALSE) {      
echo curl_error($curl);      
return FALSE;    
}    
else
return parse_payflow_string($result);
}
?>


Now create an index.php file and just copy the entire below code and paste it into your index.php file .

Note : Dont forget to change you test account credential after successfully testing payflow pro.

Index.php 

<?php
session_start();
include("PayflowNVPAPI.php");
global $environment;
$environment = "sandbox";
//Change it live if you are going for live transaction  require_once('PayflowNVPAPI.php');
//////// //// ////  First, handle any return/responses ////
/*Check if we just returned inside the iframe.  If so, store payflow response and redirect parent window with javascript.Purpose for adding this script is to get responce where ever you want on your php file otherwise paypal return response in iframe*/
if (isset($_POST['RESULT']) || isset($_GET['RESULT']) ) {   $_SESSION['payflowresponse'] = array_merge($_GET, $_POST);   echo '<script type="text/javascript">window.top.location.href = "' . script_url() .  '";</script>';   exit(0); }  echo "<span style='font-family:sans-serif;font-size:160%;font-weight:bold;'>PayPal Payments Advanced - Demo On phpsollutions.blogspot.com</span> <p style='margin-left:1em;font-family:monospace;'>
Hosted checkout page (Layout C) embedded in your site as an iframe</p>
<hr/>";
//Check whether we stored a server response.If so, print it out.
if(!empty($_SESSION['payflowresponse'])) {
$response= $_SESSION['payflowresponse'];
unset($_SESSION['payflowresponse']);
$success = ($response['RESULT'] == 0);
/*Now Here you can print all responce returning from paypal sucess or error   respectivelly */ 
if($success) echo "<span style='font-family:sans-serif;font-weight:bold;'>Transaction approved! Thank you for your order.</span>";
else echo "<span style='font-family:sans-serif;'>Transaction failed! Please try again with another payment method.</span>";
echo "<pre>(server response follows)\n";
print_r($response);
echo "</pre>
";
exit(0);
}
// Otherwise, begin hosted checkout pages flow 
//Build the Secure Token request
$request = array("PARTNER" => "PayPal", //change it paypal manager account setting 
"VENDOR" => "nitinpayflowtest", //change it paypal manager account setting 
"USER" => "nitinpayflowtest", //change it paypal manager account setting 
"PWD" => "nitin123!",  //change it paypal manager account setting 
"TRXTYPE" => "S", //'S'=>Sale,'A'=>Authorize,'D'=>Delay Captured, 
"AMT" => "149",   "CURRENCY" => "USD",   "CREATESECURETOKEN" => "Y", //Set Y=>'Yes' to create secure token 
"SECURETOKENID" => uniqid('MySecTokenID-'), //Should be unique, never used before 
"RETURNURL" => script_url(), 
"CANCELURL" => script_url(), 
"ERRORURL" => script_url(),  // In practice you'd collect billing and shipping information with your own form, // then request a secure token and display the payment iframe. // --> See page 7 of https://cms.paypal.com/cms_content/US/en_US/files/developer/Embedded_Checkout_Design_Guide.pdf // This example uses hardcoded values for simplicity.  
"BILLTOFIRSTNAME" => "salman", 
"BILLTOLASTNAME" => "ahmad", 
"BILLTOSTREET" => "123 Main St.", 
"BILLTOCITY" => "San Jose", 
"BILLTOSTATE" => "CA", 
"BILLTOZIP" => "95101", 
"BILLTOCOUNTRY" => "US",  
"SHIPTOFIRSTNAME" => "Jane", 
"SHIPTOLASTNAME" => "Smith", 
"SHIPTOSTREET" => "1234 Park Ave", 
"SHIPTOCITY" => "San Jose", 
"SHIPTOSTATE" => "CA", 
"SHIPTOZIP" => "95101", 
"SHIPTOCOUNTRY" => "US", );
//Run request and get the secure token response
$response = run_payflow_call($request);
if ($response['RESULT'] != 0) {
pre($response, "Payflow call failed");
exit(0);
}else {
$securetoken = $response['SECURETOKEN'];
$securetokenid = $response['SECURETOKENID'];
}
if($environment == "sandbox" || $environment == "pilot")
$mode='TEST';
else
$mode='LIVE';
echo '<div style="border: 1px dashed; margin-left:40px; width:492px; height:567px;">
';
// wrap iframe in a dashed wireframe for demo purposes
echo "<iframe src='https://payflowlink.paypal.com?SECURETOKEN=$securetoken&SECURETOKENID=$securetokenid&MODE=$mode' width='490' height='565' border='0' frameborder='0' scrolling='no' allowtransparency='true'>\n</iframe>";
echo "</div><p style='margin-left:40px;font-family:monospace;'>(end of hosted iframe, marked with dashed line)</p>
";
?>


2-Testing account on paypal manager (https://manager.paypal.com/):

To create a testing account please click on this link create test account .







If you having problem during implementation of paypal payflow-pro advance then you can directly contact me threw comments .


Please don't leave with out posting comment 

Chears:)

Happy coding Guys




9 comments:

Anonymous said...

Hello Salman,
This really helps me a lot, can you please tell me about the credentials, is this gonna work if i use this by adding sandbox credentials and also please let me know about creating a test account in paypal manager. i've tried but didn't work.

Thanks in advance

Anonymous said...

I,ve read the user guide for payflow and it is mentioned their for recurring transactions to make TRXTYPE = R
but it's not working. Is above code also work for Recurring payments too?
Please share code for that too.

Quick Reply would be appreciated.
Thanks in advance.

Anonymous said...

Thanks for your useful post, Is this available in Australia?

Salman Ahmad said...

Yes @mate Paypal payflow pro is available only for the UK & Australian customers.

Vamshi Krishna P said...

Hey bro,It helps me out but I'm getting an error which says "User Authentication failed".
USER_DEBUG [8]|DEBUG|RESULT=1&RESPMSG=User authentication failed.

Can you suggest me please where I'm going wrong.

Admin said...

Hi @Vimshi Krishan P - Thanks for your comment. Its looking you are missing something in configuration of payflow pro. Please checkout this link and let us know ... User-authentication-failed-Reason

Vamshi Krishna P said...

I checked them out.I'm doing it from Salesforce.
I have IP addresses included on the Pay flow white list. Besides this, I have "!!" special characters in password. If I consider this issue,there are other developers who went ahead and successful with the integration. This is confusing but still finding ways to solve this.

https://www.paypal.com/us/selfhelp/article/why-did-i-get-the-error-user-authentication-failed-or-merchant-identification-error-ts1223/1?channel=MTS

Vamshi Krishna said...

Hello Admin,
Could you please suggest me? If you are okay,I can send you an email with perfect documentation. Thank you

Admin said...

@Vamshi - Thanks for your comment. Yes sure please send me detail documentation on phpsollution@gmail.com . If its really good then we will definitely post on our website.

Thanks.

Related Posts Plugin for WordPress, Blogger...