Skip to content
Angular 2+ wrapper for StripeJS
TypeScript HTML JavaScript CSS
Branch: master
Clone or download
menzerath and richnologies add support for handleCardSetup() (#76)
* add handleCardSetup

* export CardSetupResult

* fix style
Latest commit 101caa4 Aug 18, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci chore(global): add circleci config for docs app Jan 31, 2019
.github chore(global): add github templates for contrib Feb 1, 2019
projects add support for handleCardSetup() (#76) Aug 18, 2019
.editorconfig
.gitignore ⚡️ heavy refactor to use angular CLI and Angular 7 Jan 30, 2019
.prettierrc ⚡️ heavy refactor to use angular CLI and Angular 7 Jan 30, 2019
CHANGELOG.md Update version to 7.4.3 (#73) (#74) Jun 15, 2019
LICENSE.md chore(global): update LICENSE extension Apr 1, 2018
README.md chore(global): update readme Feb 3, 2019
angular.json chore(ngx-stripe-tester): update style Feb 1, 2019
package-lock.json 🚧 working on docs page structure Jan 31, 2019
package.json fix(version): add version upper limit May 31, 2019
tsconfig.json ⚡️ heavy refactor to use angular CLI and Angular 7 Jan 30, 2019
tslint.json ⚡️ heavy refactor to use angular CLI and Angular 7 Jan 30, 2019

README.md

NgxStripe

version license

ngx-stripe

An Angular 7 wrapper for StripeJS elements

Features

  • Stripe Service
  • Lazy script loading

Installation

To install this library, run:

$ npm install ngx-stripe

Using the library

Import the NgxStripeModule into the application

The module takes the same parameters as the global Stripe object. The APIKey and the optional options to use Stripe connect

  • apiKey: string
  • options: { stripeAccount?: string; }
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Import your library
import { NgxStripeModule } from 'ngx-stripe';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgxStripeModule.forRoot('***your-stripe-publishable key***'),
    LibraryModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Stripe Service

Once imported, you can inject the StripeService anywhere you need. The stripe script will be loaded the first time the service is injected.

The stripe service exposes the same methods as the StripeJS instance but with typescript types. The API is based on Observables so it can be combined with other actions.

In the example below, the component mounts the card in the OnInit lifecycle. The buy button creates a Stripe token the could be sent to the server for further actions. In this example we just log that token to the console:

Example component (more HTML and CSS examples can be found at the Stripe Elements Examples):

<form novalidate (ngSubmit)="buy()" [formGroup]="stripeTest">
  <input type="text" formControlName="name" placeholder="Jane Doe">
  <div id="card-element" class="field"></div>
  <button type="submit">
    BUY
  </button>
</form>
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

import { StripeService, Elements, Element as StripeElement, ElementsOptions } from "ngx-stripe";

@Component({
  selector: 'app-stripe-test',
  templateUrl: 'stripe.html'
})
export class StripeTestComponent implements OnInit {
  elements: Elements;
  card: StripeElement;

  // optional parameters
  elementsOptions: ElementsOptions = {
    locale: 'es'
  };

  stripeTest: FormGroup;

  constructor(
    private fb: FormBuilder,
    private stripeService: StripeService) {}

  ngOnInit() {
    this.stripeTest = this.fb.group({
      name: ['', [Validators.required]]
    });
    this.stripeService.elements(this.elementsOptions)
      .subscribe(elements => {
        this.elements = elements;
        // Only mount the element the first time
        if (!this.card) {
          this.card = this.elements.create('card', {
            style: {
              base: {
                iconColor: '#666EE8',
                color: '#31325F',
                lineHeight: '40px',
                fontWeight: 300,
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSize: '18px',
                '::placeholder': {
                  color: '#CFD7E0'
                }
              }
            }
          });
          this.card.mount('#card-element');
        }
      });
  }

  buy() {
    const name = this.stripeTest.get('name').value;
    this.stripeService
      .createToken(this.card, { name })
      .subscribe(result => {
        if (result.token) {
          // Use the token to create a charge or a customer
          // https://stripe.com/docs/charges
          console.log(result.token);
        } else if (result.error) {
          // Error creating the token
          console.log(result.error.message);
        }
      });
  }
}

StripeCardComponent

As an alternative to the previous example, you could use the StripeCardComponent.

It will make a little bit easier to mount the card.

To fetch the Stripe Element, you could you use either the (card) output, or, by using a ViewChild, the public method getCard()

//stripe.html

<form novalidate (ngSubmit)="buy()" [formGroup]="stripeTest">
  <input type="text" formControlName="name" placeholder="Jane Doe">
  <ngx-stripe-card [options]="cardOptions" [elementsOptions]="elementsOptions"></ngx-stripe-card>
  <button type="submit">
    BUY
  </button>
</form>
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

import { StripeService, StripeCardComponent, ElementOptions, ElementsOptions } from "ngx-stripe";

@Component({
  selector: 'app-stripe-test',
  templateUrl: 'stripe.html'
})
export class StripeTestComponent implements OnInit {
  @ViewChild(StripeCardComponent) card: StripeCardComponent;

  cardOptions: ElementOptions = {
    style: {
      base: {
        iconColor: '#666EE8',
        color: '#31325F',
        lineHeight: '40px',
        fontWeight: 300,
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSize: '18px',
        '::placeholder': {
          color: '#CFD7E0'
        }
      }
    }
  };

  elementsOptions: ElementsOptions = {
    locale: 'es'
  };

  stripeTest: FormGroup;

  constructor(
    private fb: FormBuilder,
    private stripeService: StripeService) {}

  ngOnInit() {
    this.stripeTest = this.fb.group({
      name: ['', [Validators.required]]
    });
  }

  buy() {
    const name = this.stripeTest.get('name').value;
    this.stripeService
      .createToken(this.card.getCard(), { name })
      .subscribe(result => {
        if (result.token) {
          // Use the token to create a charge or a customer
          // https://stripe.com/docs/charges
          console.log(result.token.id);
        } else if (result.error) {
          // Error creating the token
          console.log(result.error.message);
        }
      });
  }
}

StripeFactoryService

If you get your stripe key in a lazy way, or if you need to work with more than one key, you can use this service.

If you don't know the key just call the forRoot method with no params:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Import your library
import { NgxStripeModule } from 'ngx-stripe';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgxStripeModule.forRoot(),
    LibraryModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then you can use the factory service to create stripe instances. The stripe instance has the same methods of old StripeService.

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

import { StripeInstance, StripeFactoryService } from "ngx-stripe";

@Component({
  selector: 'app-stripe-test',
  templateUrl: 'stripe.html'
})
export class StripeTestComponent implements OnInit {
  stripe: StripeInstance;

  constructor(
    private fb: FormBuilder,
    private stripeFactory: StripeFactoryService
  ) {}

  ngOnInit() {
    this.stripe = this.stripeFactory.create('***your-stripe-publishable key***');
  }
}

If you prefer to work the old StripeService, you can also update the key:

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

import { StripeService } from 'ngx-stripe';

@Component({
  selector: 'app-stripe-test',
  templateUrl: 'stripe.html'
})
export class StripeTestComponent implements OnInit {

  constructor(
    private fb: FormBuilder,
    private stripeSerivce: StripeService
  ) {}

  ngOnInit() {
    this.stripeService.setKey('***your-stripe-publishable key***');
  }
}

Stripe Instance and Stripe Reference

For situations where the module has any mistakes or missing methods (I'm aware it has) you can now access both your elements instance and a reference to Stripe:

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

import { StripeService } from 'ngx-stripe';

@Component({
  selector: 'app-stripe-test',
  templateUrl: 'stripe.html'
})
export class StripeTestComponent implements OnInit {

  constructor(
    private fb: FormBuilder,
    private stripeSerivce: StripeService
  ) {}

  ngOnInit() {
    // this is equivalent to window.Stipe, but it make sure the module is loaded
    const Stripe$: Observable<any> = this.stripeService.getStripeReference();

    // this is a reference to the stripe elements object
    const stripe = this.stripeService.getInstance();
  }
}

License

MIT © Ricardo Sánchez Gregorio

You can’t perform that action at this time.