0

I am trying to implement Apple Pay on checkout in a react project using Typescript. I have installed the braintree-web package and followed the instructions on braintree's website to initialize my ApplePaySession. Although typescript allows me to compile the project, in the browser my call to new ApplePaySession(3, paymentRequest); is undefined. I have wracked my brain, but I cannot understand what is going wrong. Here's a code snippet for how I have initialized ApplePay.

import { applePay, ApplePayStatusCodes, ApplePaySession } from 'braintree-web';

...

beginApplePay() {
    if (!this.btApplePayInstance) {
      //throw an erro
    }

    const paymentRequest = this.createPaymentRequest();
    const session = this.createSession(paymentRequest);

    session && session.begin();
  }

  createSession(
    paymentRequest: braintree.ApplePayPaymentRequest
  ): braintree.ApplePaySession | null {
    let session: braintree.ApplePaySession;
    console.log('creating session');
    console.log('Sample payment request: ', paymentRequest);
    console.log(
      'Supports API v3: ' + window.ApplePaySession.supportsVersion(3)
    );


    try {
      debugger;
      session = new ApplePaySession(3, paymentRequest); //this is where it fails
      console.log(session);
    } catch (err) {
      console.log(err);
      //throw an error
      return null;
    }

This is what my browser says: TypeError: undefined is not a constructor (evaluating 'new braintree_web__WEBPACK_IMPORTED_MODULE_1__["ApplePaySession"](3, paymentRequest)')

Any insight into what's going wrong would be greatly appreciated.

user1427380
  • 93
  • 1
  • 4

2 Answers2

0

I found that adding

<script src="https://js.braintreegateway.com/web/3.55.0/js/apple-pay.min.js"></script>

at the top level Js file worked for me then just using @ts-ignore when using the session.

Ugly work around I know... If you have found a better solution please share.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Brad Waterhouse
  • 183
  • 1
  • 12
0

Update: I figured out that this is a typescript specific problem. In the type definitions for braintree-web, they define a type of ApplePaySession. When the project is built, the browser thinks that ApplePaySession is a reference to some class in the braintree-web when in fact it is a reference to the ApplePaySession native to the safari browser.

The solution I found was to use the types for ApplePayWebJS and reference the ApplePaySession provided there. However, this did produce some problems further down the line when trying to get the types of the two packages to play nicely together.

user1427380
  • 93
  • 1
  • 4