Advertisement
PHP

How to Process Credit Cards with PayPal Payments Pro Using PHP

by

PayPal is one of the most popular payment processing platforms available today for many reasons. Its ease of use and its connection to the eBay platform are just the tip of the iceberg. While one of its most popular features is the ability to simply sign in to your PayPal account to submit payments, merchants using PayPal can also accept credit cards directly just like a traditional merchant account solution would provide. 

PayPal calls this solution Payments Pro, and I’m going to show you exactly how you can process credit cards directly with PayPal’s API using their Payments Pro web service API’s.


Step 1: Setup the Directory Structure

The first thing I like to do with any project is to create a basic structure organized for the project.  In this case, our structure is very simple as our project will consist of only 2 files:

Directory Structure

 As you might have guessed, we’ll be storing our configuration information in config.php, and we’ll actually handle the processing code in process-credit-card.php.


Step 2: Setup the Config File

Our /includes/config.php file will house our values for the PayPal API information we need including the end-point URL, API version, and our API username, password, and signature that we’ll be using. 

// Set sandbox (test mode) to true/false.
$sandbox = TRUE;

// Set PayPal API version and credentials.
$api_version = '85.0';
$api_endpoint = $sandbox ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp';
$api_username = $sandbox ? 'SANDBOX_USERNAME_GOES_HERE' : 'LIVE_USERNAME_GOES_HERE';
$api_password = $sandbox ? 'SANDBOX_PASSWORD_GOES_HERE' : 'LIVE_PASSWORD_GOES_HERE';
$api_signature = $sandbox ? 'SANDBOX_SIGNATURE_GOES_HERE' : 'LIVE_SIGNATURE_GOES_HERE';

Reviewing the config.php code, you can see that first we set a variable for $sandbox.  For now, we’ll leave this to TRUE because we want to interact with PayPal’s sandbox (test) servers for development purposes.  You’ll need to remember to change this to FALSE when you’re ready to move your project to a live server.

Then, based on the value of $sandbox we’re setting values to other variables for our API information.  You’ll just want to fill in those placeholders with your own details accordingly.  Now we’re ready to build our credit card processing script.


Step 3: Create an API Request

Now we can begin to build our process-credit-card.php page.  The first thing we need to do here is include our config file.

// Include config file
require_once('includes/config.php');

Next, we need to build a name-value-pair string that includes all of the data we need to send PayPal in order to process this payment.  A name-value-pair string looks just like something you might see when passing data via URL parameters.  We just need to make sure our parameter names are in all caps.

PARAM1=value1&PARAM2=value2&PARAM3=value3…etc.

So, you might be thinking to yourself “How do I know what to use for my variable names in my string?”  The good news is PayPal provides very good documentation on this.  We can see all of the possible variables that we can pass PayPal including customer details, order item details, and credit card information.  Some of this information is required in order to process a payment, but many of the variables available are optional.  For demonstration purposes, we’ll keep this pretty simple and just pass the required information.

We’ll store all of our request parameters in an array so that we can loop through this array to easily generate our NVP string.  All requests require the following parameters by default:

  • METHOD – The name of the API call you’re making.
  • USER – The API username
  • PWD – The API password
  • SIGNATURE – The API signature
  • VERSION – The API version

Then you can refer to the PayPal documentation for any API request you’d like to make to see what other parameters should be included.  For the sake of this demonstration, our array will be built as follows.

// Store request params in an array
$request_params = array
					(
					'METHOD' => 'DoDirectPayment', 
					'USER' => $api_username, 
					'PWD' => $api_password, 
					'SIGNATURE' => $api_signature, 
					'VERSION' => $api_version, 
					'PAYMENTACTION' => 'Sale', 					
					'IPADDRESS' => $_SERVER['REMOTE_ADDR'],
					'CREDITCARDTYPE' => 'MasterCard', 
					'ACCT' => '5522340006063638', 						
					'EXPDATE' => '022013', 			
					'CVV2' => '456', 
					'FIRSTNAME' => 'Tester', 
					'LASTNAME' => 'Testerson', 
					'STREET' => '707 W. Bay Drive', 
					'CITY' => 'Largo', 
					'STATE' => 'FL', 					
					'COUNTRYCODE' => 'US', 
					'ZIP' => '33770', 
					'AMT' => '100.00', 
					'CURRENCYCODE' => 'USD', 
					'DESC' => 'Testing Payments Pro' 
					);

You’ll notice we’re using our config variables from config.php, and then I’m simply loading static data for the other values.  In a standard project, though, you’ll most likely be populating these values with form data, session data, or some other form of dynamic data.

