Skip to content

Payment Request API

This lesson explains Payment Request API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Payment Request API Overview

The HTML5 Payment Request API provides a browser-native way to collect payment information, shipping address, payer name, email, and phone number from users. It simplifies checkout by allowing supported browsers and devices to show a native payment sheet instead of requiring users to fill long checkout forms manually.

The Payment Request API is commonly used in e-commerce websites, donation forms, subscription flows, ticket booking, food ordering, travel booking, digital product checkout, and Progressive Web Apps that need faster and more secure payments.

Feature Description
API Name Payment Request API
Main Object PaymentRequest
Main Method request.show()
Completion Method paymentResponse.complete()
Purpose Show native browser payment UI.
Security Requires HTTPS and user interaction.

Basic Payment Request Example

// HTML5 Payment Request API

async function startPayment() {
  if (!("PaymentRequest" in window)) {
    console.log("Payment Request API is not supported.");
    return;
  }

  const paymentMethods =
    [
      {
        supportedMethods: "basic-card"
      }
    ];

  const paymentDetails =
    {
      total: {
        label: "Total",
        amount: {
          currency: "USD",
          value: "49.99"
        }
      }
    };

  const request =
    new PaymentRequest(
      paymentMethods,
      paymentDetails
    );

  try {
    const response =
      await request.show();

    console.log(response);

    await response.complete("success");
  } catch (error) {
    console.error("Payment cancelled or failed.");
  }
}

This example checks browser support, creates a payment request, displays the native payment UI, and completes the payment after processing.

How Payment Request API Works

Step Description Example Syntax
Check Support Verify browser supports the API. "PaymentRequest" in window
Define Methods Define supported payment methods. supportedMethods
Define Details Set total, display items, tax, and shipping. paymentDetails
Create Request Create a new payment request. new PaymentRequest(methods, details)
Show Payment UI Open native browser payment sheet. request.show()
Complete Payment Tell browser whether payment succeeded or failed. response.complete("success")

Payment Method Data

const paymentMethods =
  [
    {
      supportedMethods: "basic-card",
      data: {
        supportedNetworks: [
          "visa",
          "mastercard",
          "amex",
          "discover"
        ],
        supportedTypes: [
          "credit",
          "debit"
        ]
      }
    }
  ];

Payment method data tells the browser which payment methods the website supports. In real production systems, this is usually integrated with a payment gateway or supported wallet provider.

Payment Details Example

const paymentDetails =
  {
    displayItems: [
      {
        label: "Product",
        amount: {
          currency: "USD",
          value: "39.99"
        }
      },
      {
        label: "Tax",
        amount: {
          currency: "USD",
          value: "3.20"
        }
      },
      {
        label: "Shipping",
        amount: {
          currency: "USD",
          value: "6.80"
        }
      }
    ],
    total: {
      label: "Total",
      amount: {
        currency: "USD",
        value: "49.99"
      }
    }
  };

The payment details object controls what the user sees in the payment sheet, including line items and the final total.

Payment Options

const paymentOptions =
  {
    requestPayerName: true,
    requestPayerEmail: true,
    requestPayerPhone: true,
    requestShipping: true,
    shippingType: "shipping"
  };
Option Description Example Value
requestPayerName Requests customer name. true
requestPayerEmail Requests customer email. true
requestPayerPhone Requests customer phone number. true
requestShipping Requests shipping address. true
shippingType Defines shipping purpose. shipping, delivery, pickup

Complete Checkout Example

async function checkout() {
  if (!("PaymentRequest" in window)) {
    alert("Use regular checkout form.");
    return;
  }

  const methods =
    [
      {
        supportedMethods: "basic-card"
      }
    ];

  const details =
    {
      displayItems: [
        {
          label: "HTML5 Course",
          amount: {
            currency: "USD",
            value: "29.99"
          }
        }
      ],
      total: {
        label: "Total",
        amount: {
          currency: "USD",
          value: "29.99"
        }
      }
    };

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

  const request =
    new PaymentRequest(
      methods,
      details,
      options
    );

  try {
    const response =
      await request.show();

    const paymentResult =
      await processPaymentOnServer(response);

    if (paymentResult.success) {
      await response.complete("success");
    } else {
      await response.complete("fail");
    }
  } catch (error) {
    console.error("Checkout cancelled.");
  }
}

In real applications, payment details must be sent to a secure backend or payment gateway for actual processing. The browser payment sheet does not replace server-side payment validation.

Send Payment Response to Server

async function processPaymentOnServer(response) {
  const serverResponse =
    await fetch("/api/payments", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(
        {
          methodName: response.methodName,
          details: response.details,
          payerName: response.payerName,
          payerEmail: response.payerEmail,
          payerPhone: response.payerPhone,
          shippingAddress: response.shippingAddress
        }
      )
    });

  return serverResponse.json();
}

Always process and verify payment information on the server. Never trust client-side payment data alone.

Check Whether User Can Make Payment

