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

5 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

Leave a Reply

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