ngx-stripe

repository·main·Indexed 42 days ago

https://github.com/richnologies/ngx-stripe

A comprehensive Angular library for integrating Stripe Elements and payment processing. It provides strongly-typed Angular components and services that wrap StripeJS, enabling secure payment collection. Features include support for the Payment Element, specialized components like StripeCardNumberComponent and StripeCardCvcComponent, and integration with Stripe.js v9 (dahlia).

Tokens
12.3K
Snippets
29
Records
33
Agent score
53%

What's inside ngx-stripe

  1. Update Type Imports for ngx-stripe

    main

    In recent versions of ngx-stripe, the library no longer maintains its own custom types. Instead, it uses official Stripe types.

    Crucial Change: You must now import most types from @stripe/stripe-js instead of ngx-stripe.

    Type Mapping Reference:

    Legacy (ngx-stripe)Active (Import from @stripe/stripe-js)
    OptionsStripeConstructorOptions
    StripeJSStripe
    ElementsOptionsStripeElementsOptions
    ElementStripeElement
    ElementsStripeElements
    PaymentIntentResult{ paymentIntent?: PaymentIntent; error?: StripeError; }
    CardSetupResult{ setupIntent?: SetupIntent; error?: StripeError; }
    TokenResult{ token?: Token; error?: StripeError }
  2. Configure ngx-stripe in a Standalone Application

    main

    For modern Angular applications using standalone components, provide the library using provideNgxStripe() within your application configuration (e.g., in main.ts).

    import { provideNgxStripe } from 'ngx-stripe';
    
    bootstrapApplication(AppComponent, {
      providers: [
        // ... rest of your providers
        provideNgxStripe()
      ]
    });
  3. Migrate to Stripe.js v9 (dahlia) in ngx-stripe

    main

    When upgrading to ngx-stripe versions 19.9+, 20.9+, 21.9+, or 22.9+, you are moving from the legacy Stripe.js clover (v8) to the active dahlia (v9) version.

    Key API Changes:

    • Replace initCheckout with initCheckoutElementsSdk.
    • Replace initEmbeddedCheckout with createEmbeddedCheckoutPage.
    • Removed: createSource and retrieveSource (the Sources API is removed in Stripe.js v9).
    • Peer Dependency: Update @stripe/stripe-js to version ^9.0.0.
    • CDN URL: The underlying Stripe script changes from js.stripe.com/clover/stripe.js to js.stripe.com/dahlia/stripe.js.
    # Update peer dependency
    npm install @stripe/stripe-js@^9.0.0
  4. Configure ngx-stripe in an NgModule-based Application

    main

    For applications using NgModule, import NgxStripeModule.forRoot() into your root module.

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { NgxStripeModule } from 'ngx-stripe';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        NgxStripeModule.forRoot(),
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
  5. Install ngx-stripe and @stripe/stripe-js

    main

    To install the latest active version of ngx-stripe along with its required dependency @stripe/stripe-js, use npm:

    npm install ngx-stripe @stripe/stripe-js

    If you need to install a specific version for an older Angular major version, use the LTS npm tags. For example, to install version 14 LTS:

    npm install ngx-stripe@v14-lts @stripe/stripe-js

    Ensure you choose a version of ngx-stripe that is compatible with your Angular and StripeJS versions. Refer to the compatibility table in the documentation for specific version mappings (e.g., Angular 22 with StripeJS v9 dahlia requires ngx-stripe 22.9.x+).

    $ npm install ngx-stripe @stripe/stripe-js
  6. Use the Payment Element Component to collect payments

    main

    The ngx-stripe-payment component (part of the StripePaymentElementComponent suite) allows you to render Stripe's Payment Element. It must be wrapped within an <ngx-stripe-elements> component which provides the necessary stripe instance and elementsOptions (including the clientSecret).

    Implementation Steps:

    1. Inject Stripe: Use injectStripe(YOUR_PUBLIC_KEY) to get the Stripe instance.
    2. Configure Elements: Define StripeElementsOptions (containing the clientSecret) and StripePaymentElementOptions (for layout customization).
    3. Template Setup: Use <ngx-stripe-elements> as a wrapper and <ngx-stripe-payment> as the child component.
    4. Process Payment: Use the Stripe service (the injected stripe instance) to call methods like confirmPayment, passing the elements from the component's @ViewChild reference.
    <ngx-stripe-elements
      [stripe="stripe"
      [elementsOptions="elementsOptions">
      <ngx-stripe-payment [options="paymentElementOptions" />
    </ngx-stripe-elements>
    // In your component class
    @ViewChild(StripePaymentElementComponent) paymentElement!: StripePaymentElementComponent;
    
    // To confirm payment
    this.stripe.confirmPayment({
      elements: this.paymentElement.elements,
      confirmParams: {
        payment_method_data: {
          billing_details: { /* ... */ }
        }
      },
      redirect: 'if_required'
    }).subscribe(result => { /* handle result */ });
  7. Reference: Stripe Service Method Changes

    main

    The StripeService has been updated to include all new APIs from StripeJS. While most existing methods remain (with type updates), several new methods are available, and some legacy methods are deprecated.

    New Methods Added:

    • redirectToCheckout
    • confirmAuBecsDebitPayment
    • confirmBancontactPayment
    • confirmCardPayment
    • confirmEpsPayment
    • confirmFpxPayment
    • confirmGiropayPayment
    • confirmIdealPayment
    • confirmP24Payment
    • confirmSepaDebitPayment
    • retrievePaymentIntent
    • confirmAuBecsDebitSetup
    • confirmCardSetup
    • confirmSepaDebitSetup
    • retrieveSetupIntent

    Deprecated Methods:

    • handleCardPayment
    • confirmPaymentIntent
    • handleCardSetup
    • confirmSetupIntent
    • handleFpxPayment

    Note: Deprecated functions will remain in the service as long as they are part of the official Stripe API.

  8. Reference: Stripe Element Components and Selectors

    main

    The library has expanded support beyond the basic CardElement to include a wide variety of specialized Stripe Elements. Use the following selectors in your Angular templates to implement specific payment inputs.

    <!-- Card Elements -->
    <ngx-stripe-card></ngx-stripe-card>             <!-- CardElement -->
    <ngx-stripe-card-number></ngx-stripe-card-number> <!-- CardNumberElement -->
    <ngx-stripe-card-expiry></ngx-stripe-card-expiry>   <!-- CardExpiryElement -->
    <ngx-stripe-card-cvc></ngx-stripe-card-cvc>       <!-- CardCvcElement -->
    
    <!-- Payment Methods & Specialized Elements -->
    <ngx-stripe-payment-request-button></ngx-stripe-payment-request-button> <!-- PaymentRequestButtonElement -->
    <ngx-stripe-au-bank-account></ngx-stripe-au-bank-account> <!-- AuBankAccountElement -->
    <ngx-stripe-iban></ngx-stripe-iban>             <!-- IbanElement -->
    <ngx-stripe-ideal-bank></ngx-stripe-ideal-bank> <!-- IdealBankElement -->
    <ngx-stripe-fpx-bank></ngx-stripe-fpx-bank>     <!-- FpxBankElement -->
  9. Display a loading template with StripeCardComponent

    main

    You can show a custom loading state while the Stripe Card Element is being initialized by providing a template via the NgxStripeElementLoadingTemplateDirective. The component will display this template as long as its internal state is not 'ready'.

    To use this, place a <ng-template> inside the component and mark it with the directive.

    <ngx-stripe-card [stripe]="stripe">
      <ng-template ngxStripeElementLoadingTemplate>
        <p>Loading payment field...</p>
      </ng-template>
    </ngx-stripe-card>
  10. Initialize Stripe Elements with elements()

    main

    To use Stripe Elements (the UI components for collecting payment information), call the elements() method. This method returns an Observable<StripeElements>. It accepts several types of configuration options:

    • StripeElementsOptionsClientSecret: Options including a clientSecret.
    • StripeElementsOptionsMode: Options defining the mode (e.g., payment or setup).
    • StripeElementsOptions: Standard Stripe Elements configuration.

    Example usage:

    this.stripeService.elements({ clientSecret: '...' }).subscribe(elements => {
      // Use elements to mount components
    });
  11. Use the StripeCardExpiryComponent

    main

    The StripeCardExpiryComponent provides a wrapper for the Stripe Card Expiry Element. It must be used within a parent that provides Stripe elements context, specifically either a StripeCardGroupDirective or a StripeElementsDirective.

    Inputs

    • options: A partial configuration object of type StripeCardExpiryElementOptions to customize the element's appearance and behavior.
    • containerClass: A string used to apply custom CSS classes to the element container.

    Outputs

    • load: Emits the underlying StripeCardExpiryElement once it has been initialized.
    • change: Emits a StripeCardExpiryElementChangeEvent when the expiry value changes.
    • ready: Emits when the element is ready to be used.
    • focus: Emits when the element receives focus.
    • blur: Emits when the element loses focus.
    • escape: Emits when the escape key is pressed while the element is focused.

    Loading State

    You can provide a custom loading template by using the NgxStripeElementLoadingTemplateDirective as a content child. This template will be displayed while the element is being prepared by the StripeCardGroupDirective.

    <ngx-stripe-card-expiry
      [options="{ placeholder: 'MM / YY' }"
      (change)="$event"
      (ready)="onReady()">
    </ngx-stripe-card-expiry>
  12. Use StripeServiceInterface to interact with StripeJS

    main

    The StripeServiceInterface is the primary interface for interacting with StripeJS within the ngx-stripe library. It provides an Angular-friendly, Observable-based wrapper around the core Stripe functionality.

    Key capabilities include:

    • Instance Management: Access the underlying Stripe instance via getInstance().
    • Elements API: Initialize and manage Stripe Elements via elements().
    • Payment Confirmation: Confirm various payment methods (Card, PayPal, Klarna, etc.) using confirmPayment() or specific method calls like confirmCardPayment().
    • Setup Confirmation: Confirm setup intents for saving payment methods via confirmSetup() or specific methods like confirmCardSetup().
    • Token & Payment Method Creation: Create tokens or payment methods using createToken() and createPaymentMethod().
    • Order Processing: Handle complex order flows with processOrder().
    • Specialized Flows: Support for Financial Connections, Identity verification, and Embedded Checkout.