# 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**.

{% hint style="info" %}
You need to pass the stripe instance you create with Factory to the **ngx-stripe-card** component, or any other HTML element
{% endhint %}

{% hint style="danger" %}
Don't use the **StripeService** when you work with **StripeFactory**, use your own instance. Check in the example the function **createToken**. We call createToken on the stripe instance, not the normal **StripeService**.

**StripeService** only works with the public key you pass in the **forRoot**. If you call **forRoot** with no key, the **StripeService** will not work at all
{% endhint %}

{% tabs %}
{% tab title="stripe-test.component.ts" %}

```typescript
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);
      }
    });
  }
}
```

{% endtab %}

{% tab title="stripe-test.component.html" %}

```markup
<h2>Create Token Example</h2>
<ngx-stripe-card [stripe]="stripe"></ngx-stripe-card>
<button type="submit" (click)="createToken()">
  CREATE TOKEN
</button>
```

{% endtab %}

{% tab title="app.module.ts" %}

```typescript
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 { }
```

{% endtab %}
{% endtabs %}
