### Create Setup Intent for Future Payments with Ngx-Stripe
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
This snippet demonstrates how to use Setup Intents with ngx-stripe in an Angular component to save payment methods for future use without immediate charging. It requires Angular, ngx-stripe, and @angular/common/http. The component fetches a client secret from a backend API and then uses the StripePaymentElementComponent to confirm the setup.
```typescript
import { Component, ViewChild, inject } from '@angular/core';
import { StripePaymentElementComponent, injectStripe } from 'ngx-stripe';
import { HttpClient } from '@angular/common/http';
import { StripeElementsOptions } from '@stripe/stripe-js';
@Component({
selector: 'app-save-card',
standalone: true,
imports: [StripePaymentElementComponent],
template: `
@if (elementsOptions.clientSecret) {
}
`
})
export class SaveCardComponent {
@ViewChild(StripePaymentElementComponent) paymentElement!: StripePaymentElementComponent;
private http = inject(HttpClient);
stripe = injectStripe('pk_test_your_publishable_key');
elementsOptions: StripeElementsOptions = {
locale: 'en',
clientSecret: '' // Will be set from backend
};
ngOnInit() {
// Create a SetupIntent on your backend
this.http.post<{ clientSecret: string }>('/api/create-setup-intent', {
customer: 'cus_xxx'
}).subscribe(response => {
this.elementsOptions = {
...this.elementsOptions,
clientSecret: response.clientSecret
};
});
}
saveCard() {
this.stripe.confirmSetup({
elements: this.paymentElement.elements,
confirmParams: {
return_url: 'https://yoursite.com/setup-complete'
},
redirect: 'if_required'
}).subscribe(result => {
if (result.error) {
console.error('Setup failed:', result.error.message);
} else if (result.setupIntent?.status === 'succeeded') {
console.log('Payment method saved!');
console.log('Payment Method ID:', result.setupIntent.payment_method);
}
});
}
}
```
--------------------------------
### Install ngx-stripe and Stripe.js
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
Installs the ngx-stripe library and the official Stripe.js types package using npm. This is the first step to integrating Stripe into your Angular application.
```bash
npm install ngx-stripe @stripe/stripe-js
```
--------------------------------
### Install ngx-stripe and @stripe/stripe-js
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe/README.md
Installs the latest active version of ngx-stripe and the @stripe/stripe-js package. This is the standard installation command for new projects.
```bash
$ npm install ngx-stripe @stripe/stripe-js
```
--------------------------------
### Card Group as a Directive Example in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Provides an example of implementing the Card Group functionality as a directive within an Angular application. This allows for a more declarative approach to managing grouped card input fields.
```html
```
--------------------------------
### Card Group as a Component Example in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Demonstrates using the Card Group functionality as a component in an Angular application. This offers an alternative, component-based approach to integrating grouped card input fields.
```html
```
--------------------------------
### Mount Single Card Element in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Demonstrates mounting a single Card Element component within an Angular application to collect payment information and create a token. This is a basic setup for integrating Stripe's card input.
```html
```
--------------------------------
### Angular Integration of Stripe Express Checkout Element
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/express-checkout/express-checkout.component.html
Example demonstrating the basic integration of the Express Checkout Element in an Angular component using ngx-stripe. This snippet shows how to import the component and potentially bind to its outputs.
```typescript
import { Component } from '@angular/core';
import {
StripeExpressCheckoutComponent,
StripeExpressCheckoutElementOptions
} from 'ngx-stripe';
@Component({
selector: 'app-express-checkout',
template: '',
standalone: true,
imports: [StripeExpressCheckoutComponent]
})
export class ExpressCheckoutComponent {
checkoutOptions: StripeExpressCheckoutElementOptions = {
// Add your Express Checkout Element options here
// For example:
// paymentMethodTypes: ['link', 'card'],
};
// Example event handlers (implement actual logic)
onLoad(element: any) { console.log('Express Checkout Element loaded:', element); }
onCancel() { console.log('Express Checkout cancelled'); }
onConfirm(event: any) { console.log('Express Checkout confirmed:', event); }
onShippingAddressChange(event: any) { console.log('Shipping address changed:', event); }
onShippingRateChange(event: any) { console.log('Shipping rate changed:', event); }
}
```
--------------------------------
### StripeFactoryService: Manage Multiple Stripe Accounts in Angular
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
Illustrates how to use StripeFactoryService in Angular to create and manage multiple Stripe instances, each associated with a different publishable key. This is useful for applications supporting multiple Stripe accounts or Connect platforms. The example shows confirming card payments using distinct Stripe accounts.
```typescript
import { Component, inject } from '@angular/core';
import { StripeFactoryService } from 'ngx-stripe';
@Component({
selector: 'app-multi-account',
template: `
`,
standalone: true
})
export class MultiAccountComponent {
private stripeFactory = inject(StripeFactoryService);
payWithMainAccount() {
const mainStripe = this.stripeFactory.create('pk_test_main_account_key');
mainStripe.confirmCardPayment('pi_xxx_secret_xxx', {
payment_method: 'pm_xxx'
}).subscribe(result => {
console.log('Main account payment:', result);
});
}
payWithConnectAccount() {
const connectStripe = this.stripeFactory.create('pk_test_platform_key', {
stripeAccount: 'acct_connected_account_id'
});
connectStripe.confirmCardPayment('pi_xxx_secret_xxx', {
payment_method: 'pm_xxx'
}).subscribe(result => {
console.log('Connect account payment:', result);
});
}
}
```
--------------------------------
### Install Specific ngx-stripe Version (LTS)
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe/README.md
Installs a specific Long-Term Support (LTS) version of ngx-stripe, such as v14-lts, along with @stripe/stripe-js. This is useful for maintaining compatibility with older Angular versions.
```bash
$ npm install ngx-stripe@v14-lts @stripe/stripe-js
```
--------------------------------
### Collect Card Payments with Payment Element in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/payment-element/payment-element.component.html
Example demonstrating how to collect card payments using the Payment Element within an Angular application via ngx-stripe. It utilizes the Stripe Elements Directive for integration.
```typescript
import {
StripePaymentElementComponent,
StripeElementsDirective,
StripeService
} from 'ngx-stripe';
// ... component code ...
@ViewChild(StripePaymentElementComponent) paymentElementRef: StripePaymentElementComponent;
async ngOnInit() {
this.stripeService.elements(this.elementsOptions).subscribe(elements => {
this.elements = elements;
// You can now use this.elements to create or manage Stripe Elements
});
}
async pay() {
if (!this.paymentElementRef?.element) {
return;
}
const { paymentIntent, error } = await this.stripeService.confirmPaymentIntent(this.clientSecret, {
payment_method: {
card: this.paymentElementRef.element
}
});
if (error) {
// Handle error
} else {
// Handle successful payment
}
}
```
--------------------------------
### Fetching Updates for Payment Element
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/payment-element/payment-element.component.html
Demonstrates the usage of the `fetchUpdates` method to synchronize the Payment Element with the latest data from a PaymentIntent or SetupIntent.
```typescript
import { StripePaymentElementComponent } from 'ngx-stripe';
// Assuming you have access to the StripePaymentElementComponent instance
// For example, via @ViewChild
// @ViewChild(StripePaymentElementComponent) paymentElementRef: StripePaymentElementComponent;
async function refreshPaymentIntentData(paymentElementRef: StripePaymentElementComponent) {
try {
await paymentElementRef.fetchUpdates();
console.log('Payment Element updated successfully.');
} catch (error) {
console.error('Error fetching updates:', error);
}
}
```
--------------------------------
### Configure StripeIssuingCardCvcDisplayComponent in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/issuing/issuing.component.html
Details the setup for the StripeIssuingCardCvcDisplayComponent, which securely displays the CVC of Issuing cards. It supports customization through CSS classes and Stripe-specific options for integration.
```typescript
// Example usage in an Angular component template:
//
//
// In your component's TypeScript file:
// import { Component } from '@angular/core';
// import { StripeIssuingCardCvcDisplayComponent, StripeIssuingCardCvcDisplayElement } from 'ngx-stripe';
// @Component({
// selector: 'app-cvc-display',
// templateUrl: './cvc-display.component.html',
// styleUrls: ['./cvc-display.component.css']
// })
// export class CvcDisplayComponent {
// cvcOptions = {}; // Configure your StripeIssuingCardCvcDisplayElementOptions here
// onCvcLoad(element: StripeIssuingCardCvcDisplayElement) {
// console.log('Card CVC Element loaded:', element);
// }
// }
```
--------------------------------
### Configure ngx-stripe for Standalone Apps
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
Provides global NgxStripe providers for standalone Angular applications using `bootstrapApplication`. This is the recommended configuration method for Angular 14+.
```typescript
import { bootstrapApplication } from '@angular/platform-browser';
import { provideNgxStripe } from 'ngx-stripe';
import { AppComponent } from './app.component';
bootstrapApplication(AppComponent, {
providers: [
provideNgxStripe('pk_test_your_publishable_key')
]
});
```
--------------------------------
### Updating Address Element Options
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/address/address.component.html
Demonstrates how to update the configuration options of an existing Stripe Address Element instance using the `update` method. This allows for dynamic changes to the element's behavior after initialization.
```typescript
addressElement.update({ country: 'US' });
```
--------------------------------
### Integrate Stripe Payment Element in Angular
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
This snippet demonstrates how to use the StripePaymentElementComponent in an Angular application. It includes setting up the form, initializing the Stripe elements with client secret and options, and handling payment confirmation. Dependencies include Angular's ReactiveFormsModule, ngx-stripe, and @stripe/stripe-js.
```typescript
import { Component, ViewChild, signal, inject } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
import { StripePaymentElementComponent, injectStripe } from 'ngx-stripe';
import { StripeElementsOptions, StripePaymentElementOptions } from '@stripe/stripe-js';
@Component({
selector: 'app-checkout',
standalone: true,
imports: [ReactiveFormsModule, StripePaymentElementComponent],
template: `
`
})
export class CheckoutComponent {
@ViewChild(StripePaymentElementComponent) paymentElement!: StripePaymentElementComponent;
private fb = inject(FormBuilder);
stripe = injectStripe('pk_test_your_publishable_key');
paying = signal(false);
paymentForm = this.fb.group({
name: ['John Doe', Validators.required],
email: ['john@example.com', [Validators.required, Validators.email]]
});
elementsOptions: StripeElementsOptions = {
locale: 'en',
clientSecret: 'pi_xxx_secret_xxx', // Get from your backend
appearance: { theme: 'stripe' }
};
paymentElementOptions: StripePaymentElementOptions = {
layout: { type: 'tabs', defaultCollapsed: false }
};
onPaymentChange(event: any) {
console.log('Payment element changed:', event);
}
pay() {
if (this.paymentForm.invalid || this.paying()) return;
this.paying.set(true);
const { name, email } = this.paymentForm.value;
this.stripe.confirmPayment({
elements: this.paymentElement.elements,
confirmParams: {
payment_method_data: {
billing_details: { name, email }
}
},
redirect: 'if_required'
}).subscribe(result => {
this.paying.set(false);
if (result.error) {
console.error('Payment failed:', result.error.message);
} else if (result.paymentIntent?.status === 'succeeded') {
console.log('Payment successful!');
}
});
}
}
```
--------------------------------
### Updating Payment Element Options
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/payment-element/payment-element.component.html
Illustrates how to imperatively update the configuration options of an existing Payment Element instance using the `update` method.
```typescript
import { StripePaymentElementComponent } from 'ngx-stripe';
import { StripePaymentElementOptions } from '@stripe/stripe-js';
// Assuming you have access to the StripePaymentElementComponent instance
// For example, via @ViewChild
// @ViewChild(StripePaymentElementComponent) paymentElementRef: StripePaymentElementComponent;
function changePaymentElementConfiguration(paymentElementRef: StripePaymentElementComponent) {
const newOptions: StripePaymentElementOptions = {
// New configuration options
// e.g., layout: { type: 'accordion' }
};
const updatedElement = paymentElementRef.update(newOptions);
console.log('Payment Element updated:', updatedElement);
}
```
--------------------------------
### StripeService Methods: Create, Retrieve, Confirm Payments in Angular
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
Demonstrates various StripeService methods for handling payments within an Angular component. It covers creating payment methods, retrieving PaymentIntents, confirming card payments, handling next actions like 3D Secure, creating tokens from card data, verifying identity, and initializing embedded checkouts. This service returns RxJS Observables for reactive integration.
```typescript
import { Component, inject } from '@angular/core';
import { StripeService } from 'ngx-stripe';
@Component({
selector: 'app-stripe-methods',
template: ``,
standalone: true
})
export class StripeMethodsComponent {
private stripeService = inject(StripeService);
testMethods() {
// Create a payment method
this.stripeService.createPaymentMethod({
type: 'card',
card: { token: 'tok_visa' },
billing_details: { name: 'John Doe' }
}).subscribe(result => {
if (result.paymentMethod) {
console.log('PaymentMethod:', result.paymentMethod.id);
}
});
// Retrieve a PaymentIntent
this.stripeService.retrievePaymentIntent('pi_xxx_secret_xxx')
.subscribe(result => {
console.log('PaymentIntent status:', result.paymentIntent?.status);
});
// Confirm card payment directly
this.stripeService.confirmCardPayment('pi_xxx_secret_xxx', {
payment_method: 'pm_xxx'
}).subscribe(result => {
if (result.error) {
console.error(result.error.message);
} else {
console.log('Payment status:', result.paymentIntent?.status);
}
});
// Handle next action (3D Secure, etc.)
this.stripeService.handleNextAction({ clientSecret: 'pi_xxx_secret_xxx' })
.subscribe(result => {
console.log('Next action result:', result);
});
// Create a token from card data
this.stripeService.createToken('card', {
name: 'John Doe',
address_line1: '123 Main St',
address_city: 'San Francisco',
address_state: 'CA',
address_zip: '94102',
address_country: 'US'
}).subscribe(result => {
if (result.token) {
console.log('Token:', result.token.id);
}
});
// Verify identity
this.stripeService.verifyIdentity('vs_xxx')
.subscribe(result => {
console.log('Verification:', result);
});
// Initialize embedded checkout
this.stripeService.initEmbeddedCheckout({
fetchClientSecret: async () => {
// Fetch from your server
const response = await fetch('/create-checkout-session');
const { clientSecret } = await response.json();
return clientSecret;
}
}).subscribe(checkout => {
checkout.mount('#checkout-container');
});
}
}
```
--------------------------------
### Link Authentication Component in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/link-authentication/link-authentication.component.html
Demonstrates the basic usage of the StripeLinkAuthenticationComponent in an Angular application. It shows how to import the component and use its selector in a template.
```html
```
--------------------------------
### Import NgxStripeModule in Angular Module
Source: https://github.com/richnologies/ngx-stripe/blob/main/README.md
This snippet demonstrates how to import the `NgxStripeModule` into an Angular application that uses NgModules. It shows the necessary import statement and how to include `NgxStripeModule.forRoot()` within the `imports` array of the application's root module.
```typescript
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// Import the library
import { NgxStripeModule } from 'ngx-stripe';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
// ... rest of your imports
NgxStripeModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
```
--------------------------------
### Payment Element Component Implementation (TypeScript)
Source: https://github.com/richnologies/ngx-stripe/blob/main/README.md
This TypeScript code implements the CheckoutFormComponent using Angular. It sets up a reactive form for collecting billing details, configures Stripe Elements and Payment Element options, injects the Stripe service, and handles the payment confirmation process. The `pay` method uses `stripe.confirmPayment` to process the payment and manages the UI state and user feedback.
```typescript
import { Component, inject, signal, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import {
injectStripe,
StripePaymentElementComponent
} from 'ngx-stripe';
import {
StripeElementsOptions,
StripePaymentElementOptions
} from '@stripe/stripe-js';
@Component({
selector: 'ngstr-checkout-form',
templateUrl: './payment-element.component.html',
standalone: true,
imports: [
ReactiveFormsModule,
MatInputModule,
StripePaymentElementComponent
]
})
export class CheckoutFormComponent {
@ViewChild(StripePaymentElementComponent)
paymentElement!: StripePaymentElementComponent;
private readonly fb = inject(UntypedFormBuilder);
paymentElementForm = this.fb.group({
name: ['John Doe', [Validators.required]],
email: ['support@ngx-stripe.dev', [Validators.required]],
address: [''],
zipcode: [''],
city: [''],
amount: [2500, [Validators.required, Validators.pattern(/\d+/)]]
});
elementsOptions: StripeElementsOptions = {
locale: 'en',
clientSecret: '{{YOUR_CLIENT_SECRET}}'
appearance: {
theme: 'flat'
}
};
paymentElementOptions: StripePaymentElementOptions = {
layout: {
type: 'tabs',
defaultCollapsed: false,
radios: false,
spacedAccordionItems: false
}
};
// Replace with your own public key
stripe = injectStripe('{{YOUR_PUBLIC_KEY}}');
paying = signal(false);
pay() {
if (this.paying() || this.paymentElementForm.invalid) return;
this.paying.set(true);
const {
name,
email,
address,
zipcode,
city
} = this.checkoutForm.getRawValue();
this.stripe
.confirmPayment({
elements: this.paymentElement.elements,
confirmParams: {
payment_method_data: {
billing_details: {
name: name as string,
email: email as string,
address: {
line1: address as string,
postal_code: zipcode as string,
city: city as string
}
}
}
},
redirect: 'if_required'
})
.subscribe(result => {
this.paying.set(false);
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
alert({ success: false, error: result.error.message });
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
// Show a success message to your customer
alert({ success: true });
}
}
});
}
}
```
--------------------------------
### Fetching Updates for Payment Element
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/elements/elements.component.html
The `fetchUpdates` method is used with the Payment Element to retrieve the latest information from the associated PaymentIntent or SetupIntent. This allows you to reflect any changes in the Payment Element UI.
```typescript
import { StripeElements } from 'ngx-stripe';
// Assuming 'elements' is an instance of StripeElements obtained from the directive
async function updatePaymentElement(elements: StripeElements) {
try {
await elements.fetchUpdates();
console.log('Payment Element updates fetched successfully.');
} catch (error) {
console.error('Error fetching Payment Element updates:', error);
}
}
```
--------------------------------
### Link Authentication Element Options
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/link-authentication/link-authentication.component.html
Shows how to configure the Link Authentication Element using the `StripeLinkAuthenticationElementOptions` interface. This includes setting default values for the email address.
```typescript
import { Component } from '@angular/core';
import {
StripeLinkAuthenticationComponent,
StripeLinkAuthenticationElementOptions,
} from 'ngx-stripe';
@Component({
selector: 'app-checkout',
templateUrl: './checkout.component.html',
standalone: true,
imports: [StripeLinkAuthenticationComponent],
})
export class CheckoutComponent {
linkAuthenticationOptions: StripeLinkAuthenticationElementOptions = {
defaultValues: {
email: 'test@example.com',
},
};
}
```
--------------------------------
### Collapsing the Payment Element
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/payment-element/payment-element.component.html
Shows how to use the `collapse` method, which is exclusive to the Payment Element component, to hide parts of the element and display payment method tabs.
```typescript
import { StripePaymentElementComponent } from 'ngx-stripe';
// Assuming you have access to the StripePaymentElementComponent instance
// For example, via @ViewChild
// @ViewChild(StripePaymentElementComponent) paymentElementRef: StripePaymentElementComponent;
function minimizePaymentElement(paymentElementRef: StripePaymentElementComponent) {
const collapsedElement = paymentElementRef.collapse();
console.log('Payment Element collapsed:', collapsedElement);
}
```
--------------------------------
### Provide ngx-stripe in Standalone Angular App
Source: https://github.com/richnologies/ngx-stripe/blob/main/README.md
This snippet shows how to provide the ngx-stripe service when using standalone components in Angular. It imports `provideNgxStripe` and includes it in the application's bootstrap providers.
```typescript
import { provideNgxStripe } from 'ngx-stripe';
bootstrapApplication(AppComponent, {
providers: [
// ... rest of your providers
provideNgxStripe()
]
});
```
--------------------------------
### Angular Express Checkout Component Implementation
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
This Angular component demonstrates how to use the `StripeExpressCheckoutComponent` from `ngx-stripe`. It configures various options for the express checkout, including button types, themes, layout, and payment method visibility. It also includes event handlers for component readiness, button clicks, payment confirmation, cancellation, and shipping address changes.
```typescript
import { Component, ViewChild, inject } from '@angular/core';
import { StripeExpressCheckoutComponent, injectStripe } from 'ngx-stripe';
import {
StripeExpressCheckoutElementOptions,
StripeExpressCheckoutElementConfirmEvent,
StripeExpressCheckoutElementClickEvent
} from '@stripe/stripe-js';
@Component({
selector: 'app-express-checkout',
standalone: true,
imports: [StripeExpressCheckoutComponent],
template: `
`
})
export class ExpressCheckoutComponent {
@ViewChild(StripeExpressCheckoutComponent) expressCheckout!: StripeExpressCheckoutComponent;
stripe = injectStripe('pk_test_your_publishable_key');
elementsOptions = {
mode: 'payment' as const,
amount: 2500,
currency: 'usd',
locale: 'en' as const
};
expressCheckoutOptions: StripeExpressCheckoutElementOptions = {
buttonType: {
applePay: 'buy',
googlePay: 'buy'
},
buttonTheme: {
applePay: 'black',
googlePay: 'black'
},
layout: { maxColumns: 2, maxRows: 1 },
paymentMethods: {
applePay: 'always',
googlePay: 'always',
link: 'auto'
}
};
onReady(event: any) {
console.log('Express Checkout ready:', event.availablePaymentMethods);
}
onClick(event: StripeExpressCheckoutElementClickEvent) {
console.log('Button clicked:', event.expressPaymentType);
// Resolve with line items and shipping options
event.resolve({
lineItems: [
{ name: 'Product', amount: 2500 }
],
shippingRates: [
{ id: 'standard', displayName: 'Standard Shipping', amount: 500 }
]
});
}
onConfirm(event: StripeExpressCheckoutElementConfirmEvent) {
console.log('Payment confirmed:', event);
// Process the payment on your server
// event.expressPaymentType contains 'apple_pay', 'google_pay', or 'link'
// event.billingDetails contains customer billing info
}
onCancel() {
console.log('Payment cancelled');
}
onShippingAddressChange(event: any) {
console.log('Shipping address changed:', event.address);
// Update shipping options based on address
event.resolve({
shippingRates: [
{ id: 'standard', displayName: 'Standard Shipping', amount: 500 }
]
});
}
}
```
--------------------------------
### Importing Card Element Components in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Shows the necessary imports for using various Stripe Card Element components within an Angular project. This includes `StripeCardComponent`, `StripeCardNumberComponent`, `StripeCardExpiryComponent`, and `StripeCardCvcComponent`.
```typescript
import {
StripeCardComponent,
StripeCardNumberComponent,
StripeCardExpiryComponent,
StripeCardCvcComponent
} from 'ngx-stripe'
```
--------------------------------
### Handling Link Authentication Events in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/link-authentication/link-authentication.component.html
Illustrates how to handle the 'change' and 'load' events emitted by the StripeLinkAuthenticationComponent. The 'change' event provides the email details, while the 'load' event emits the StripeLinkAuthenticationElement instance.
```typescript
import { Component } from '@angular/core';
import {
StripeLinkAuthenticationComponent,
StripeLinkAuthenticationElement,
StripeLinkAuthenticationElementChangeEvent,
} from 'ngx-stripe';
@Component({
selector: 'app-checkout',
templateUrl: './checkout.component.html',
standalone: true,
imports: [StripeLinkAuthenticationComponent],
})
export class CheckoutComponent {
linkAuthenticationOptions: any;
customerEmail: string | undefined;
onLinkAuthenticationChange(event: StripeLinkAuthenticationElementChangeEvent) {
if (event.complete) {
this.customerEmail = event.value.email;
console.log('Customer email:', this.customerEmail);
}
}
onLinkAuthenticationLoad(element: StripeLinkAuthenticationElement) {
console.log('Link Authentication Element loaded:', element);
}
}
```
--------------------------------
### Inject Stripe Instance in Angular Component
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
A helper function to create a Stripe instance using Angular's dependency injection. It allows injecting Stripe into components without global key configuration, supporting multiple accounts or dynamic keys.
```typescript
import { Component, inject } from '@angular/core';
import { injectStripe } from 'ngx-stripe';
@Component({
selector: 'app-payment',
template: ``,
standalone: true
})
export class PaymentComponent {
// Use the globally configured key
stripe = injectStripe();
// Or provide a specific key
// stripe = injectStripe('pk_test_specific_key');
}
```
--------------------------------
### StripeCardComponent API in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Details the properties and outputs of the `StripeCardComponent` in ngx-stripe. It covers inputs like `containerClass` and `options`, and outputs such as `load`, `blur`, `change`, `focus`, `ready`, and `escape`.
```typescript
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { StripeCardElement, StripeCardElementOptions, StripeCardElementChangeEvent, StripeElementsOptions, StripeServiceInterface } from '@stripe/stripe-js';
@Component({
selector: 'ngx-stripe-card',
template: ''
})
export class StripeCardComponent {
@Input() containerClass?: string;
@Input() options?: StripeCardElementOptions;
@Input() elementsOptions?: StripeElementsOptions; // DEPRECATED
@Input() stripe?: StripeServiceInterface; // DEPRECATED
@Output() load = new EventEmitter();
@Output() blur = new EventEmitter();
@Output() change = new EventEmitter();
@Output() focus = new EventEmitter();
@Output() ready = new EventEmitter();
@Output() escape = new EventEmitter();
element: StripeCardElement;
update(options: StripeCardElementOptions): Promise;
}
```
--------------------------------
### StripePaymentElementComponent API
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/payment-element/payment-element.component.html
API reference for the StripePaymentElementComponent, including its input properties, output events, and methods for managing the Payment Element.
```APIDOC
## StripePaymentElementComponent
**Selector:** `ngx-stripe-payment`
### Description
The `StripePaymentElementComponent` is an Angular component that wraps the Stripe Payment Element, allowing for secure and streamlined collection of payment details within an Angular application using ngx-stripe.
### Properties
#### Input Properties
- **containerClass** (`string`) - Optional - A CSS class to add to the container element.
- **options** (`StripePaymentElementOptions`) - Optional - An object containing the configuration options for the Payment Element. Refer to Stripe documentation for details.
- **elementsOptions** (`StripeElementsOptions`) - Deprecated - Use `elements` instead. An object containing configuration options for the Stripe Elements instance.
- **stripe** (`StripeServiceInterface`) - Deprecated - Use `elements` instead. The StripeServiceInterface instance for creating the Stripe Elements instance.
- **appearance** (`Appearance`) - Deprecated - Use `elementsOptions` instead. The appearance of the element.
- **clientSecret** (`string`) - Deprecated - Use `elementsOptions` instead. The client secret of the intent.
#### Output Events
- **load** (`EventEmitter`) - Custom (ngx-stripe only): Emitted when the Angular Component is ready and emits the StripePaymentElement Web Element instance.
- **blur** (`EventEmitter`) - Triggered when the Element loses focus.
- **change** (`EventEmitter`) - The change event is triggered when the Element's value changes. The event payload contains certain keys and Element-specific keys.
- **focus** (`EventEmitter`) - Triggered when the Element gains focus.
- **ready** (`EventEmitter`) - Triggered when the Element is fully rendered and can accept `element.focus()` calls.
- **escape** (`EventEmitter`) - Triggered when the escape key is pressed within an Element.
- **loaderror** (`EventEmitter`) - Triggered when the Element fails to load.
### Methods
- **fetchUpdates()**: Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements and reflects these updates in the Payment Element.
- **update(options: StripePaymentElementOptions): StripePaymentElement**: Updates the options the Payment Element was initialized with. Updates are merged into the existing configuration.
- **collapse(): StripePaymentElement**: Collapses the Payment Element into a row of payment method tabs. This method is exclusively available for the Payment Element component.
```
--------------------------------
### Importing StripeAddressComponent in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/address/address.component.html
This snippet shows how to import the StripeAddressComponent from the ngx-stripe library in an Angular application. This is the primary step to use the Address Element in your project.
```typescript
import { StripeAddressComponent } from 'ngx-stripe';
```
--------------------------------
### Handling Express Checkout Events in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/express-checkout/express-checkout.component.html
Illustrates how to handle various events emitted by the Express Checkout Element in an Angular component. This includes 'clicked', 'confirm', 'cancel', 'shippingaddresschange', and 'shippingratechange'.
```typescript
import { Component, Output, EventEmitter } from '@angular/core';
import {
StripeExpressCheckoutComponent,
StripeExpressCheckoutElementOptions,
StripeExpressCheckoutElementConfirmEvent,
StripeExpressCheckoutElementShippingAddressChangeEvent,
StripeExpressCheckoutElementShippingRateChangeEvent
} from 'ngx-stripe';
@Component({
selector: 'app-checkout-handler',
template: '',
standalone: true,
imports: [StripeExpressCheckoutComponent]
})
export class CheckoutHandlerComponent {
checkoutOptions: StripeExpressCheckoutElementOptions = {};
@Output() paymentConfirmed = new EventEmitter();
@Output() orderCancelled = new EventEmitter();
onLoad(element: any) {
console.log('Express Checkout Element loaded:', element);
}
onClick() {
console.log('Express Checkout button clicked.');
// Logic to prepare payment interface
}
onConfirm(event: StripeExpressCheckoutElementConfirmEvent) {
console.log('Payment confirmed:', event);
this.paymentConfirmed.emit(event);
// Trigger payment confirmation logic
}
onCancel() {
console.log('Express Checkout cancelled.');
this.orderCancelled.emit();
// Handle order cancellation, potentially refunding payment if already created
}
onShippingAddressChange(event: StripeExpressCheckoutElementShippingAddressChangeEvent) {
console.log('Shipping address changed:', event);
// Update shipping options based on new address
}
onShippingRateChange(event: StripeExpressCheckoutElementShippingRateChangeEvent) {
console.log('Shipping rate changed:', event);
// Update order total based on new shipping rate
}
}
```
--------------------------------
### Using Payment Element Without an Elements Instance (Deprecated)
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/elements/elements.component.html
While recommended to use an Elements instance, certain elements like the Payment Element can be created directly by passing their options. This approach is maintained for backward compatibility but is considered deprecated.
```typescript
import { Stripe, StripePaymentElementOptions } from '@stripe/stripe-js';
// Assume 'stripe' is an initialized Stripe instance
async function createPaymentElementDirectly(stripe: Stripe) {
const paymentElementOptions: StripePaymentElementOptions = {
// Payment Element specific options
};
try {
const element = await stripe.elements().create('payment', paymentElementOptions);
// Mount the element to a DOM container
// element.mount('#payment-element-container');
console.log('Payment Element created directly:', element);
} catch (error) {
console.error('Error creating Payment Element directly:', error);
}
}
// Note: This method is deprecated. Prefer using StripeElementsDirective.
```
--------------------------------
### StripeCardNumberComponent API in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Outlines the properties and outputs for the `StripeCardNumberComponent` in ngx-stripe. Key inputs include `containerClass` and `options`, while outputs cover `load`, `blur`, `change`, `focus`, `ready`, and `escape`.
```typescript
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { StripeCardNumberElement, StripeCardNumberElementOptions, StripeCardNumberElementChangeEvent, StripeElementsOptions, StripeServiceInterface } from '@stripe/stripe-js';
@Component({
selector: 'ngx-stripe-card-number',
template: ''
})
export class StripeCardNumberComponent {
@Input() containerClass?: string;
@Input() options?: StripeCardNumberElementOptions;
@Input() elementsOptions?: StripeElementsOptions; // DEPRECATED
@Input() stripe?: StripeServiceInterface; // DEPRECATED
@Output() load = new EventEmitter();
@Output() blur = new EventEmitter();
@Output() change = new EventEmitter();
@Output() focus = new EventEmitter();
@Output() ready = new EventEmitter();
@Output() escape = new EventEmitter();
element: StripeCardNumberElement;
update(options: StripeCardNumberElementOptions): Promise;
}
```
--------------------------------
### Collect Shipping/Billing Address with TypeScript
Source: https://context7.com/richnologies/ngx-stripe/llms.txt
Shows how to use the StripeAddressComponent for collecting addresses, offering autocomplete and validation. It imports the component and necessary types from ngx-stripe and @stripe/stripe-js, configuring options like mode, allowed countries, and required fields.
```typescript
import { Component, ViewChild, inject } from '@angular/core';
import { StripeAddressComponent, injectStripe } from 'ngx-stripe';
import { StripeAddressElementOptions, StripeAddressElementChangeEvent } from '@stripe/stripe-js';
@Component({
selector: 'app-address-form',
standalone: true,
imports: [StripeAddressComponent],
template: `
{{ addressValue | json }}
`
})
export class AddressFormComponent {
@ViewChild(StripeAddressComponent) addressElement!: StripeAddressComponent;
stripe = injectStripe('pk_test_your_publishable_key');
addressValue: any = null;
addressOptions: StripeAddressElementOptions = {
mode: 'shipping',
allowedCountries: ['US', 'CA', 'GB', 'DE', 'FR'],
blockPoBox: true,
fields: {
phone: 'always'
},
validation: {
phone: { required: 'always' }
},
defaultValues: {
name: 'John Doe',
address: {
line1: '123 Main St',
city: 'San Francisco',
state: 'CA',
postal_code: '94102',
country: 'US'
}
}
};
onAddressChange(event: StripeAddressElementChangeEvent) {
console.log('Address changed:', event);
if (event.complete) {
this.addressValue = event.value;
}
}
onReady() {
console.log('Address element ready');
}
async getAddress() {
const result = await this.addressElement.getValue();
console.log('Current address:', result);
this.addressValue = result.value;
}
}
```
--------------------------------
### StripePaymentElementComponent API Reference
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/payment-element/payment-element.component.html
API details for the StripePaymentElementComponent in ngx-stripe, including input properties for configuration and output events for handling user interactions and component lifecycle.
```typescript
import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { StripePaymentElement, StripePaymentElementChangeEvent, StripePaymentElementOptions, StripeElementsOptions, Appearance } from '@stripe/stripe-js';
import { StripeServiceInterface } from 'ngx-stripe';
@Component({
selector: 'ngx-stripe-payment',
template: ''
})
export class StripePaymentElementComponent {
@Input() containerClass: string;
@Input() options: StripePaymentElementOptions;
@Input() elementsOptions: StripeElementsOptions; // DEPRECATED
@Input() stripe: StripeServiceInterface; // DEPRECATED
@Input() appearance: Appearance; // DEPRECATED
@Input() clientSecret: string; // DEPRECATED
@Output() load = new EventEmitter();
@Output() blur = new EventEmitter();
@Output() change = new EventEmitter();
@Output() focus = new EventEmitter();
@Output() ready = new EventEmitter();
@Output() escape = new EventEmitter();
@Output() loaderror = new EventEmitter();
element: StripePaymentElement;
// Methods
fetchUpdates(): Promise;
update(options: StripePaymentElementOptions): StripePaymentElement;
collapse(): StripePaymentElement;
}
```
--------------------------------
### StripeCardCvcComponent API in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/card-elements/card-elements.component.html
Describes the properties and outputs for the `StripeCardCvcComponent` in ngx-stripe. It features inputs like `containerClass` and `options`, and outputs including `load`, `blur`, `change`, `focus`, `ready`, and `escape`.
```typescript
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { StripeCardCvcElement, StripeCardCvcElementOptions, StripeCardElementChangeEvent, StripeElementsOptions, StripeServiceInterface } from '@stripe/stripe-js';
@Component({
selector: 'ngx-stripe-card-cvc',
template: ''
})
export class StripeCardCvcComponent {
@Input() containerClass?: string;
@Input() options?: StripeCardCvcElementOptions;
@Input() elementsOptions?: StripeElementsOptions; // DEPRECATED
@Input() stripe?: StripeServiceInterface; // DEPRECATED
@Output() load = new EventEmitter();
@Output() blur = new EventEmitter();
@Output() change = new EventEmitter();
@Output() focus = new EventEmitter();
@Output() ready = new EventEmitter();
@Output() escape = new EventEmitter();
element: StripeCardCvcElement;
update(options: StripeCardCvcElementOptions): Promise;
}
```
--------------------------------
### Update StripeIssuingCardNumberDisplayComponent Options
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/issuing/issuing.component.html
Shows how to update the configuration options for an existing StripeIssuingCardNumberDisplayComponent instance. This method allows for dynamic changes to the element's behavior or appearance after initialization.
```typescript
// Assuming you have a reference to the component instance, e.g., cardNumberDisplayComponent
// cardNumberDisplayComponent.update({ /* new options */ });
```
--------------------------------
### Retrieving Address Element Values
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/address/address.component.html
Illustrates how to retrieve and validate the form values from the Address Element using the `getValue` method. This method returns a promise that resolves with the address data or indicates if there were validation errors.
```typescript
const value = await addressElement.getValue();
if (value.complete) {
// Process the address value
}
```
--------------------------------
### Update StripeIssuingCardCvcDisplayComponent Options
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/issuing/issuing.component.html
Explains how to update the configuration options for a StripeIssuingCardCvcDisplayComponent. This allows for dynamic adjustments to the CVC display element after it has been initialized, enhancing flexibility.
```typescript
// Assuming you have a reference to the component instance, e.g., cvcDisplayComponent
// cvcDisplayComponent.update({ /* new options */ });
```
--------------------------------
### Issuing Card Pin Display Element Methods
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/issuing/issuing.component.html
This section details the methods available for interacting with the Issuing Card Pin Display Element.
```APIDOC
## Issuing Card Pin Display Element Methods
### Description
This section describes the methods available for updating the Issuing Card Pin Display Element.
### Method
#### `update(options: StripeIssuingCardPinDisplayElementOptions)`
### Description
Updates the options the Element was initialized with. Updates are merged into the existing configuration.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (StripeIssuingCardPinDisplayElementOptions) - Required - The new options to update the element with.
```
--------------------------------
### Configure StripeIssuingCardNumberDisplayComponent in Angular
Source: https://github.com/richnologies/ngx-stripe/blob/main/projects/ngx-stripe-docs/src/app/docs/issuing/issuing.component.html
Demonstrates how to configure the StripeIssuingCardNumberDisplayComponent in an Angular application. This component allows for the PCI-compliant display of card numbers, accepting configuration options for styling and integration.
```typescript
// Example usage in an Angular component template:
//
//
// In your component's TypeScript file:
// import { Component } from '@angular/core';
// import { StripeIssuingCardNumberDisplayComponent, StripeIssuingCardNumberDisplayElement } from 'ngx-stripe';
// @Component({
// selector: 'app-card-display',
// templateUrl: './card-display.component.html',
// styleUrls: ['./card-display.component.css']
// })
// export class CardDisplayComponent {
// cardOptions = {}; // Configure your StripeIssuingCardNumberDisplayElementOptions here
// onCardNumberLoad(element: StripeIssuingCardNumberDisplayElement) {
// console.log('Card Number Element loaded:', element);
// // You can interact with the element here if needed
// }
// }
```