Angular 8 – Angular Stripe Payment Gateway

Stripe allow us to easily accept and manage payments online. On the other hand, Angular is gathering more and more popularity. In this tutorial we will learn Stripe Payment Gateway in the Angular 8 application. Stripe payment gateway integration with the angular 8 application is very easy. There are lots of package available for the stripe and angular but i am going to show you, how easily you can handle stripe payment gateway in Angular 8 application without additional Angular 8 library for Stripe payment gateway

Before start Stripe integration in Angular 8. We need a Angular 8 Project. If you don’t know how to create a new angular 8 project. Follow this tutorial.

Stripe offer two way to interact with Stripe server using JS.

  • Default Stripe form.
  • Custom Stripe Form.

Default Stripe Form gives us the easiest and safest way to create a token.

So, let’s start with ‘Default Stripe Form’

First of all, we need to add a stripe checkout script which will highlight the global variable stripecheckout.

We have two ways to load this JS.

In the first method we need to add the script tag to the index.html file.

<script src="https://checkout.stripe.com/checkout.js"></script>

The second way to include it via component.

I will prefer second method becuase in this method the stripe will load when we really need it.

Open the app.component.ts file and add the below method on it

loadStripe() {
    
    if(!window.document.getElementById('stripe-script')) {
      var s = window.document.createElement("script");
      s.id = "stripe-script";
      s.type = "text/javascript";
      s.src = "https://checkout.stripe.com/checkout.js";
      window.document.body.appendChild(s);
    }
}

Next, Call the above method from ngOnInit method like below

ngOnInit() {
    this.loadStripe();
}

The loadStripe method will add the script dynamically when component will load.

Next, Create a new method called pay which will open the stripe payment form.

pay(amount) {    

    var handler = (<any>window).StripeCheckout.configure({
      key: 'pk_test_aeUUjYYcx4XNfKVW60pmHTtI',
      locale: 'auto',
      token: function (token: any) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log(token)
        alert('Token Created!!');
      }
    });

    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: amount * 100
    });

}

Next, We need to add the button to our component’s template. Open the app.component.html file and put the below html

<div class="container mt-5">
  <h2>Stripe Checkout</h2>
  <div class="row mt-5">
    <div class="col-md-4">
      <button (click)="pay(20)" class="btn btn-primary btn-block">Pay $20</button>
    </div>
    <div class="col-md-4">
      <button (click)="pay(30)" class="btn btn-success btn-block">Pay $30</button>
    </div>
    <div class="col-md-4">
      <button (click)="pay(50)" class="btn btn-info btn-block">Pay $50</button>
    </div>    
  </div>
  <p class="mt-5">
      Try it out using the test card number <b>4242 4242 4242 4242</b>, a random three-digit CVC number, any expiration date in the future, and a random five-digit U.S. ZIP code.
  </p>
</div>

After the above changes our app.component.ts file will looks like this

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  
  constructor() { }
  handler:any = null;
  ngOnInit() {

    this.loadStripe();
  }

  pay(amount) {    

    var handler = (<any>window).StripeCheckout.configure({
      key: 'pk_test_aeUUjYYcx4XNfKVW60pmHTtI',
      locale: 'auto',
      token: function (token: any) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log(token)
        alert('Token Created!!');
      }
    });

    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: amount * 100
    });

  }

  loadStripe() {
    
    if(!window.document.getElementById('stripe-script')) {
      var s = window.document.createElement("script");
      s.id = "stripe-script";
      s.type = "text/javascript";
      s.src = "https://checkout.stripe.com/checkout.js";
      s.onload = () => {
        this.handler = (<any>window).StripeCheckout.configure({
          key: 'pk_test_aeUUjYYcx4XNfKVW60pmHTtI',
          locale: 'auto',
          token: function (token: any) {
            // You can access the token ID with `token.id`.
            // Get the token ID to your server-side code for use.
            console.log(token)
            alert('Payment Success!!');
          }
        });
      }
      
      window.document.body.appendChild(s);
    }
  }
}

You have successfully integrated the strip with angler. With the above integration you will be able to generate tokens. Now you need to code some server side code to catch this payment.

