async function ApplePay(buttonEl) {
  const paymentRequest = window.payments.paymentRequest(
    // Use global method from sq-payment-flow.js
    window.getPaymentRequest()
  );

  let applePay;
  try {
    applePay = await window.payments.applePay(paymentRequest);
  } catch (e) {
    console.error(e)
    return;
  }

  async function eventHandler(event) {
    // Clear any existing messages
    window.paymentFlowMessageEl.innerText = '';
    try {
      const result = await applePay.tokenize();
      if (result.status === 'OK') {
        console.log( "eventHandler OK" );
        // Use global method from sq-payment-flow.js
        window.createPayment(result.token);
      } else {
        window.paymentCanceled();
      }
    } catch (e) {
      if (e.message) {
        console.log( `Error: ${e.message}` );
        //window.showError(`Error: ${e.message}`);
        window.showError(`Error: No se ha podido completar el pago con Apple Pay`);
      } else {
        window.showError('Se ha producido un error al procesar el pago con Apple Pay');
      }
    }
  }

  buttonEl.addEventListener('click', eventHandler);
}
