Create and process orders

To create an order and authorize funds to make payments later, complete these steps:

1. Set up the order information object.
2. Initialize the order and redirect the user. Redirect the user to PayPal to confirm the order. After the user confirms the order, PayPal redirects the user back to the return URL specified in the payment object.
3. Complete the order setup and get the order ID.
4. At a later time, authorize funds and capture the order payment.

Tip: An authorized payment places funds on hold for a later payment while an order indicates that the buyer has consented to the purchase but does not place the funds on hold.

Set up the order information object

The order 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. To start the order process, create this object:

// Build PayPal order request
var payReq = JSON.stringify({
  intent:'order',
  payer: {
    payment_method: 'paypal'
  },
  redirect_urls:{
    return_url:'http://localhost:3001/process',
    cancel_url:'http://localhost:3001/cancel'
  },
  transactions: [{
    amount: {
      total: '30.03',
      currency: 'USD',
      details: {
        subtotal: '30.00',
        tax: '0.03'
      }
    },
    description: 'This is the payment transaction description.',
    invoice_number: '485787589673',
    payment_options: {
      allowed_payment_method: 'INSTANT_FUNDING_SOURCE'
    },
    item_list:{
      items: [{
        name: 'hat',
        quantity: '5',
        price: '3',
        tax: '0.01',
        sku: '123123',
        currency: 'USD'
      },{
        name: 'handbag',
        quantity: '1',
        price: '15',
        tax: '0.02',
        sku: '456456',
        currency: 'USD'
      }]
    }
  }]
});
require __DIR__ . '/../bootstrap.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;

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

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

// Set item list
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
  ->setCurrency('USD')
  ->setQuantity(1)
  ->setPrice(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
  ->setCurrency('USD')
  ->setQuantity(5)
  ->setPrice(2);

$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));

// Set payment details
$details = new Details();
$details->setShipping(1.2)
  ->setTax(1.3)
  ->setSubtotal(17.50);

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

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

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

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

  # 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": "30.03",
      "currency": "USD",
      "details": {
        "subtotal": "30.00",
        "tax": "0.03"
      }
    },
    "description": "This is the payment transaction description.",
    "invoice_number": "23423522324234234",
    "payment_options": {
      "allowed_payment_method": "INSTANT_FUNDING_SOURCE"
    },
    "item_list":{
      "items": [{
        "name": "hat",
        "quantity": "5",
        "price": "3",
        "tax": "0.01",
        "sku": "1",
        "currency": "USD"
      },{
        "name": "handbag",
        "quantity": "1",
        "price": "15",
        "tax": "0.02",
        "sku": "product34",
        "currency": "USD"
      }],
      "shipping_address":{
        "recipient_name": "Mr. Tester",
        "line1": "4thFloor",
        "line2": "unit#34",
        "city": "SAn Jose",
        "country_code": "US",
        "postal_code": "95131",
        "phone": "011862212345678",
        "state": "CA"
      }
    }
  }]
})
# Create payment object
payment = Payment.new({
  :intent => "order",

  # Set payment type
  :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 => [{

    # Items
    :item_list => {
      :items => [{
        :name => "hat",
        :quantity => "5",
        :price => "3",
        :tax => "0.01",
        :sku => "1",
        :currency => "USD"
      },{
        :name => "handbag",
        :quantity => "1",
        :price => "15",
        :tax => "0.02",
        :sku => "product34",
        :currency => "USD"
      }
    ]},

    # Amount - must match item list breakdown price
    :amount => {
      :total => "30.03",
      :currency => "USD",
      :details => {
        :subtotal => "30.00",
        :tax => "0.03"
      }
    },
    :description => "payment description.",
    :invoice_number => "126774445533222345",
    :payment_options => {
      :allowed_payment_method => "INSTANT_FUNDING_SOURCE"
    }
  }]
})
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.Capture;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Order;
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;

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

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

// 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 description.");

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

// Add payment details
Payment payment = new Payment();
payment.setIntent("order");
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 ListItem()
  {
    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",
  details = details
};

var transactionList = new ListTransaction();

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

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

Important: A unique invoice_number value must be supplied with each transaction. Using the same invoice_number as a previous transaction will produce a Duplicate invoice Id detected error.

Initialize the order and redirect the user

To create the order, pass the order information object in the order request. A successful call returns an approval_url. Redirect the customer to this URL to confirm the order information.

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
  }
}

To create the order, pass the order information object in the order request. A successful call returns an approval_url. Redirect the customer to this URL to confirm the order information.

Complete the order setup and get the order ID

After the user confirms, he or she is redirected to the URL that you defined in the order information object. The query string contains the PayerID and paymentId parameters, which are confirmation objects that complete the order setup. Use the order ID to capture payment later.

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

paypal.payment.execute(paymentId, payerId, function(error, payment){
  if(error){
    console.error(JSON.stringify(error));
  } else {
    if (payment.state === 'approved'
    && payment.transactions
    && payment.transactions[0].related_resources
    && payment.transactions[0].related_resources[0].order) {
      console.log('order authorization completed successfully');

      // Capture order id
      order = payment.transactions[0].related_resources[0].order.id;
    } else {
      res.send('payment not successful');
    }
  }
});
// Get payment object by passing paymentId
$paymentId = $_GET['paymentId'];
$payment = Payment::get($paymentId, $apiContext);

