Angular 8 Stripe integration with custom form

Stripe is the best platform to collection payment online. In the angular 8 stripe integration tutorial, we will learn Stripe integration in Angular 8.

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.js makes it easy to collect credit card—and other similarly sensitive—details without having the information touch your server.

Set up Stripe Elements

First of all, we need to add a stripe script.

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 type="text/javascript" src="https://js.stripe.com/v2/"></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-custom-form-script')) {
    var s = window.document.createElement("script");
    s.id = "stripe-custom-form-script";
    s.type = "text/javascript";
    s.src = "https://js.stripe.com/v2/";
    s.onload = () => {
      window['Stripe'].setPublishableKey('pk_test_aeUUjYYcx4XNfKVW60pmHTtI');
    }
    
    window.document.body.appendChild(s);
  }
}

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

Next, Call the above method from ngOnInit method like below

ngOnInit() {
  this.loadStripe();
}

Create your payment form

Next, We need to create beautiful html form. We am using bootstrap in our project.

open the app.component.html file and put the below html

<div class="container">    
  <div class="row">
    <div class="col-xs-12 col-md-8 mr-auto ml-auto">            
      <div class="panel panel-default">
        <form [formGroup]="customStripeForm" (ngSubmit)="pay(customStripeForm.value)">
          <div class="panel-body mt-5">
            <h4>Stripe - Custom form demo</h4>    
            <p><b>{{ message }}</b></p>
            <div class="row">
              <div class="col-xs-12 col-md-12">
                <div class="form-group">
                  <label>CARD NUMBER</label>
                  <div class="input-group">
                    <input type="text" formControlName="cardNumber" class="form-control" placeholder="Valid Card Number" name="cardNumber" maxlength="18" />
                    <span class="input-group-addon">
                      <span class="fa fa-credit-card"></span>
                    </span>
                  </div>
                  <div *ngIf="submitted &amp;&amp; customStripeForm.controls.cardNumber.errors" class="text-danger">
                    <div *ngIf="customStripeForm.controls.cardNumber.errors.required">Card number is required</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col-xs-7 col-md-7">
                <div class="form-group">
                  <label><span class="hidden-xs">EXPIRATION</span> Date</label>
                  <div class="row">
                    <div class="col-md-6">
                      <div class="form-group">
                        <select formControlName="expMonth" class="form-control">
                          <option value="">Select Month</option>
                          <option value="1">01</option>
                          <option value="2">02</option>
                          <option value="3">03</option>
                          <option value="4">04</option>
                          <option value="5">05</option>
                          <option value="6">06</option>
                          <option value="7">07</option>
                          <option value="8">08</option>
                          <option value="9">09</option>
                          <option value="10">10</option>
                          <option value="11">11</option>
                          <option value="12">12</option>
                        </select>
                      </div>
                    </div>
                    <div class="col-md-6 pull-right">
                    <div class="form-group">
                      <select formControlName="expYear" class="form-control">
                        <option value="">Select Year</option>
                        <option value="20">2020</option>
                        <option value="21">2021</option>
                        <option value="22">2022</option>
                        <option value="23">2023</option>
                        <option value="24">2024</option>
                        <option value="25">2025</option>
                        <option value="26">2026</option>
                        <option value="27">2027</option>
                        <option value="28">2028</option>
                        <option value="29">2029</option>
                        <option value="30">2030</option>
                      </select>
                    </div>
                  </div>
                </div>

                <div *ngIf="submitted &amp;&amp; customStripeForm.controls.expMonth.errors" class="text-danger">
                  <div *ngIf="customStripeForm.controls.expMonth.errors.required">Expiration month is required</div>
                </div>

                <div *ngIf="submitted &amp;&amp; customStripeForm.controls.expYear.errors" class="text-danger">
                  <div *ngIf="customStripeForm.controls.expYear.errors.required">Expiration year is required</div>
                </div>
              </div>                            
            </div>
            <div class="col-xs-5 col-md-5 pull-right">
              <div class="form-group">
                <label>CV CODE</label>
                <input type="text" formControlName="cvv" class="form-control" placeholder="CVC" maxlength="4" />
              </div>
              <div *ngIf="submitted &amp;&amp; customStripeForm.controls.cvv.errors" class="text-danger">
                <div *ngIf="customStripeForm.controls.cvv.errors.required">CVV is required</div>
                <div *ngIf="customStripeForm.controls.cvv.errors.minlength">CVV must be at least 3 characters</div>
              </div>
            </div>
          </div>
        </div>
        <div class="panel-footer">
          <div class="row">
            <div class="col-xs-12 col-md-12">
              <button class="btn btn-warning btn-lg btn-block" *ngIf="!formProcess">Process payment</button>
              <span class="btn btn-warning btn-lg btn-block" *ngIf="formProcess">Processing please wait...</span>
            </div>
          </div>
        </div>
      </form>
      <p class="mt-2">Try it out using the test card number 4242 4242 4242 4242, a random three-digit CVC number and any expiration date in the future.</p>
    </div>
  </div>
