codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🎨

HTML & CSS

41 / 59 topics
34HTML5 History API35HTML5 Web Workers36HTML5 Service Workers37HTML5 Fetch API38HTML5 WebSockets39HTML5 Geolocation API40HTML5 Device Orientation API41HTML5 Payment Request API42HTML5 Push Notifications
Tutorials/HTML & CSS/HTML5 Payment Request API
🎨HTML & CSS

HTML5 Payment Request API

Updated 2026-04-20
3 min read

HTML5 Payment Request API

The HTML5 Payment Request API is a modern web standard designed to simplify the payment process on websites. It allows users to make payments using their preferred payment method, such as credit cards, digital wallets, or other supported methods, directly from the browser. This API enhances user experience by reducing friction and providing a seamless payment flow.

In this tutorial, we will explore how to implement the Payment Request API in your web applications. We'll cover the basics of setting up the API, handling different payment methods, and integrating it with existing forms.

Prerequisites

Before diving into the implementation, ensure you have the following:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A modern web browser that supports the Payment Request API (e.g., Chrome, Firefox).

Setting Up the Payment Request API

To use the Payment Request API, you need to create a PaymentRequest object. This object requires three main parameters: supported payment methods, details about the transaction, and options for the payment request.

Supported Payment Methods

The first parameter is an array of objects representing the payment methods your application supports. Each object should have at least one method identifier, such as "basic-card" for credit cards or specific wallet identifiers like "https://apple.com/apple-pay" for Apple Pay.

const supportedMethods = [
  "basic-card",
  {
    supportedMethods: "https://apple.com/apple-pay",
    data: {
      merchantIdentifier: "merchant.com.example",
      supportedNetworks: ["visa", "mastercard"],
      countryCode: "US"
    }
  }
];

Transaction Details

The second parameter is an object that provides details about the transaction, such as the total amount and currency.

const details = {
  displayItems: [
    {
      label: 'T-shirt',
      amount: {currency: 'USD', value: '15.00'}
    }
  ],
  total: {
    label: 'Total',
    amount: {currency: 'USD', value: '15.00'}
  }
};

Payment Request Options

The third parameter is an optional object that allows you to specify additional options, such as whether shipping or payment handler details are required.

const options = {
  requestPayerName: true,
  requestPayerEmail: true,
  requestShipping: false
};

Creating the Payment Request Object

With the parameters defined, you can create a PaymentRequest object and display it to the user.

if (window.PaymentRequest) {
  const request = new PaymentRequest(supportedMethods, details, options);

  // Show the payment request dialog
  request.show()
    .then(response => {
      // Handle successful payment response
      return response.complete('success');
    })
    .catch(error => {
      // Handle errors
      console.error('Payment failed:', error);
    });
} else {
  console.log("Payment Request API is not supported in this browser.");
}

Handling Payment Responses

Once the user selects a payment method and completes the payment, the show() method resolves with a PaymentResponse object. You can use this object to process the payment on your server.

request.show()
  .then(response => {
    // Send payment details to the server for processing
    return fetch('/process-payment', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        methodName: response.methodName,
        details: response.details
      })
    }).then(res => {
      if (!res.ok) {
        throw new Error('Payment processing failed');
      }
      return res.json();
    }).then(data => {
      // Handle server response
      console.log('Payment processed:', data);
      return response.complete('success');
    });
  })
  .catch(error => {
    console.error('Payment failed:', error);
    request.abort();
  });

Best Practices

  1. Graceful Degradation: Always provide a fallback for browsers that do not support the Payment Request API.
  2. Security: Ensure that payment details are transmitted securely using HTTPS.
  3. User Experience: Test the payment flow thoroughly to ensure a smooth user experience across different devices and browsers.

Real-World Example

Here's a complete example of how you might integrate the Payment Request API into an e-commerce website:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Payment Request Example</title>
</head>
<body>
  <button id="payButton">Pay with Payment Request API</button>

  <script>
    const supportedMethods = [
      "basic-card",
      {
        supportedMethods: "https://apple.com/apple-pay",
        data: {
          merchantIdentifier: "merchant.com.example",
          supportedNetworks: ["visa", "mastercard"],
          countryCode: "US"
        }
      }
    ];

    const details = {
      displayItems: [
        {
          label: 'T-shirt',
          amount: {currency: 'USD', value: '15.00'}
        }
      ],
      total: {
        label: 'Total',
        amount: {currency: 'USD', value: '15.00'}
      }
    };

    const options = {
      requestPayerName: true,
      requestPayerEmail: true,
      requestShipping: false
    };

    document.getElementById('payButton').addEventListener('click', () => {
      if (window.PaymentRequest) {
        const request = new PaymentRequest(supportedMethods, details, options);

        request.show()
          .then(response => {
            return fetch('/process-payment', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                methodName: response.methodName,
                details: response.details
              })
            }).then(res => {
              if (!res.ok) {
                throw new Error('Payment processing failed');
              }
              return res.json();
            }).then(data => {
              console.log('Payment processed:', data);
              return response.complete('success');
            });
          })
          .catch(error => {
            console.error('Payment failed:', error);
            request.abort();
          });
      } else {
        alert("Payment Request API is not supported in this browser.");
      }
    });
  </script>
</body>
</html>

Conclusion

The HTML5 Payment Request API provides a powerful and user-friendly way to handle payments on the web. By following the steps outlined in this tutorial, you can integrate this API into your applications and offer a seamless payment experience to your users. Remember to test thoroughly and provide fallbacks for unsupported browsers to ensure a robust implementation.


PreviousHTML5 Device Orientation APINext HTML5 Push Notifications

Recommended Gear

HTML5 Device Orientation APIHTML5 Push Notifications