Search code examples
angularbraintree

braintree on Angular2


I'm trying to get the Braintree client sample (https://developers.braintreepayments.com/start/hello-client/javascript/v3) working on Angular2. I'm very new to Angular2 (and Javascript).

First of all, I'm not sure if I'm supposed to add "braintree-web": "^3.6.3" under package.json's dependencies. Or add

<script src="https://js.braintreegateway.com/web/3.6.3/js/client.min.js"></script>

and

<script src="https://js.braintreegateway.com/web/3.6.3/js/hosted-fields.min.js"></script> 

under index.html. I ended up doing both.

After I run npm install, if I look inside the node_modules/braintree-web, I see only .js files. I don't see any ts files. Is this a problem? Am I not supposed to use braintree-web for this? Is this package written for Angular1? If I do indeed have to use braintree-web, do I also need to include those 2 js files in my index.html? Doesn't braintree-web already include them?

In my payment.component.ts file, I copied and pasted the Braintree client code:

import { braintree } from 'braintree-web/client';
...
ngOnInit() {
    var authorization = '...';
    var submit = document.querySelector('input[type="submit"]');

    braintree.client.create({
      authorization: authorization
    }, function (clientErr, clientInstance) {
      if (clientErr) {

When I try to run tsc, I'm getting the following error:

app/admin/user/payment.component.ts(3,27): error TS2307: Cannot find module 'braintree-web/client'

What am I doing wrong?


Solution

  • Since Angular2 is strongly typed, you can't just use the Javascript sample code provided by Braintree. You need types defined for all those functions. So Trying to integrate braintree-web into Angular2 was the first clue that you need the @types/braintree-web installed (in package.json). These are not the official Braintree types, but open source contribution from http://definitelytyped.org/. I asked Braintree support for help and they mentioned you could use their Javascript sample code in Angular2, but you would need to specify a type for each parameter. They couldn't recommend the types package from definitelytyped because it's not their own code.

    You don't need any more imports at the top of the file, but you do need the 2 Braintree Javascript files included in index.html.