Now we can simply loop through this array to generate our NVP string.

// Loop through $request_params array to generate the NVP string.
$nvp_string = '';
foreach($request_params as $var=>$val)
{
	$nvp_string .= '&'.$var.'='.urlencode($val);	
}

The value of $nvp_string is now:

METHOD=DoDirectPayment&USER=sandbo*****e.com&PWD=12***74&SIGNATURE=AiKZ******6W18v&VERSION=85.0&PAYMENTACTION=Sale&IPADDRESS=72.135.111.9&CREDITCARDTYPE=MasterCard&ACCT=5522340006063638&EXPDATE=022013&CVV2=456&FIRSTNAME=Tester&LASTNAME=Testerson&STREET=707+W.+Bay+Drive&CITY=Largo&STATE=FL&COUNTRYCODE=US&ZIP=33770&AMT=100.00&CURRENCYCODE=USD&DESC=Testing+Payments+Pro

This string is what we'll send to PayPal for our request.


Step 4: Send the HTTP Request to PayPal

Now that our NVP string is ready to go we need to send this to the PayPal server to be processed accordingly.  To do this, we’ll use PHP’s CURL methods.

// Send NVP string to PayPal and store response
$curl = curl_init();
		curl_setopt($curl, CURLOPT_VERBOSE, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_URL, $api_endpoint);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $nvp_string);

$result = curl_exec($curl);		
curl_close($curl);

Here you can see that we’ve setup CURL with a few simple options and we’re using our $api_endpoint and $nvp_string variables accordingly.

This data will be sent over to PayPal and we will receive the API response back in our $result variable so that we can see the result and send the user to a successful or failure page based on whether or not the call succeeded or not.


Step 5: Parse the API Response

The value that we get back in $result from the previous step will be an NVP string just like the one we generated and sent to PayPal.  When we run our current script we get a successful response back that looks like this:

TIMESTAMP=2012%2d04%2d16T07%3a59%3a36Z&CORRELATIONID=9eb40cd84a7d3&ACK=Success&VERSION=85%2e0&BUILD=2764190&AMT=100%2e00&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=160896645A8111040

One very simple way to parse this result is to use PHP’s parse_str() function.  This will load all of the response data into PHP variables matching the names and values returned in the response.  For example, if we do the following:

  // Parse the API response
  $nvp_response_array = parse_str($result);

We would end up with access to the following PHP variables:

  • $TIMESTAMP
  • $CORRELATIONID
  • $ACK
  • $VERSION
  • $BUILD
  • $AMT
  • $CURRENCYCODE
  • $AVSCODE
  • $CVV2MATCH
  • $TRANSACTIONID

We can then proceed to use these variables to present information back to our customer, populate values in email receipts we’d like to generate, update database information, or anything else we need to do once an order is completed.

