Search code examples
javascriptapplepayapplepayjs

Issue with Apple Pay integration in iframe


I recently started integrating Apple Pay into my website which actually loads the payment view in an iframe. Here the catch is my iframe loads in a different domain than my website. I followed the developer.apple.com site to integrate the Apple Pay into my website and created all the certificates and identifiers necessary.

Actual issue is when I'm trying to create the Apple Pay session, I'm receiving an error InvalidAccessError: Trying to start an Apple Pay session from a document with an different security origin than its top-level frame." I've not seen anyone facing this before.

Below is the code that I tried to create the Apple session.

var merchantIdentifier = 'my merchant identifier registered in developer account';
var promise = ApplePaySession.canMakePaymentsWithActiveCard(merchantIdentifier);
var canMakePayments = false;
promise.then(function (canMakePayments) {
    if(canMakePayments) {
        var session = new ApplePaySession(3, request);
    }
}, function(error) {
       alert(error);
});

As soon as the canMakePayments true line hits the code is trying to create an ApplePaySession and that is where I'm receiving the error.


Solution

  • Only way is running some JS on the top frame and communicate between them using messages.

    E.g. in the top frame

    window.addEventListener('message', (event) => {
      if(event.data.type === 'applepay') {
        const session = new ApplePaySession(...);
    
        ...
    
        session.onpaymentauthorized = (event) => {
          event.source.postMessage({ type: 'paymentauthorized', payment: event.payment});
        }
    
      }
    });
    

    in the iframe

    window.addEventListener('message', (event) => {
      if(event.data.type ==== 'paymentauthorized') {
        // do something with the event.data.payment data you received
      }
    });
    iframe.postMessage({type: 'applepay' });