How to create a future payment with PayPal in PHP

May 5, 2020

FuturePaymentPayPalEN
PayPal allows you to create a payment whose completion, i.e. the withdrawal and receipt of money, will take place later. This article will explain how to use this functionality in a web application using PHP.

Before you can use the PayPal API, you need to install the PayPal SDK which consists of its download from the following link PayPal SDK, in unpacking in the application folder, initialize the SDK going to include the following file

require FCPATH  . '/PayPal-PHP-SDK/autoload.php';

and in recalling the various objects used at the beginning of the PHP file through a directive of this type

use PayPal\Api\Payer;

Creation of future payment

In order to use this functionality, you need to take two steps, create the object that represents the payment and redirect the PayPal system so that the buyer provides the authorization.
To create the object you must first create the instance of the bees, specifying the ClientID and the ClientSecret that are obtained from the PayPal developer area after the creation of a project https://www.paypal.com/signin?intent=developer

$apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                'ClientID',     // ClientID
                'ClientSecret'      // ClientSecret
            )
);

and a number of instances of PayPal classes:

  • An object that represents the buyer
$payer = new Payer();
$payer -> setPaymentMethod("paypal");
  • An object representing the seller, where the email associated with his account is set
$payee = new Payee();
$payee->setEmail("venditore@example.com");
  • An object that represents the amount of the payment, where the currency must be specified, specifying the codice stringa, and the total
$amount = new Amount();
$amount->setCurrency("EUR")->setTotal("25.00");
  • An object that represents the transaction where to specify the instance of the payment amount, the description of the transaction, a string that identifies it and the instance of the recipient of the payment
$transaction = new Transaction();
$transaction->setAmount($amount)->setDescription("Pagamento per camera Basic")->setCustom("Pagamento 001")->setPayee($payee);
  • An object containing urls where to redirect in case of a successfully created transaction or in case of a transaction not created
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("http://www.example.com/success")->setCancelUrl("http://www.example.com/failed");

Finally, the future payment can be created

$payment = new FuturePayment();
$payment->setIntent("authorize")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

$payment->create($apiContext);

Full function

$apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                'ClientID',     // ClientID
                'ClientSecret'      // ClientSecret
            )
);

$payer = new Payer();
$payer->setPaymentMethod("paypal");
$payee = new Payee();
$payee->setEmail("venditore@example.com");
$amount = new Amount();
$amount->setCurrency("EUR")->setTotal("25.00");
$transaction = new Transaction();
$transaction->setAmount($amount)->setDescription("Pagamento per camera Basic")->setCustom("Pagamento 001")->setPayee($payee);
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("http://www.example.com/success")->setCancelUrl("http://www.example.com/failed");

$payment = new FuturePayment();
$payment->setIntent("authorize")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

$payment->create($apiContext);

After the creation of the payment it is necessary to redirect to the PayPal site so that the buyer provides the authorization for the payment. The url is obtained through the following method

$payment->getApprovalLink();

Receipt of payment

Also in order to proceed with the positive closure of the payment and, consequently, upon its receipt, it is necessary to create an instance of the bees, which we avoid repeating, and a series of objects:

  • One that represents the payment by specifying the identifier of it obtained as a return parameter in the success URL
$payment = Payment::get("PAYID-AF46441464AF", $apiContext);
  • One that represents the execution of the payment, where to specify the buyer’s PayPal ID, also obtained as a parameter in the success URL
$execution = new PaymentExecution();
$execution->setPayerId("ADAFSD3443CS3");
  • One who represents the authorization of the transaction
try {
  $result = $payment->execute($execution, $apiContext);
  $authorization = $result->getTransactions()[0]->getRelatedResources()[0]->getAuthorization();
} catch (Exception $ex) {
    print_r($ex);
}
  • After obtaining authorization from this, obtain the identifier of it and the total
$authorizationId = $authorization->getId();
$total = $authorization->getAmount()->getTotal();
  • One representing authorization for payment
$authorization = Authorization::get($authorizationId, $apiContext);
  • One that represents the amount of the payment
$amt = new Amount();
$amt->setCurrency("EUR")->setTotal($total);
  • One who represents the class to conclude the payment
$capture = new Capture();
$capture->setAmount($amt);

After making this the payment can be concluded and the money received

$capture = $authorization->capture($capture, $apiContext);

Full function

$payment = Payment::get("PAYID-AF46441464AF", $apiContext);
$execution = new PaymentExecution();
$execution->setPayerId("ADAFSD3443CS3");
$authorization = null;

try {
    $result = $payment->execute($execution, $apiContext);
    $authorization = $result->getTransactions()[0]->getRelatedResources()[0]->getAuthorization();
} catch (Exception $ex) {
    print_r($ex);
}

$authorizationId = $authorization->getId();
$total = $authorization->getAmount()->getTotal();
$authorization = Authorization::get($authorizationId, $apiContext);
$amt = new Amount();
$amt->setCurrency("EUR")->setTotal($total);

$capture = new Capture();
$capture->setAmount($amt);
$capture = $authorization->capture($capture, $apiContext);

Cancellazione della transazione

In order to cancel the transaction it is necessary to create an instance of the bees, which we avoid repeating, and a series of instances of PayPal classes:

  • One that represents the payment by specifying the identifier of it obtained as a return parameter in the success URL
$payment = Payment::get("PAYID-AF46441464AF", $apiContext);
  • Uno che rappresenta l’esecuzione del pagamento, dove specificare l’identificativo PayPal dell’acquirente, anch’esso ottenuto come parametro nell’URL di successo
$execution = new PaymentExecution();
$execution->setPayerId("ADAFSD3443CS3");
  • One that represents the authorization of the transaction
try {
  $result = $payment->execute($execution, $apiContext);
  $authorization = $result->getTransactions()[0]->getRelatedResources()[0]->getAuthorization();
} catch (Exception $ex) {
    print_r($ex);
}
  • After obtaining authorization from this, obtain the identification of it
$authorizationId = $authorization->getId();
  • One representing authorization for payment
$authorization = Authorization::get($authorizationId, $apiContext);

After doing this the payment can be canceled

$authorization->void($apiContext);

Full function

$payment = Payment::get("PAYID-AF46441464AF", $apiContext);
$execution = new PaymentExecution();
$execution->setPayerId("ADAFSD3443CS3");
$authorization = null;

try {
    $result = $payment->execute($execution, $apiContext);
    $authorization = $result->getTransactions()[0]->getRelatedResources()[0]->getAuthorization();
} catch (Exception $ex) {
    print_r($ex);
}

$authorizationId = $authorization->getId();
$authorization = Authorization::get($authorizationId, $apiContext);
$authorization->void($apiContext);
© 2020 Nifty tech tag lists from Wouter Beeftink