Menu Close

PayPal-JS-FullStack-Standard-Checkout-Sample

PayPal Developer Cover


Twitter: PayPal Developer


Twitter
  –  
PayPal
  –  
Docs
  –  
Code Samples
  –  
Blog


PayPal JS FullStack Standard Checkout

This sample app shows you how to integrate PayPal into your app for the [standard checkout(https://developer.paypal.com/docs/checkout/standard/integrate/) workflow.

To create this application from scratch, follow the Standard Checkout integration guide from the PayPal Developer docs.

Public/index.html

Create Order

The createOrder() callback allows you to create the request of your order with the following properties from the V2 orders create call: item_total, purchase_units, and more.

createOrder: function (data, actions) { return fetch("/api/orders", { method: "post", }) .then((response) => response.json()) .then((order) => order.id); },

Approve Order

The onApprove() allows doing something with the order details after the order has been created. You can learn more about the onApprove() callback in your docs.

onApprove: function (data, actions) { return fetch(`/api/orders/${data.orderID}/capture`, { method: "post", }) .then((response) => response.json()) .then((orderData) => { // Successful capture! For dev/demo purposes: console.log( "Capture result", orderData, JSON.stringify(orderData, null, 2) ); const transaction = orderData.purchase_units[0].payments.captures[0]; alert(`Transaction ${transaction.status}: ${transaction.id} See console for all available details `); }); },

PayPal-API.js

Create Order

The createOrder() is called on the createOrder()callback from the PayPal button to create an order. In this function, you can create the request of your order with the following properties from the V2 orders create call: item_total, purchase_units, and more.

Endpoint: /api/orders

export async function createOrder() {
  const purchaseAmount = "100.00"; // TODO: pull prices from a database
  const accessToken = await generateAccessToken();
  const url = `${base}/v2/checkout/orders`;
  const response = await fetch(url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
    body: JSON.stringify({
      intent: "CAPTURE",
      purchase_units: [
        {
          amount: {
            currency_code: "USD",
            value: purchaseAmount,
          },
        },
      ],
    }),
  });

Capture Payment

The capturePayment() function is called on the onApprove() callback from the PayPal button once an order has been completed. In this function, you can use the value returned to be stored in a database or to do something else with it.

Endpoint: /api/orders/:orderID/capture

export async function capturePayment(orderId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v2/checkout/orders/${orderId}/capture`;
  const response = await fetch(url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
  });

  return handleResponse(response);
}

Server.js

This NodeJS server is using ExpressJS to create the backend server.

The following code serves the index.html page.

app.use(express.static("public"));

Capture payment POST endpoint that calls the paypal.createOrder() helper function.

app.post("/api/orders", async (req, res) => { try { const order = await paypal.createOrder(); res.json(order); } catch (err) { res.status(500).send(err.message); } });

Capture payment POST endpoint that calls the paypal.capturePayment() helper function.

app.post("/api/orders/:orderID/capture", async (req, res) => { const { orderID } = req.params; try { const captureData = await paypal.capturePayment(orderID); res.json(captureData); } catch (err) { res.status(500).send(err.message); } });

Run this App

You will need to create a .env file with the following environment variables:

CLIENT_ID=
APP_SECRET=

Complete the steps in Get started to get the following sandbox account information from the Developer Dashboard:

  • Sandbox client ID and the secret of a REST app.
  • Access token to use the PayPal REST API server.

paypal developer credentials

Now, run the following command in your terminal to start the server:

npm run start

and navigate in your browser to: http://localhost:8888/.

PayPal Developer Community

The PayPal Developer community helps you build your career while improving your products and the developer experience. You’ll be able to contribute code and documentation, meet new people and learn from the open-source community.

View Source Code
Posted in Development