Issue: “Must create a new ApplePaySession from a user gesture handler.”

This JavaScript error is thrown by the Apple Pay SDK if there’s an attempt to create a ApplePaySession outside of a user gesture handler.

This usually means there’s too much time between the last user interaction, and the start of the Apple Pay session. This is usually caused by some kind of slow task that is performed right after a user clicked a button to submit Embed and before the Apple Pay payment sheet opens. For example, you may try to make an API call to your server to get the latest order ID, which can take hundreds of milliseconds. This delay between the last user action and the start of the Apple Pay session causes Apple Pay to fail.

Solution: Use onBeforeTransaction

To solve for this issue, move any slow actions into Embed’s onBeforeTransaction callback. This function will run before the transaction is created, but after Apple Pay has been initialized.

Make sure to return a promise from inside the callback block. You will need to make it resolve or reject depending on your needs. If reject is called, a transaction will not be created and the transactionFailed event will be broadcasted.

onBeforeTransaction: () => {
  return new Promise((resolve, reject) => {
    fetch('https://example.com/someapi')
      .then((response) => response.json())
      .then((data) => {
        resolve()
      })
      .catch((err) => {
        reject()
      })
  });
},

Waiting for a server response before programmatically submitting Embed

In some cases, you might want to make a call to your server to fetch some information to include as part of the transaction, when the user clicks your custom Pay button and before submitting with embed.submit().

However, this can cause the issue described above, where Apple Pay fails because there’s a delay between the last user interaction (clicking the Pay button) and the start of the Apple Pay session (happening on embed.submit() once the call is complete). Moving the call to onBeforeTransaction won’t work in this case as that callback is executed after the Apple Pay session has already been initialized. It is currently not possible to update the information in the payment sheet once open.

This is a security measure of the Apple Pay SDK and there is no way to prevent this error from occurring in that scenario.