async function checkPaymentAvailability(request) {
  if (!request.canMakePayment) {
    return false;
  }

  try {
    const canPay =
      await request.canMakePayment();

    return canPay;
  } catch (error) {
    return false;
  }
}

The canMakePayment() method checks whether the user appears able to make a payment with the supported methods. Use it to decide whether to show a fast checkout button or fallback checkout form.

Shipping Address and Shipping Options

const details =
  {
    total: {
      label: "Total",
      amount: {
        currency: "USD",
        value: "55.00"
      }
    },
    shippingOptions: [
      {
        id: "standard",
        label: "Standard Shipping",
        amount: {
          currency: "USD",
          value: "5.00"
        },
        selected: true
      },
      {
        id: "express",
        label: "Express Shipping",
        amount: {
          currency: "USD",
          value: "15.00"
        }
      }
    ]
  };

const options =
  {
    requestShipping: true
  };

Shipping options allow customers to choose delivery methods during the payment flow.

Handle Shipping Option Changes

request.addEventListener(
  "shippingoptionchange",
  (event) => {
    const selectedOption =
      request.shippingOption;

    event.updateWith(
      updateTotalForShipping(selectedOption)
    );
  }
);

function updateTotalForShipping(optionId) {
  if (optionId === "express") {
    return {
      total: {
        label: "Total",
        amount: {
          currency: "USD",
          value: "65.00"
        }
      }
    };
  }

  return {
    total: {
      label: "Total",
      amount: {
        currency: "USD",
        value: "55.00"
      }
    }
  };
}

When users change shipping options, update the total amount so the final payment reflects the selected delivery method.

PaymentResponse Properties

Property / Method Description Common Use
methodName Selected payment method. Identify payment provider.
details Payment method-specific response data. Send to payment processor.
payerName Name provided by user. Receipt and order details.
payerEmail Email provided by user. Send confirmation email.
payerPhone Phone number provided by user. Delivery or support contact.
shippingAddress User shipping address. Delivery calculation and fulfillment.
complete() Completes payment UI. Show success or failure result.

Payment Request Events

Event When It Runs Common Use
shippingaddresschange User changes shipping address. Validate address and update shipping options.
shippingoptionchange User changes shipping method. Update total cost.
paymentmethodchange User changes payment method. Update fees or validation logic.

Feature Detection

function supportsPaymentRequest() {
  return "PaymentRequest" in window;
}

if (supportsPaymentRequest()) {
  console.log("Payment Request API supported.");
} else {
  console.log("Use normal checkout form.");
}

Always provide a traditional checkout fallback because support and available payment methods vary by browser, device, and region.

Common Payment Request API Use Cases

  • Fast checkout for e-commerce websites.
  • Donation forms.
  • Subscription sign-up flows.
  • Ticket booking and event registration.
  • Food delivery checkout.
  • Travel booking payments.
  • Digital product purchases.
  • Progressive Web App checkout flows.

Payment Request API Best Practices

  • Use HTTPS for all payment pages.
  • Always provide a normal checkout form fallback.
  • Process payments securely on the server.
  • Never trust client-side payment data alone.
  • Use canMakePayment() before showing fast checkout options.
  • Keep payment totals accurate and easy to understand.
  • Handle cancellation and failed payments gracefully.
  • Show clear order confirmation after successful payment.

Security and Privacy Considerations

  • Do not store raw payment details in the browser.
  • Use a trusted payment processor for real transactions.
  • Validate totals, products, shipping, taxes, and discounts on the server.
  • Use secure cookies or tokenized payment flows for sessions.
  • Protect checkout pages from XSS and script injection.
  • Do not expose secret payment gateway keys in frontend code.
  • Collect only the payer information your checkout actually needs.
  • Provide clear privacy and refund information.

Common Payment Request API Mistakes

  • Using the API without checking browser support.
  • Not providing a fallback checkout form.
  • Trusting totals calculated only on the client.
  • Not handling user cancellation.
  • Forgetting to call response.complete().
  • Assuming all browsers support the same payment methods.
  • Collecting unnecessary payer information.
  • Exposing sensitive payment configuration in frontend code.

Payment Request API vs Traditional Checkout Form

Feature Payment Request API Traditional Checkout Form
User Experience Fast native payment sheet. Manual form entry.
Browser Support Varies by browser and platform. Works everywhere.
Fallback Needed Yes. No special fallback needed.
Best Use Fast checkout enhancement. Primary reliable checkout flow.
Server Validation Required. Required.

Key Takeaways

  • The Payment Request API provides a native browser checkout experience.
  • Use new PaymentRequest() to create a payment request.
  • Use request.show() to display the payment UI.
  • Use response.complete() after processing payment.
  • Always validate and process payments on the server.
  • Always provide a traditional checkout fallback.

Important Note

The Payment Request API improves checkout experience, but it is not a complete payment processor. Real payments still require secure backend processing, gateway integration, fraud checks, server-side validation, and compliance with payment security requirements.