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
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
stripe-test.component.ts
stripe-test.component.html
app.module.ts
1
import { Component, OnInit, ViewChild } from '@angular/core';
2
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
3
4
import {
5
StripeCardComponent,
6
StripeInstance,
7
StripeFactoryService
8
} from "ngx-stripe";
9
10
@Component({
11
selector: 'app-stripe-test',
12
templateUrl: 'stripe.html'
13
})
14
export class StripeTestComponent implements OnInit {
15
@ViewChild(StripeCardComponent) card: StripeCardComponent;
16
17
stripe: StripeInstance;
18
stripeTest: FormGroup;
19
20
constructor(
21
private fb: FormBuilder,
22
private stripeFactory: StripeFactoryService
23
) {}
24
25
ngOnInit() {
26
this.stripe = this.stripeFactory.create('***your-stripe-publishable key***');
27
this.stripeTest = this.fb.group({
28
name: ['', [Validators.required]],
29
});
30
}
31
32
createToken(): void {
33
const name = this.stripeTest.get('name').value;
34
this.stripe.createToken(this.card.element, { name }).subscribe((result) => {
35
if (result.token) {
36
// Use the token
37
console.log(result.token.id);
38
} else if (result.error) {
39
// Error creating the token
40
console.log(result.error.message);
41
}
42
});
43
}
44
}
Copied!
1
<h2>Create Token Example</h2>
2
<ngx-stripe-card [stripe]="stripe"></ngx-stripe-card>
3
<button type="submit" (click)="createToken()">
4
CREATE TOKEN
5
</button>
Copied!
1
import { BrowserModule } from '@angular/platform-browser';
2
import { NgModule } from '@angular/core';
3
4
import { AppComponent } from './app.component';
5
6
// Import your library
7
import { NgxStripeModule } from 'ngx-stripe';
8
9
@NgModule({
10
declarations: [
11
AppComponent
12
],
13
imports: [
14
BrowserModule,
15
NgxStripeModule.forRoot(),
16
LibraryModule
17
],
18
providers: [],
19
bootstrap: [AppComponent]
20
})
21
export class AppModule { }
Copied!
Last modified 2mo ago
Copy link