How to integrate the paypal payment api with php - rest - instant payment - sdk - install - composer
Topics

Hi!
I'm Karsten and I want to help people learn German.
Buy me a coffee if you feel I did well.

How to integrate the paypal payment api with php

Rest-API software development kit (SDK)

Instant payment and authentication

Let us first look at the file that authenticates you:

start.php:
require 'autoload.php';
define ('WEBSITE', 'http://www.name_of_your_site.com');
$credentials = new \PayPal\Rest\ApiContext(
		new \PayPal\Auth\OAuthTokenCredential(
		'aasdfasdfsdfgdfsghjdfxcbxcvbyasdfasdfasdfadsfasdfasdfasdfasdfadfadsfadsf', 
		'asdfasdfasdfasdfasdfasdfadsfasdfadfadfasdfasdfsdfgdsfgsdfgsfgsdfgsfgFasd')
);

Get an account at paypal first, then get an accout at PAYPAL developer.

Go to dashboard/My apps and create a new app, the name of the app that I have created is 'make_it_easy'.

Create an object of \PayPal\Auth\OAuthTokenCredential by passing the credentials of your account to the constructor (see above):

If you look closely, there is a sandbox version and the live version. Use the sandbox version to test your transactions.

Of course first you have to download the sdk from github in order to get the ZIP file.

autoload.php is in the PayPal-PHP-SDK folder:

Put start.php into the folder 'PayPal-PHP-SDK', and require it from anywhere:

pay.php:
require 'path/to/PayPal-PHP-SDK/start.php';
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;


$product1  = "Das deutsche Passiv";
$product2  = "EBook with compliments et1linguae";
$price    = 9.00;
$total = $price;
$payer = new Payer();
$payer->setPaymentMethod('paypal');

$item1 = new Item();
$item1->setName($product1)
      ->setSku('abcd')
      ->setCurrency('EUR')
      ->setQuantity(1)
      ->setPrice($price)
      ->setDescription('Enabling playing.')
      ->setCategory['DIGITAL']; 				
//    ->setShipping(1.2)
//    ->setTax(1.3)
$item2 = new Item();
$item2->setName($product2)
      ->setSku('abcde')
      ->setCurrency('EUR')
      ->setQuantity(1)
      ->setPrice(0.00)
      ->setDescription('Enabling playing.')
      ->setCategory['DIGITAL']; 				
       
$itemlist = new ItemList();
$itemlist->setItems(array($item1, $item2));

$details = new Details();
$details->setSubtotal ($total);

$amount = new Amount();
$amount->setCurrency('EUR')
       ->setTotal($total)
       ->setDetails($details);
       
$transaction = new Transaction();
$transaction->setAmount($amount)
            ->setItemList($itemlist)
            ->setDescription('Hello World!')
            ->setInvoiceNumber('12345');
//          ->setInvoiceNumber(uniqid());		
$redirect_Urls = new RedirectUrls();
$redirect_Urls->setReturnUrl(WEBSITE . '/url/to/processing_file.php?success=true')
              ->setCancelUrl(WEBSITE . '/url/to/processing_file.php?success=false');
			  
$payment = new Payment();
$payment->setIntent('sale')
        ->setPayer($payer)
        ->setRedirectUrls($redirect_Urls)
        ->setTransactions([$transaction]);
			
try {
$payment->create($credentials);
} catch (Exception $e){
die ($e);
}
	   
$approval_Url = $payment->getApprovalLink();   
header("Location: {$approval_Url}");

The sums must be correct, for example if you sell two products and two items of each product for 9 EUR:

pay.php:
require 'path/to/PayPal-PHP-SDK/start.php';
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;

$quantity = 2;
$product1  = "ebook1";
$product2  = "ebook2";
$price    = 9.00;
$total = $price*4;//2 items * 2 copies
$payer = new Payer();
$payer->setPaymentMethod('paypal');

$item1 = new Item();
$item1->setName($product1)
      ->setSku('abcd')
      ->setCurrency('EUR')
      ->setQuantity($quantity)
      ->setPrice($price)
      ->setDescription('a cool E-book no.1')
      ->setCategory['DIGITAL']; 				

$item2 = new Item();
$item2->setName($product2)
      ->setSku('abc')
      ->setCurrency('EUR')
      ->setQuantity($quantity)
      ->setPrice($price)
      ->setDescription('a cool E-book no.2')
      ->setCategory['DIGITAL']; 				
 
$itemlist = new ItemList();
$itemlist->setItems(array($item1, $item2));
//$itemlist->setItems([$item]);

$details = new Details();
$details->setSubtotal ($total);

$amount = new Amount();
$amount->setCurrency('EUR')
       ->setTotal($total)
       ->setDetails($details);

$transaction = new Transaction();
$transaction->setAmount($amount)
            ->setItemList($itemlist)
            ->setDescription('Hallo Welt!')
            ->setInvoiceNumber('12345');
			