</div>
</div>

Next, We will create a new method which will validate the form and get the form data and sent it to the stripe server to generate the token

Add the below method on app.component.ts file

pay(form) {

  if(!window['Stripe']) {
    alert('Oops! Stripe did not initialize properly.');
    return;
  }
  
  this.submitted = true;

  console.log(this.customStripeForm);
  if (this.customStripeForm.invalid) {      
    return;
  }   

  this.formProcess = true;
  console.log("form");
  console.log(form);
  if(!window['Stripe']) {
    alert('Oops! Stripe did not initialize properly.');
    return;
  }
  (<any>window).Stripe.card.createToken({
    number: form.cardNumber,
    exp_month: form.expMonth,
    exp_year: form.expYear,
    cvc: form.cvc
  }, (status: number, response: any) => {
    this.submitted = false;
    this.formProcess = false;
    if (status === 200) {
      this.message = `Success! Card token ${response.card.id}.`;
    } else {
      this.message = response.error.message;
    }
  });
}

You have successfully integrated the stripe with Angular 8. 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 this (https://stripe.com/docs/api/charges/create) url

Here is how our application will looks like

41 Comments

  1. Erick said:

    Hi i have a problem my code stops in this part

    (window).Stripe.card.createToken({
    number: form.cardNumber,
    exp_month: form.expMonth,
    exp_year: form.expYear,
    cvc: form.cvc
    }, (status: number, response: any) => {

    this.submitted = false;
    this.formProcess = false;
    if (status === 200) {
    this.message = `Success! Card token ${response.card.id}.`;
    } else {
    this.message = response.error.message;
    }
    });
    }
    It never enters to these lines

    August 9, 2019
    Reply
    • w3path said:

      Can you explain more? What you want to achieve?
      Are you trying to do some code on callback? If yes then you have to write your code just after ‘this.message = `Success! Card token ${response.card.id}`’;

      August 11, 2019
      Reply
      • chen said:

        Hello
        Nice to meet you I read your tutor. I am very interesting in it. Could you please share github link?

        September 16, 2019
        Reply
  2. Akash kumar Verma said:

    thank you so much for this tutorial. can you please share git link of this code.

    September 12, 2019
    Reply
  3. Angela said:

    Thank you very much! it works perfectly for me, your work is so professional!, I updated to version 3 in stripe only changing the link, that was so great!. Angela from Peru.

    September 24, 2019
    Reply
    • Martin Braun said:

      Hi Angela. I’ve implemented this tutorial with stripe version 2 and it worked 😉 But if I change to version 3 It looks like I cannot init the stripe successfully ;-( Does anybody has any clue? Thx.

      July 11, 2020
      Reply
  4. viagra pills said:

    Thanks for your whole work on this website. My niece takes pleasure in working on research and it is simple to grasp why. We all notice all relating to the powerful ways you render very useful tips and tricks via your website and therefore welcome response from website visitors on this theme while our own simple princess is without question understanding so much. Take pleasure in the rest of the year. Your performing a very good job. https://limoitnow.com/

    January 7, 2021
    Reply
  5. ABILIFY cheap said:

    I’m also commenting to let you be aware of of the excellent discovery my cousin’s child enjoyed checking your blog. She discovered a wide variety of details, most notably how it is like to have a marvelous coaching heart to get many more easily fully understand certain complicated matters. You actually did more than my desires. I appreciate you for delivering such great, healthy, educational and also cool guidance on that topic to Evelyn. https://abilifyaripiprazoles.com/

    January 8, 2021
    Reply
  6. escitalopram cost said:

    I happen to be writing to make you understand what a wonderful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the rest without problems understand various very confusing topics. You undoubtedly surpassed visitors’ expected results. Thanks for supplying those warm and helpful, trustworthy, revealing not to mention unique tips on your topic to Tanya. https://lexaproescitalopram.com/

    January 8, 2021
    Reply
  7. generic lexapro said:

    I’m also commenting to let you be aware of of the brilliant discovery my child encountered checking the blog. She came to understand a lot of details, including how it is like to have a marvelous coaching character to get certain people completely comprehend a variety of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel. https://lexaproescitalopram.com/

    January 8, 2021
    Reply
  8. seroquel price said:

    I am commenting to let you know of the fine encounter my friend’s daughter found reading your site. She figured out many issues, not to mention what it’s like to have a wonderful giving mindset to have men and women quite simply have an understanding of selected hard to do subject areas. You really exceeded our expectations. Many thanks for giving the insightful, safe, explanatory and as well as easy thoughts on the topic to Jane. https://seroquelquetiapine.com/#

    January 9, 2021
    Reply
  9. https://txt2080.com/ said:

    Yeah most of the words you can’t really use in normal sentences, like ‘I have good knowledge in math’ and if you replace it with the words on this list it just doesn’t work.
    my principal word of the day today was Stellar it is #37 on the list and he said Monday he is coming up with a word that is positive for me because he is trying to get me to be positive and not so negative to myself
    카지노사이트

    January 15, 2021
    Reply
  10. https://www.vfv79.com/ said:

    THIS WAS VERY USEFUL. THANK YOU 😊! YOU JUST HAVE TO KNOW WHEN AND WHERE TO USE THESE WONDERFUL WORDS. THEY ALL REPLACE AND COME IN BEAUTIFULLY. 😉
    I HAVE READ AN ARTICLE RECENTLY PUBLISHED IN “MEDICAL EXPRESS”, “WRITING GOOD ENGLISH: IS SCIENTIFIC ENGLISH A LATIN LANGUAGE IN DISGUISE?”
    카지노사이트

    January 15, 2021
    Reply
  11. https://liveone9.com/ said:

    WITH RESPECT TO THE STATISTICAL ANALYSES, I HAVE SOME COMMENTS. I WOULD LIKE TO POINT OUT THAT ANOVA, THE STATISTICAL TREATMENT USED TO COMPARE THE INCIDENCE OF LATIN/GREEK WORDS IN ENGLISH AGAINST PORTUGUESE TEXTS, IS NOT APPROPRIATE FOR THE DATA ANALYZED.
    THE REASON IS VERY SIMPLE: THE SAMPLE SPACE OF A NORMAL DISTRIBUTION IS THE WHOLE REAL SET OF NUMBERS EXTENDING FROM −∞ TO +∞. IN CONTRAST, THE SAMPLE SPACE OF A PROPORTION Π EXTENDS FROM ZERO TO ONE. ANOTHER POINT IS THAT THE BETA DISTRIBUTION IS SYMMETRIC ONLY WHEN (Π = ½ – BETA). THE BETA DISTRIBUTION,
    카지노사이트

    January 15, 2021
    Reply
  12. Maurice said:

    It’s actually a great and helpful piece of info. I’m glad
    that you shared this useful information with us.
    Please keep us informed like this. Thanks for sharing.

    Look at my site … cheap flights

    January 31, 2021
    Reply
  13. Ina said:

    I visit daily some sites and websites to read content,
    but this blog offers quality based content.

    Review my web blog: cheap flights

    January 31, 2021
    Reply
  14. Darrin said:

    Appreciate the recommendation. Let me try it out.

    my web blog … cheap flights (http://tinyurl.com/)

    February 2, 2021
    Reply
  15. Verona said:

    Wow, amazing blog layout! How long have you been blogging for?

    you make blogging look easy. The overall look of your site is fantastic, as well as the content!

    Also visit my website – cheap flights

    February 2, 2021
    Reply
  16. Rafaela said:

    You should take part in a contest for one
    of the greatest blogs online. I will recommend this
    web site!

    Visit my webpage … cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  17. NncsGeste said:

    generic viagra prescription free viagra generic sale viagraeb_amphl=freb_amprlz=1t4adfa_frca391ca391eb_ampprmd=ivnseb_ampei=ccmrtd7gepdtgqfrxyz0bqeb_ampstart=10eb_ampsa=n

    February 7, 2021
    Reply
  18. Fqhhguany said:

    canadian online pharmacy ED Trial Pack discount pharmaceuticals

    February 9, 2021
    Reply
  19. Ingrid said:

    When I initially left a comment I seem to have clicked the -Notify me when new comments
    are added- checkbox and from now on whenever a comment is
    added I receive 4 emails with the same comment.
    Is there a means you can remove me from that service?
    Cheers!

    Feel free to surf to my web page cheap flights – http://tinyurl.com

    February 12, 2021
    Reply
  20. pulmonary hypertension and sildenafil said:

    pulmonary hypertension and sildenafil

    pulmonary hypertension and sildenafil

    February 14, 2021
    Reply
  21. Annmarie said:

    My members of the family always point out that I am just killing my time at
    net, except I know I am getting know-how everyday by reading thes good articles or reviews.

    my web site – LincolnPLunz

    February 17, 2021
    Reply
  22. teen boy takes viagra said:

    teen boy takes viagra

    teen boy takes viagra

    February 23, 2021
    Reply

Leave a Reply

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