Process PayPal Payments
Important: These
/v1/payments
and general-purpose REST SDKs are deprecated. See our current SDK offerings, which include the/v2/checkout
and Payouts use cases. For other APIs, use direct integration.
To create a PayPal payment:
1. | Define payment with details about the PayPal payment. |
2. | Create payment. To create the payment, send the payment object to PayPal. This action provides a redirect URL to which to redirect the customer. After the customer accepts the payment, PayPal redirects the customer to the return or cancel URL that you specified in the payment object. |
3. | Execute payment. Use the payer ID and payment ID that the create payment call returns. |
Define payment
To define the payment, create a payment
object, which sets:
- The payment method to
paypal
- The transaction details
- The URL to which to redirect the customer after the customer accepts the cancels the PayPal payment
- Other information
// 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 List<Transaction> transactions = new ArrayList<Transaction>(); 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<Item>() { 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<Transaction>(); 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 };
Create payment
After you define the payment
object in step 1, use it to create the PayPal 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 the redirect URL is present, redirect the customer to that URL if (links.hasOwnProperty('approval_url')){ // Redirect the customer 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 the customer $approvalUrl = $payment->getApprovalLink(); // Redirect the customer 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 = (link.href) # Redirect the customer 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 the customer to redirect_url else logger.error payment.error.inspect end
// Create payment try { Payment createdPayment = payment.create(apiContext); Iteratorlinks = createdPayment.getLinks().iterator(); while (links.hasNext()) { Links link = links.next(); if (link.getRel().equalsIgnoreCase("approval_url")) { // Redirect the customer 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 the customer to link.href } }
Extract the approval_url
from the create payment response. Redirect the customer to this URL to accept or cancel the payment.
Execute payment
After the customer accepts the payment, your app redirects the customer to the return_url
or cancel_url
that you defined in the payment
object in step 1.
If the customer accepts the payment, you can execute the payment.
To execute the payment, set the payment ID and payer ID parameters in the request:
Note: The create payment call returns the payment ID and payer ID.
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 with the payer ID from the create payment call (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 with the payer ID 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);