Process a PayPal payment

To create a PayPal payment, complete these steps:

1. Set up a payment information object that contains details about the PayPal payment.
2. Initialize the payment and redirect the user. To do so, send the payment object to PayPal. This action provides a redirect URL to which to redirect the user. After the user confirms the payment, PayPal redirects the user to the return URLs specified in the payment object.
3. Complete the payment. Use the payer and payment IDs provided in the query string following the redirect.

Set up the payment information object

The payment object contains information about the method of payment, transaction details, where to redirect the user after they accept the payment on PayPal, and so on. Start the payment by creating this object.

// Build PayPal payment request
var payReq = JSON.stringify({
  intent:'sale',
  payer:{
    payment_method:'paypal'
  },
  redirect_urls:{
    return_url:'http://localhost:3000/process',
    cancel_url:'http://localhost:3000/cancel'
  },
  transactions:[{
    amount:{
      total:'10',
      currency:'USD'
    },
    description:'This is the payment transaction description.'
  }]
});
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;

// Create new payer and method
$payer = new Payer();
$payer->setPaymentMethod("paypal");

// Set redirect urls
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl('http://localhost:3000/process.php')
  ->setCancelUrl('http://localhost:3000/cancel.php');

// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD")
  ->setTotal(10);

// Set transaction object
$transaction = new Transaction();
$transaction->setAmount($amount)
  ->setDescription("Payment description");

// Create the full payment object
$payment = new Payment();
$payment->setIntent('sale')
  ->setPayer($payer)
  ->setRedirectUrls($redirectUrls)
  ->setTransactions(array($transaction));
from paypalrestsdk import Payment

# Create payment object
payment = Payment({
  "intent": "sale",

  # Set payment method
  "payer": {
    "payment_method": "paypal"
  },

  # Set redirect urls
  "redirect_urls": {
    "return_url": "http://localhost:3000/process",
    "cancel_url": "http://localhost:3000/cancel"
  },

  # Set transaction object
  "transactions": [{
    "amount": {
      "total": "10.00",
      "currency": "USD"
    },
    "description": "payment description"
  }]
})
# Create payment object
payment = Payment.new({
  :intent =>  "sale",

  # Set payment type
  :payer =>  {
    :payment_method =>  "paypal"
  },

  # Set redirect urls
  :redirect_urls => {
    :return_url => "http://localhost/payment/execute",
    :cancel_url => "http://localhost:3000/"
  },

  # Set transaction object
  :transactions =>  [{

    # Items
    :item_list => {
      :items => [{
        :name => "item",
        :sku => "item",
        :price => "10",
        :currency => "USD",
        :quantity => 1
      }]
    },

    # Amount - must match item list breakdown price
    :amount =>  {
      :total =>  "10",
      :currency =>  "USD"
    },
    :description =>  "payment description."
  }]
})
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentExecution;
import com.paypal.api.payments.RedirectUrls;
import com.paypal.api.payments.Transaction;

// Set payer details
Payer payer = new Payer();
payer.setPaymentMethod("paypal");

// Set redirect URLs
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl("http://localhost:3000/cancel");
redirectUrls.setReturnUrl("http://localhost:3000/process");

// Set payment details
Details details = new Details();
details.setShipping("1");
details.setSubtotal("5");
details.setTax("1");

// Payment amount
Amount amount = new Amount();
amount.setCurrency("USD");
// Total must be equal to sum of shipping, tax and subtotal.
amount.setTotal("7");
amount.setDetails(details);

// Transaction information
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction
  .setDescription("This is the payment transaction description.");

// Add transaction to a list
ListTransaction transactions = new ArrayListTransaction();
transactions.add(transaction);

// Add payment details
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setRedirectUrls(redirectUrls);
payment.setTransactions(transactions);
var payer = new Payer() { payment_method = "paypal" };

var guid = Convert.ToString((new Random()).Next(100000));
var redirUrls = new RedirectUrls()
{
  cancel_url = "http://localhost:3000/cancel",
  return_url = "http://localhost:3000/process"
};

var itemList = new ItemList()
{
  items = new List()
  {
    new Item()
    {
      name = "Item Name",
      currency = "USD",
      price = "15",
      quantity = "5",
      sku = "sku"
    }
  }
};

var details = new Details()
{
  tax = "15",
  shipping = "10",
  subtotal = "75"
};

var amount = new Amount()
{
  currency = "USD",
  total = "100.00", // Total must be equal to sum of shipping, tax and subtotal.
  details = details
};

var transactionList = new List();

transactionList.Add(new Transaction()
{
  description = "Transaction description.",
  invoice_number = Common.GetRandomInvoiceNumber(),
  amount = amount,
  item_list = itemList
});

var payment = new Payment()
{
  intent = "sale",
  payer = payer,
  redirect_urls = redirUrls,
  transactions = transactionList
};

To create a PayPal payment, set payment_method to paypal under payer.

Adjust the rest of the payment information to your needs.

Initialize the payment and redirect the user

