boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

使用 Angular 14 实现 Stripe 自定义支付流程


avatar
站长 2025年8月16日 5

使用 Angular 14 实现 Stripe 自定义支付流程

本文将介绍如何在 Angular 14 项目中集成 Stripe 支付,并实现自定义支付流程,避免使用 stripe-ngx 库及其默认弹窗样式。我们将重点讲解如何在 Angular 组件中捕获支付成功事件,避免页面跳转,以及解决使用 Stripe JS checkout 时可能遇到的 clientSecret 错误。

集成 Stripe JS 到 Angular 项目

首先,需要在 Angular 项目中引入 Stripe JS 库。可以通过在 index.html 文件中添加以下代码来实现:

<!DOCTYPE html> <html>   <head>     <script src="https://js.stripe.com/v3/"></script>   </head>   <body>     <app-root></app-root>   </body> </html>

或者,在 angular.json 文件中配置 scripts 数组:

"architect": {   "build": {     "builder": "@angular-devkit/build-angular:browser",     "options": {       "scripts": [         "node_modules/stripe/stripe-js/dist/stripe.js"       ]     }   } }

接下来,在需要使用 Stripe 的 Angular 组件中,注入 Stripe 实例。建议创建一个 Stripe 服务来封装 Stripe 相关逻辑,以便在多个组件中复用。

import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment';  @Injectable({   providedIn: 'root' }) export class StripeService {   stripe: any;    constructor() {     this.stripe = Stripe(environment.stripePublicKey); // 替换为你的 Stripe 公钥   }    getStripeInstance() {     return this.stripe;   } }

在 environment.ts 文件中配置你的 Stripe 公钥:

export const environment = {   production: false,   stripePublicKey: 'pk_test_YOUR_STRIPE_PUBLIC_KEY' // 替换为你的 Stripe 公钥 };

实现自定义支付流程

在组件中,获取 Stripe 实例,并创建支付元素。

import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core'; import { StripeService } from './stripe.service';  @Component({   selector: 'app-payment',   templateUrl: './payment.component.html',   styleUrls: ['./payment.component.css'] }) export class PaymentComponent implements OnInit, AfterViewInit {   @ViewChild('cardElement') cardElement: ElementRef;   stripe: any;   elements: any;   card: any;   emailAddress: string = 'test@example.com'; // 示例邮箱    constructor(private stripeService: StripeService) {     this.stripe = this.stripeService.getStripeInstance();   }    ngOnInit(): void {   }    ngAfterViewInit(): void {     this.elements = this.stripe.elements();     this.card = this.elements.create('card');     this.card.mount(this.cardElement.nativeElement);   }    async confirmPayment() {     const { error } = await this.stripe.confirmPayment({       elements: this.elements,       confirmParams: {         receipt_email: this.emailAddress,       },       redirect: "if_required" // 添加 redirect: "if_required"     });      if (error && (error.type === "card_error" || error.type === "validation_error")) {       this.showMessage(error.message);     } else if (error) {       this.showMessage("An unexpected error occurred.");     } else {       // 支付成功,可以在这里处理后续逻辑       this.showMessage("Payment succeeded!");     }   }    showMessage(message: string) {     // 显示消息的逻辑,例如使用 alert 或 Angular Material Snackbar     alert(message);   } }

在 HTML 模板中,添加一个元素用于挂载 Stripe Card Element:

<div #cardElement></div> <button (click)="confirmPayment()">Pay</button>

注意事项:

  • redirect: “if_required”:这个配置告诉 Stripe 在需要重定向时才进行重定向,例如进行 3D Secure 验证。

解决 clientSecret 错误

如果在调用 stripe.confirmPayment 时遇到 clientSecret 找不到的错误,请确保以下几点:

  1. clientSecret 的正确获取: clientSecret 是在服务器端创建 PaymentIntent 或 SetupIntent 时生成的。 你需要通过你的后端 API 获取到这个 clientSecret。 确保你的后端代码正确地创建了 PaymentIntent 或 SetupIntent,并将其 clientSecret 返回给前端。

  2. 正确传递 clientSecret: 在调用 stripe.confirmPayment 时,clientSecret 必须正确地传递给 Stripe。 通常,clientSecret 是通过 elements 对象传递的,而不是直接作为参数传递。 确保你正确地创建了 elements 对象,并且已经将其传递给了 stripe.confirmPayment。

  3. 检查 elements 对象: 在调用 stripe.confirmPayment 之前,使用 console.log(this.elements) 检查 elements 对象是否正确创建。 确保 elements 对象包含了 Stripe Card Element 的信息。

示例 (假设从后端获取了 clientSecret):

// ... async confirmPayment() {   // 假设 this.clientSecret 从后端获取   const { error } = await this.stripe.confirmPayment({     elements: this.elements,     confirmParams: {       receipt_email: this.emailAddress,       // payment_method: {       //   card: this.card       // },       // client_secret: this.clientSecret // 不要在这里直接传递 clientSecret     },     redirect: "if_required"   });    // ... }

总结:

通过以上步骤,你可以在 Angular 14 项目中成功集成 Stripe 支付,并实现自定义的支付流程。 关键在于正确地引入 Stripe JS 库,创建 Stripe Card Element,以及正确地调用 stripe.confirmPayment 方法。 注意处理可能出现的错误,例如 clientSecret 找不到的错误,并根据 Stripe 的文档进行调试。 记住,PaymentIntent 或 SetupIntent 的创建和 clientSecret 的获取需要在后端完成,确保安全性。



评论(已关闭)

评论已关闭