onpayerdetailchange

The onpayerdetailschange event handler of a PaymentResponse instance lets you get notified when the user updates a requested piece of personal information.

Example

In this example, we show how onpayerdetailschange to validate user's details, and ask the user to correct any mistakes.

// causes input fields to appear in
// browser's payment sheet.
const options = {
  requestShipping: true,
  requestPayerEmail: true,
  requestPayerName: true,
  requestPayerPhone: true,
};
const request = new PaymentRequest(methods, details, options);
const response = request.show();

// Let's check what we got back
let {
  payerName: oldPayerName,
  payerEmail: oldPayerEmail,
  payerPhone: oldPayerPhone,
} = response;

// Assuming they are invalid, we can ask
// the user to fix things via .retry() below

response.onpayerdetailchange = async ev => {
  const promisesToValidate = [];
  const { payerName, payerEmail, payerPhone } = response;
  if (oldPayerName !== payerName) {
    promisesToValidate.push(validateName(payerName));
    oldPayerName = payerName;
  }
  if (oldPayerEmail !== payerEmail) {
    promisesToValidate.push(validateEmail(payerEmail));
    oldPayerEmail = payerEmail;
  }
  if (oldPayerPhone !== payerPhone) {
    promisesToValidate.push(validatePhone(payerPhone));
    oldPayerPhone = payerPhone;
  }
  const errors = await Promise.all(promisesToValidate).then(results =>
    results.reduce((errors, result), Object.assign(errors, result))
  );
  // Check if we are good!
  if (Object.getOwnPropertyNames(errors).length) {
    await response.retry(errors);
  } else {
    // yay! data looks good.
    await fetch("/pay-for-things/", { method: "POST", body: response.json() });
    response.complete("success");
  }
};

await response.retry({
  payer: {
    email: "invalid domain.",
    phone: "invalid number.",
  },
});

Document Tags and Contributors

Contributors to this page: marcoscaceres
Last updated by: marcoscaceres,