With the payment object set, you can initialize the payment on PayPal. After you send the request to create a payment, PayPal responds with a JSON response that includes a links object with the approval_url, which is the location to which to redirect the customer so that he or she can verify or cancel the payment.

paypal.payment.create(payReq, function(error, payment){
  var links = {};

  if(error){
    console.error(JSON.stringify(error));
  } else {
    // Capture HATEOAS links
    payment.links.forEach(function(linkObj){
      links[linkObj.rel] = {
        href: linkObj.href,
        method: linkObj.method
      };
    })

    // If redirect url present, redirect user
    if (links.hasOwnProperty('approval_url')){
      //REDIRECT USER TO links['approval_url'].href
    } else {
      console.error('no redirect URI present');
    }
  }
});
// Create payment with valid API context
try {
  $payment->create($apiContext);

  // Get PayPal redirect URL and redirect user
  $approvalUrl = $payment->getApprovalLink();

  // REDIRECT USER TO $approvalUrl
} catch (PayPal\Exception\PayPalConnectionException $ex) {
  echo $ex->getCode();
  echo $ex->getData();
  die($ex);
} catch (Exception $ex) {
  die($ex);
}
# Create payment
if payment.create():
  # Extract redirect url
  for link in payment.links:
    if link.method == "REDIRECT":
      # Capture redirect url
      redirect_url = str(link.href)

      # REDIRECT USER to redirect_url
else:
  print("Error while creating payment:")
  print(payment.error)
# Create payment
if payment.create
  # Capture redirect url
  redirect_url = payment.links.find{|v| v.rel == "approval_url" }.href

  # REDIRECT USER TO redirect_url
else
  logger.error payment.error.inspect
end
// Create payment
try {
  Payment createdPayment = payment.create(apiContext);

  Iterator links = createdPayment.getLinks().iterator();
  while (links.hasNext()) {
    Links link = links.next();
    if (link.getRel().equalsIgnoreCase("approval_url")) {
      // REDIRECT USER TO link.getHref()
    }
  }
} catch (PayPalRESTException e) {
    System.err.println(e.getDetails());
}
var createdPayment = payment.Create(apiContext);

var links = createdPayment.links.GetEnumerator();
while (links.MoveNext())
{
  var link = links.Current;
  if (link.rel.ToLower().Trim().Equals("approval_url"))
  {
    // REDIRECT USER TO link.href
  }
}

Issue a call to create the payment. Pass the payment information object that you created in the previous step. If that request succeeds, extract the approval_url and redirect the user to the PayPal URL to confirm that payment information.

Complete the payment

After the customer confirms the payment information, he or she is redirected to the URL that was specified in the payment information object, set in the first step. In the query string will also be two parameters, PayerID and paymentId. These parameters are confirmation objects used to complete the payment.

var paymentId = req.query.paymentId;
var payerId = { payer_id: req.query.PayerID };

paypal.payment.execute(paymentId, payerId, function(error, payment){
  if(error){
    console.error(JSON.stringify(error));
  } else {
    if (payment.state == 'approved'){
      console.log('payment completed successfully');
    } else {
      console.log('payment not successful');
    }
  }
});
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\ExecutePayment;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

// Get payment object by passing paymentId
$paymentId = $_GET['paymentId'];
$payment = Payment::get($paymentId, $apiContext);
$payerId = $_GET['PayerID'];

// Execute payment with payer id
$execution = new PaymentExecution();
$execution->setPayerId($payerId);

try {
  // Execute payment
  $result = $payment->execute($execution, $apiContext);
  var_dump($result);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
  echo $ex->getCode();
  echo $ex->getData();
  die($ex);
} catch (Exception $ex) {
  die($ex);
}
from paypalrestsdk import Payment

# Payment id obtained when creating the payment (following redirect)
payment = Payment.find("PAY-28103131SP722473WKFD7VGQ")

# Execute payment using payer_id obtained when creating the payment (following redirect)
if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}):
  print("Payment[%s] execute successfully" % (payment.id))
else:
  print(payment.error)
# Get payment id from query string following redirect
payment = Payment.find(ENV["PAYMENT_ID"])

# Execute payment using payer_id obtained from query string following redirect
if payment.execute( :payer_id => ENV["PAYER_ID"] )  #return true or false
  logger.info "Payment[#{payment.id}] executed successfully"
else
  logger.error payment.error.inspect
end
Payment payment = new Payment();
payment.setId(req.getParameter("paymentId"));

PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(req.getParameter("PayerID"));
try {
  Payment createdPayment = payment.execute(apiContext, paymentExecution);
  System.out.println(createdPayment);
} catch (PayPalRESTException e) {
  System.err.println(e.getDetails());
}
var guid = Request.Params["guid"];

// Using the information from the redirect, setup the payment to execute.
var paymentId = Session[guid] as string;
var paymentExecution = new PaymentExecution() { payer_id = payerId };
var payment = new Payment() { id = paymentId };

// Execute the payment.
var executedPayment = payment.Execute(apiContext, paymentExecution);

To complete the payment, extract the paymentId and PayerID from the query string parameters and call the execute method.

Additional information