Service Factory

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

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

Then you can use the factory service to create stripe instances. The stripe instance has the same api as the regular StripeService.

You need to pass the stripe instance you create with Factory to the ngx-stripe-card component, or any other HTML element

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

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

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

  stripe: StripeInstance;
  stripeTest: FormGroup;

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

  ngOnInit() {
    this.stripe = this.stripeFactory.create('***your-stripe-publishable key***');
    this.stripeTest = this.fb.group({
      name: ['', [Validators.required]],
    });
  }
  
  createToken(): void {
    const name = this.stripeTest.get('name').value;
    this.stripe.createToken(this.card.element, { name }).subscribe((result) => {
      if (result.token) {
        // Use the token
        console.log(result.token.id);
      } else if (result.error) {
        // Error creating the token
        console.log(result.error.message);
      }
    });
  }
}

Last updated

Was this helpful?