The $ACK value is what will tell us whether or not the API call was successful or not.  Values for $ACK can be:

  • Success
  • SuccessWithWarning
  • Failure
  • FailureWithWarning
  •  

    You can simply redirect your user where they need to go and show them information based on this value.

    A failing API call will result in additional parameters that provide information about why the transaction failed.  If I run this test again with an invalid credit card number, for example, I get the following response back from PayPal:

    TIMESTAMP=2012%2d04%2d16T08%3a08%3a52Z&CORRELATIONID=590d41dbb31e0&ACK=Failure&VERSION=85%2e0&BUILD=2764190&L_ERRORCODE0=10527&L_SHORTMESSAGE0=Invalid%20Data&L_LONGMESSAGE0=This%20transaction%20cannot%20be%20processed%2e%20Please%20enter%20a%20valid%20credit%20card%20number%20and%20type%2e&L_SEVERITYCODE0=Error&AMT=100%2e00&CURRENCYCODE=USD

    Now, when we use parse_str() we end up with the following PHP variables available to us:

    • $TIMESTAMP
    • $CORRELATIONID
    • $ACK
    • $VERSION
    • $BUILD
    • $L_ERRORCODE0
    • $L_SHORTMESSAGE0
    • $L_LONGMESSAGE0
    • $L_SEVERITYCODE0
    • $AMT
    • $CURRENCYCODE

    In this case, $ACK shows a Failure so we know the call did not succeed and we can check the error parameters for more details about what went wrong.

    Additional Data Parsing Option

    While the previous method of parsing the response works just fine, I personally prefer to work with data arrays.  As such, I use the following function to convert the PayPal response into an array.

    // Function to convert NTP string to an array
    function NVPToArray($NVPString)
    {
    	$proArray = array();
    	while(strlen($NVPString))
    	{
    		// name
    		$keypos= strpos($NVPString,'=');
    		$keyval = substr($NVPString,0,$keypos);
    		// value
    		$valuepos = strpos($NVPString,'&') ? strpos($NVPString,'&'): strlen($NVPString);
    		$valval = substr($NVPString,$keypos+1,$valuepos-$keypos-1);
    		// decoding the respose
    		$proArray[$keyval] = urldecode($valval);
    		$NVPString = substr($NVPString,$valuepos+1,strlen($NVPString));
    	}
    	return $proArray;
    }

    This allows me to see all of the response data available by simply looking at the contents of the array:

    If I run my script again now I get the following result on screen:

    Array
    (
        [TIMESTAMP] => 2012-04-16T08:15:41Z
        [CORRELATIONID] => 9a652cbabfdd9
        [ACK] => Success
        [VERSION] => 85.0
        [BUILD] => 2764190
        [AMT] => 100.00
        [CURRENCYCODE] => USD
        [AVSCODE] => X
        [CVV2MATCH] => M
        [TRANSACTIONID] => 6VR832690S591564M
    )

    And If I were to cause an error again I get the following:

    Array
    (
        [TIMESTAMP] => 2012-04-16T08:18:46Z
        [CORRELATIONID] => 2db182b912a9
        [ACK] => Failure
        [VERSION] => 85.0
        [BUILD] => 2764190
        [L_ERRORCODE0] => 10527
        [L_SHORTMESSAGE0] => Invalid Data
        [L_LONGMESSAGE0] => This transaction cannot be processed. Please enter a valid credit card number and type.
        [L_SEVERITYCODE0] => Error
        [AMT] => 100.00
        [CURRENCYCODE] => USD
    )

    You can see this is a nice, easy to navigate result array that contains everything we might need to move the user through our application and update data sources as necessary.


    Conclusion

    As you can see, processing credit cards using PayPal Payments Pro is actually a very simple procedure.  It just involves a few standard steps for working with API web services, and a basic knowledge of working with array data can help as well.

    Good luck, and happy coding!

Related Posts
  • Code
    Tips
    New wp-config Tweaks You Probably Don't Know8 new wp config tweaks you probably didnt know about 400
    The wp-config.php file: One of the most loved WordPress feature for some, one of the worst nightmares for others. There are countless tips and tricks in a plethora of articles, and you can't get enough of them; however, this article is aiming to be different. In this article, we're going to get familiar with eight new wp-config tricks that are less known than functionality such as turning off post revisions, increasing the memory limit, or other similar features.Read More…
  • Code
    PHP
    Building a Customer Management App Using AngularJS and LaravelLaravel 4 auth retina preview
    When creating a single-page app we should use some kind of framework to do some of the job for us, so we can focus on the actual functionality. AngularJS fits here perfectly, because features like dynamic dependency injection and bi-directional data binding are just great. Sometimes we also require some kind of server. If you've chosen PHP then Laravel may be your best option, as it's easy to work with and pretty powerful.Read More…
  • Code
    JavaScript & AJAX
    Adding Bitcoin Payment Processing to Your WebsiteBitcoin retina preview
    Bitcoin has definitely started to become more mainstream, and with its global reach and minimal fees, it is a payment method worth considering. In this article, we will take a look at what Bitcoin is, as well as how to start accepting them in your applications.Read More…
  • Code
    PHP
    How to Accept Payments With StripeCode
    Processing credit cards is unfortunately far more difficult than we might hope, as developers. Given that it’s such a common task, is it really necessary that we jump through countless hoops (surrounded by fire, of course) for the sole purpose of processing a payment? Merchants? Gateways? SSL? Security? Very quickly, a seemingly simple operation can become an overwhelmingly confusing and, more importantly, dangerous task. Any time that you find yourself handling a user’s sensitive data, you better be on your toes. Read More…
  • Code
    PHP
    How to Setup Recurring PaymentsSetup recurring payments retina preview
    It's likely that, at some point, you'll want to implement recurring or subscription payments for a SaaS or other service. Thankfully, PayPal offers the tools we need to implement a fully integrated subscription payment solution.Read More…
  • Code
    Plugins
    A Guide to the WordPress HTTP API: Payments With PayPalPreview
    In the first part, we touched on the basics of the WordPress HTTP API and how to make a simple GET request and read the response. In this tutorial, we'll learn about the PayPal Express Checkout API and how to build a class that uses the HTTP API to process payments with PayPal. Preferably, you will have some knowledge of what PayPal is and also a Sandbox account (which is free and easy to get). We've done this as a plugin to show how the PayPal class works and ease making the HTTP requests.Read More…