$redirect_Urls = new RedirectUrls();
$redirect_Urls->setReturnUrl(WEBSITE . '/url/to/processing_file.php?success=true')
              ->setCancelUrl(WEBSITE . '/url/to/processing_file.php?success=false');
		  
$payment = new Payment();
$payment->setIntent('sale')
        ->setPayer($payer)
        ->setRedirectUrls($redirect_Urls)
        ->setTransactions([$transaction]);	
try {
$payment->create($credentials);
} catch (Exception $e){
die ($e);
}
$approval_Url = $payment->getApprovalLink();   
header("Location: {$approval_Url}");

The language settings adapt to your IP-Adress, for example Canada:

Or Germany:

Read the documentation to find out more.

Once the buyer has approved the payment they will be transferred back to your site and the order will get completed via this code (you have to customize and optimize it, of course):

url/to/processing_file.php?success=true:
require 'path/to/PayPal-PHP-SDK/start.php';

use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;


if (
      !isset ($_GET ['success']) 
   && !isset ($_GET ['paymentId'])
   && !isset ($_GET ['PayerID'])
   ){
   die("not set");
}

if ((bool)$_GET ['success'] === false ){
   die("Did you have any problems, can I help you in any way?");
}


$paymentId = $_GET ['paymentId'];
$payerId   = $_GET ['PayerID'];

$payment = Payment::get($paymentId, $credentials);

$execute = new PaymentExecution();
$execute->setPayerId($payerId);


$result = $payment->execute($execute, $credentials);

For more basic information go to the PayPal Classic APIs Getting Started Guide.

Once you are ready to go live there is a good documentation on github on how to do this.

This file is the most important file:

start.php:
require 'autoload.php';
define ('WEBSITE', 'http://www.name_of_your_site.com');
$credentials = new \PayPal\Rest\ApiContext(
		new \PayPal\Auth\OAuthTokenCredential(
		'aasdfasdfsdfgdfsghjdfxcbxcvbyasdfasdfasdfadsfasdfasdfasdfasdfadfadsfadsf', 
		'asdfasdfasdfasdfasdfasdfadsfasdfadfadfasdfasdfsdfgdsfgsdfgsfgsdfgsfgFasd')
);

It is used to authenticate you at the gates of paypal (the so called endpoint). The command is nested and can be also seen like this:


start.php:
require 'autoload.php';
define ('WEBSITE', 'http://www.name_of_your_site.com');
$Data = new \PayPal\Auth\OAuthTokenCredential(
		'aasdfasdfsdfgdfsghjdfxcbxcvbyasdfasdfasdfadsfasdfasdfasdfasdfadfadsfadsf', 
		'asdfasdfasdfasdfasdfasdfadsfasdfadfadfasdfasdfsdfgdsfgsdfgsfgsdfgsfgFasd');
$credentials = new \PayPal\Rest\ApiContext($Data);

What we are doing first is to create a \PayPal\Auth\OAuthTokenCredential object ($Data). See the documentation of this object in the SDK:

To do this you have to have a sandbox account as explained earlier. There you get the SANDBOX (not the live credentials, be careful with this) credentials, consisting of the ClientID and the Secret, which you insert here in the given order, first the ClientID, then the Secret. Then you create a \PayPal\Rest\ApiContext object ($credentials) to whose constructor you pass the \PayPal\Auth\OAuthTokenCredential object ($Data).

The paypal api is namespaced. So you have to use the corresponding namespaces:


use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;

What are they for? Imagine yourself creating a class of you own. You might want to call it ItemList. That would conflict with the api because it also has a class called ItemList. The namespaces exist so that the classes don't get mixed up and confused. Here are some variables of our own that are defined. Make sure that the sums are consistent and add up to the subtotal and the total price correctly:


$quantity = 2;
$product1  = "ebook1";
$product2  = "ebook2";
$price    = 9.00;
$total = $price*4;//2 items * 2 copies

This is the interesting part, the setting of the product(s):


$item1 = new Item();
$item1->setName($product1)
      ->setSku('abcd')
      ->setCurrency('EUR')
      ->setQuantity($quantity)
      ->setPrice($price)
      ->setDescription('a cool E-book no.1')
      ->setCategory['DIGITAL']; 				

$item2 = new Item();
$item2->setName($product2)
      ->setSku('abc')
      ->setCurrency('EUR')
      ->setQuantity($quantity)
      ->setPrice($price)
      ->setDescription('a cool E-book no.2')
      ->setCategory['DIGITAL']; 				

This code creates two item objects. Each object contains the different set-methods, through which the attributes of the product are set respectively. As you can see in the documentation you can set quite a few attributes like name, sku (your item number, specified for the customer as "item number" or "Artikelnummer" while buying your product), the currency you want to receive, the price, of course (which you have to specify as a float variable), etc.




submit to reddit





Sneak peek of the server side code