Loading

How to integrate paypal in WordPress

September 19, 2014     Layero Themes    

Paypal integration can be a pain if you are doing it for the first time. But once you understand the procedure,its really easy. This tutorial will help you learn how to integrate Paypal with WordPress. This Paypal integration guide for WordPress covers all aspects and scenarios of payment integration in any CMS system.

# Step 1 – Implementing the Paypal Buy Now button form fields in your website.

Paypal button is basically a form, and you are posting this form to Paypal (when you click Buy Now) along with some hidden values  The code below shows a Paypal button form.

This form (when placed inside a template page code base) will generate a Paypal button inside that specific templates WordPress page. For instance if you have post type named “books”, place the button code inside single post page of the book post type so that the customer can buy each specific book using the Paypal buy now button.

Now lets have a look at the fields mentioned above(Hidden field names),

  • action – The action of the form (https://www.sandbox.paypal.com/cgi-bin/webscr). We post data to this url. Keep in mind that  sandbox part is for Paypal testing. If you need to take this live, just remove the “sandbox” part from the url
  • business – This is the email of paypal business account(the email to which payments are made in paypal)
  • currency_code – The currency code of the transaction to be made. USD in our example.
  • custom – A custom field(paypal pass through variable), we can use this field to pass a value to paypal. We’ll get the same value on return(after the payment) so that we can identify the payment. Say a user id, so that we can identify that a particular user have had made the payment. Here we’ve passed the post ID so that we can verify which book the customer has purchased. Other pass through variables are invoice,item_numberx,item_namex etc
  • amount – This is the amount that should be paid through Paypal. We fetch value of the price and pass it through the hidden field amount.
  • return – Place your return url here. Your customer will be redirected to this url once the payment is made. The transaction Id and other payment details will be appended along with the return url. We should verify the transaction id by posting another curl request to paypal. And if we get a successful notification from paypal , we can verify that the payment was genuine/successful/failure etc. We can store it inside the database or whatever as we wish. In WordPress, we need to create a Return Url Page template, create a page and assign the return url template to it and finally pass the return url in the above mentioned Paypal button form.
  • cancel_return – The cancellation url. Pretty straightforward, the customer will be directed to this url once he changes his mind and cancels the payment. We can create another WordPress page template for this if necessary

# Step 2 – Paypal Payment Notifications

There are two methods in verifying a paypal payment. You can use any one of them or both depending on your requirements

Method 1 – PDT
Method 2 – IPN

Method 1- PDT (Payment data transfer)

Enabling PDT and getting the identity token

This is the most preferred method . Once the customer makes a payment, he is returned to the website and the payment is verified. We need to enable PDT in Paypal first.

Logging to your Paypal business account and get into,

Profile>My Selling Tools > Website Preferences (In the Selling Online section)

paypal auto return

turn on the PDT and enable the auto return feature. After saving this page you’ll get an identity token. You need this token to verify the transaction

The Return URL page template

/**
 * Template Name: Paypal Return Url Page
 */
if($_GET['cm']) $postID=$_GET['cm']; 
// The unique transaction id. 
    if($_GET['tx']) $tx= $_GET['tx'];
    $paypalAction="https://www.sandbox.paypal.com/cgi-bin/webscr";
// Curl post to paypal inorder to verify the paypal transaction id
// Init 
    $ch = curl_init(); 
// Set request options 
    curl_setopt_array($ch, array ( CURLOPT_URL => $paypalAction,
      CURLOPT_POST => TRUE,
      CURLOPT_POSTFIELDS => http_build_query(array
        (
          'cmd' => '_notify-synch',
          'tx' => $tx,
          'at' => $identity,
          )),
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HEADER => FALSE,
  // CURLOPT_SSL_VERIFYPEER => TRUE,
  // CURLOPT_CAINFO => 'cacert.pem',
      ));
// Execute request and get response and status code
    $response = curl_exec($ch);
    $status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close connection
    curl_close($ch);
    $lines = explode("n", $response);
    $processed = (strcmp($lines[0], "SUCCESS") == 0) ? true : false;
    unset($lines[0]);
    unset($lines[30]);
    $paypalReturnArray = array();
    foreach ($lines as $line)
    {
        if(!empty($line)){
           list($key,$val) = explode("=", $line);
           $paypalReturnArray[urldecode($key)] = urldecode($val);
       }

   }

if ($processed && $paypalReturnArray['payment_status'] == 'Completed') {
 add_post_meta($_GET['item_number'],'paypal',json_encode($paypalReturnArray));
}

I’ve mentioned about the pass through custom hidden variable above. We can obtain back the variable (Post id)in return url page.

 $postID=$_GET['cm']; 

We can get the transaction id from,

$tx= $_GET['tx'];

After all we are posting a curl request to paypal with these fields,

      CURLOPT_POSTFIELDS => http_build_query(array
        (
          'cmd' => '_notify-synch',
          'tx' => $tx,
          'at' => $identity,
          )),

Here the $identity represents the identity token I’ve mentioned above. Get it, hardcocde it and post it to Paypal. After posting the transaction id to Paypal and verifying it, we’ll get the response. We do parse the response and get the final results in an array variable $paypalReturnArray.

If the status is completed we’ll save this as a meta field value. So that we can retrieve this later and can put an order history in the WordPress admin side.

 add_post_meta($_GET['item_number'],'paypal',json_encode($paypalReturnArray));

Check out the return page after a successful payment

paypal order

Method 2- IPN(Instant Payment Notifications)

From your paypal business account , you need to browse into,

Profile >My Selling Tools > Instant Payment Notifications(under Getting paid and managing my risk)

Under that you need Choose IPN Settings, and you need to provide an IPN Notification url and enable the Receive IPN Messages option.

ipn paypal

Her you’ll be setting an ipn return url where you can receive the instant payment notification as post data. You can verify the status of the payment by looping through the post data.

$ipnPost=$_POST;
foreach ($ipnPost as $key => $value) {
  $finalIPN[$key] = $value;
}
// Saving the encode transaction details  to the table
$dataJson = json_encode($finalIPN);

You’ll receive an instant payment notification to the url mentioned as soon as the customer makes the payment. No matter whether he closes his window or his network crashes, you will be receiving the notification.

# Step 3 – Creating order history in the WordPress admin side.

An order history page is really important that you can check the orders, verify it and take the necessary steps. Lets check how we can create an order management section in the WordPress admin side.

Keep in mind that we already saved the json Paypal return (order data) as meta key value pairs.

 add_post_meta($_GET['item_number'],'paypal',json_encode($paypalReturnArray));

Now What we need to do is to retrieve them and show in the WordPress admin side(have a look at the complete code).

Hope you enjoyed this article. If you have any queries or doubts, feel free to post a comment .

Categories: Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Support