// Execute payment with payer id
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);

try {
  // Execute payment
  $result = $payment->execute($execution, $apiContext);

  // Extract order
  $order = $payment->transactions[0]->related_resources[0]->order;
} catch (PayPal\Exception\PayPalConnectionException $ex) {
  echo $ex->getCode();
  echo $ex->getData();
  die($ex);
} catch (Exception $ex) {
  die($ex);
}
# Payment id obtained when creating the payment (following redirect)
payment = Payment.find("PAY-28103131SP722473WKFD7VGQ")

# Execute order setup using payer_id obtained when creating the payment (following redirect)
if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}):
  print("Payment execute successfully")
  orderid = payment.transactions[0].related_resources[0].order.id
else:
  print(payment.error)
# Get payment id from query string following redirect
payment = Payment.find(ENV["paymentId"])

# Execute payment using payer_id obtained from query string following redirect
if payment.execute( :payer_id => ENV["PayerID"])
  logger.info "order executed successfully"

  # Capture order id
  orderid = payment.transactions[0].related_resources[0].order.id;
else
  logger.error payment.error.inspect
end
// Get payment id from query string following redirect
Payment payment = new Payment();
payment.setId("PAY-28103131SP722473WKFD7VGQ");

// Execute payment using payer_id obtained from query string following redirect
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId("DUFRQ8GWYMJXC");
try {
  Payment createdPayment = payment.execute(apiContext, paymentExecution);

  if ("approved".equals(createdPayment.getState())){
    // Get order id
    String orderId = createdPayment.getTransactions().get(0)
      .getRelatedResources().get(0).getOrder().getId();
  }
} 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 authorization.
var executedPayment = payment.Execute(apiContext, paymentExecution);

// Capture authorization object
var order = executedPayment.transactions[0].related_resources[0].order;

To complete the order setup, extract the paymentId and PayerID from the query string parameters. Once obtained, make a call to the respective SDK execute method to complete the order setup. In the success response object that is returned, extract the order ID.

Authorize funds and capture the order payment

Once an order is ready to be fulfilled, create an authorization to ensure that funds are available and then issue a capture request to process the funds.

var orderId = '9W723769WF684170J';

var capture_details = {
  amount: {
    currency: 'USD',
    total: '30.03'
  }
};

paypal.order.authorize(orderId, capture_details, function (error, authorization){
  if (error) {
    console.error(JSON.stringify(error));
  } else {
    paypal.order.capture(orderId, capture_details, function (error, capture) {
      if (error) {
        console.error(error);
      } else {
        console.log("ORDER CAPTURE SUCCESS");
        console.log(JSON.stringify(capture));
      }
    });
  }
});
// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD")
  ->setTotal(20);

// Set capture details
$captureDetails = new Authorization();
$captureDetails->setAmount($amount);

try {
  $result = $order->capture($captureDetails, $apiContext);
  print_r($result);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
  echo $ex->getCode();
  echo $ex->getData();
  die($ex);
} catch (Exception $ex) {
  die($ex);
}
order = Order.find(orderid)

response = order.authorize({
  "amount": {
    "currency": "USD",
    "total": "30.03"
  }
})

if order.success():
  capture = order.capture({
    "amount": {
      "currency": "USD",
      "total": "30.03"
    },
    "is_final_capture": True
  })

  if capture.success():
    print("Capture[%s] successfully" % (capture.id))
  else:
    print(capture.error)
else:
  print(order.error)
order = Order.find(orderid)

if order.authorize()
  capture = order.capture({
      :amount => {
      :currency => "USD",
      :total => "10"
    },
    :is_final_capture => true
  })

  if capture.success?
    logger.info "Capture[#{capture.id}]"
  else
    logger.error capture.error.inspect
  end
else
  logger.error capture.error.inspect
end
try {
  // Set auth amount
  Amount amount = new Amount();
  amount.setCurrency("USD");
  amount.setTotal("4.54");

  // Authorize order
  Order order = new Order();
  order = Order.get(apiContext, orderId);
  order.setAmount(amount);
  Authorization authorization = order.authorize(apiContext);

  // Capture payment
  Capture capture = new Capture();
  capture.setAmount(amount);
  capture.setIsFinalCapture(true);

  Capture responseCapture = authorization.capture(apiContext, capture);

  System.out.println("Capture id = " + responseCapture.getId()
    + " and status = " + responseCapture.getState());
} catch (PayPalRESTException e) {
  System.err.println(e.getDetails());
}
order.Authorize(apiContext);

var amount = new Amount()
{
  currency = "USD",
  total = "100.00",
  details = details
};

var capture = new Capture();
capture.amount = amount;
capture.is_final_capture = true;
order.Capture(apiContext, capture);

Set the order ID obtained from the previous step, then create a capture detail object, which contains the currency and total amount that you want to authorize and capture for the order.

Call the respective SDK method to authorize and ensure that the funds are available to capture from the funding source, such as PayPal. Pass the order ID and capture details object in the request.

If the funds are authorized, issue a request to the capture method to finalize payment and capture the funds, again passing through the order ID and capture details object to the method.

Additional information