For server side payment capture, visit https://stripe.com/docs/api/charges/create

Running application:

Run the application using ng serve --o and you should see three payment button, click on any one will appear stripe payment popup. Congrats!! See, it was easy.

Sometime we need more handling we can achieve it via (Custom Stripe Form). We will learn about this in next tutorial

Our Application will look like this

44 Comments

  1. Md. Helal Uddin said:

    Can you please update your tutorial as Stripe has released new version. Thanks

    July 27, 2019
    Reply
  2. Matt said:

    Good tutorial! worked for me on the first shot.. Thanks!

    September 19, 2019
    Reply
  3. Nawress said:

    Do you use the legacy version??

    November 7, 2019
    Reply
  4. Ajeet Verma said:

    how to send payment request on server after getting token.

    December 2, 2019
    Reply
    • Miguel Angel said:

      I’m just like you, did you get it?

      December 3, 2019
      Reply
  5. Ajeet Verma said:

    my methos is:
    pay(amount:any, title:any, membershipid:any) {
    if (this.Token.loggedIn() == false) {
    this.router.navigateByUrl(‘/login’);
    return false;
    }
    let handler = (window).StripeCheckout.configure({
    key: ‘pk_test_I50GTpyJhyrEbVrggdkFTgOG00KJDCrjwN’,
    locale: ‘auto’,
    token: function (token: any) {

    console.log(token);

    //alert(‘Token Created!!, Server Payment’);
    var UserId = localStorage.getItem(‘profileID’);
    let data = {“stripeToken”: token.id, “amount”: amount, “currency”: ‘NZD’, “UserID”: UserId, “MembershipID”: membershipid}
    console.log(data);

    this.Middleware.saveSuccessdata(data).subscribe((data) => {
    console.log(data);
    });
    }

    });
    handler.open({
    name: ‘Kalkine Subscription’,
    description: title,
    amount: amount * 100,
    zipCode: true,
    currency: ‘NZD’
    });
    }

    error is :
    ERROR TypeError: Cannot read property ‘saveSuccessdata’ of undefined
    at TokenCallback.token [as fn] (membership.component.ts:188)
    at TokenCallback.trigger (VM12554 checkout.js:3)
    at TokenCallback.trigger (VM12554 checkout.js:3)
    at IframeView.onToken (VM12554 checkout.js:3)
    at IframeView.closed (VM12554 checkout.js:3)
    at Object.closed (VM12554 checkout.js:3)
    at RPC.processMessage (VM12554 checkout.js:2)
    at RPC.processMessage (VM12554 checkout.js:2)
    at RPC.message (VM12554 checkout.js:2)
    at VM12554 checkout.js:2

    December 4, 2019
    Reply
    • w3path said:

      Use arrow function for token callback

      December 4, 2019
      Reply
  6. Ajeet Verma said:

    Can you explain with code.please

    December 4, 2019
    Reply
  7. Ajeet said:

    Thanks , it’s working

    December 4, 2019
    Reply
  8. Fareed said:

    Code Working Fine,
    But when I check at Stripe Account Payments I don’t see any entries over there.
    Where we can see the performed transactions using API.?

    December 18, 2019
    Reply
  9. Foysal Remon said:

    Hi, I have followed your tutorial. When I click on any pay button. It’s do nothing but reloading the same page.

    December 30, 2019
    Reply
  10. Blek said:

    Hi w3path,

    Thank you for this Tuto.
    Please give me a code for token callback. I would like use a service for send datas in backend nodejs to create a charge stripe.
    ******************************************************************************************************
    w3path said:
    Use arrow function for token callback
    *******************************************************************************************************
    This is my code is not work correctly :

    pay(reservation, sToken:any, sData:any) {
    let handler = (window).StripeCheckout.configure({
    key: ‘pk_test_IiguTRFJJDOLdfteZDgzgz’uHYGKDZ’,
    locale: ‘auto’,
    token: function (token: any) {
    // You can access the token ID with `token.id`.
    // Get the token ID to your server-side code for use.
    if (token) {
    stoken = token.id;
    console.log(token);
    alert(‘Token Created!!’);
    sData = {
    ‘sToken’: sToken,
    ‘sEmail’: reservation.email,
    ‘sCurrency’: ‘xaf’,
    ‘sAmount’: reservation.amount,
    ‘sDescription’: reservation.type +’ ‘+ reservation.motif,

    };
    console.log(sData);
    this.resourceService.saveResource(‘checkout’, this.sData).subscribe(data => {
    console.log(data);
    },err => {
    this.toastr.error(Errors(err), ‘Major Error’);
    console.log(‘err’, err);
    });
    }
    }

    March 3, 2020
    Reply
  11. xmc said:

    Najwieksza porazka w zyciu czlowieka to rozziew pomiedzy tym, kim mlgl sie stac, a tym, kim stal sie w rzeczywistosci.- Ashley Montagu.

    December 27, 2020
    Reply
  12. cheap mirtazapine said:

    My spouse and i have been really lucky that Louis managed to finish off his research through your precious recommendations he made through your web pages. It is now and again perplexing to just find yourself handing out solutions which people today may have been selling. Therefore we know we need the writer to give thanks to for that. The specific illustrations you have made, the simple web site navigation, the relationships you will help to instill – it’s got most powerful, and it’s really leading our son in addition to the family reason why the subject is fun, which is really pressing. Thank you for the whole lot! https://remeronmirtazapine.com

    January 8, 2021
    Reply
  13. sumair said:

    how we send token in api request because inside token function any variable any service are not call

    January 12, 2021
    Reply
  14. EKONOM.XMC.PL said:

    Zycie zaczyna sie po opuszczeniu wygodnego kokonu. – Neale Donald Walsh

    February 4, 2021
    Reply
  15. Ahkdguany said:

    online pharmacy no prescription needed canadian drug canadian pharcharmy

    February 6, 2021
    Reply
  16. Aluminium Metale said:

    Zycie, uswiadomil sobie, bardzo przypomina piosenke. Na poczatku jest tajemnica, na końcu – potwierdzenie, ale to w srodku kryja sie wszystkie emocje, dla ktorych cala sprawa staje sie warta zachodu. – Nicholas Sparks

    February 6, 2021
    Reply
  17. NncsGeste said:

    where can i buy viagra with out a prescriptrion young people viagra free viagra alternative

    February 7, 2021
    Reply
  18. Pianino Tematy said:

    Trzeba zyc bez wzgledu na to, ile razy runelo niebo. – David Herbert Lawrence

    February 8, 2021
    Reply
  19. FvfcGeste said:

    buy brand name viagra online buying viagra viagra canada

    February 10, 2021
    Reply
  20. Fqbbguany said:

    can you be turned down for a payday loan cash advance 33125 hard money loans santa barbara

    February 12, 2021
    Reply
  21. Ahbzguany said:

    payday loan mountain view ca payday loan ohio software for merchant cash advance

    February 13, 2021
    Reply
  22. Norwegia Tapety said:

    Krytykuj przyjaciela w cztery oczy, a chwal zawsze przy swiadkach i podwladnych. Leonardo da Vinci & Tm.

    February 13, 2021
    Reply
  23. Labxguany said:

    viagra 100mg vs cialis 20mg order viagra cialis foro donde comprar cialis generico

    February 16, 2021
    Reply
  24. Jbnvbluch said:

    cash loans cape town gumtree payday advance maryland payday loans direct lender no checking account

    February 16, 2021
    Reply
  25. Filozofia said:

    Najlepszym wojownikiem jest ten, kto zdola wroga przemienic w najlepszego przyjaciela. P. Coelho.

    February 16, 2021
    Reply
  26. Donaldcep said:

    Very high quality text.

    free robux

    February 17, 2021
    Reply
  27. USA Polityka said:

    Czlowiek nie moze zyc, nie wiedzac, po co zyje” – Gustaw Herling-Grudziński

    February 20, 2021
    Reply
  28. Japonia.XMC.PL said:

    Jesli bedziesz przykladnie pracowal osiem godzin dziennie, moze ci sie kiedys uda zostac kierownikiem i pracowac dwanascie. R. Frost

    February 23, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *