Angular和Stripe集成

问题描述

我正在尝试将Stripe集成到我的网站中,但目前遇到了一些麻烦。 我真的有问题

#1: 我已经关注了这个thread和这个stackblitz页面。但是它仍然无法正常工作。看来我的应用程序没有使用Stripe组件。

payment form of my application

我的ts文件

import {
 Component,AfterViewInit,OnDestroy,ViewChild,ElementRef,ChangeDetectorRef
} from '@angular/core';

import  { NgForm } from "@angular/forms"
import { AngularstripeService } from '@fireflysemantics/angular-stripe-service'

@Component({
selector: 'payment',templateUrl: './payment.component.html',styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements AfterViewInit,OnDestroy {

@ViewChild('cardInfo',{ static: false }) cardInfo: ElementRef;

stripe: any;
loading = false;
confirmation: any;

card: any;
cardHandler = this.onChange.bind(this);
error: any;

constructor(
 private cd: ChangeDetectorRef,private stripeService:AngularstripeService) {}

ngAfterViewInit() {
 this.stripeService.setPublishableKey('pk_test____________').then(
  stripe=> {
    console.log("in function"); // logging to console
    this.stripe = stripe;
    const elements = stripe.elements();    
    this.card = elements.create('card');
    this.card.mount(this.cardInfo.nativeElement); // also tried "#card-info"
    this.card.addEventListener('change',this.cardHandler);
 }).catch((e:any)) => { // no errors
   console.error(e);
}

ngOnDestroy() {
 this.card.removeEventListener('change',this.cardHandler);
 this.card.destroy();
}

onChange( error: any ) {
 if (error) {
  this.error = error.message;
 } else {
  this.error = null;
 }
 this.cd.detectChanges();
}

async onSubmit(form: NgForm) {
 console.log(form)
 const { token,error } = await this.stripe.createtoken(this.card);

 if (error) {
  console.log('Error:',error);
 } else {
  console.log('Success!',token);
 }
}
}

仅当对表单进行子突变时,应用程序不会给出任何错误,但我收到错误消息,表明表单为空,这是有道理的。

我的程序包JSON条纹组件

"@types/stripe-checkout": "^1.0.3","@types/stripe-v3": "^3.1.20","@fireflysemantics/angular-stripe-service": "^1.0.0","@stripe/stripe-js": "^1.9.0","@types/stripe": "^7.13.24",

我不确定自己在做什么错 我也曾尝试过CDN版本,但这种方法

无效

我的HTML和CSS与Stackblitz页面完全相同

#2: 是否有任何有关将Stripe IDEAL与Angular集成的文档?

我不必解决本教程的必要内容,但我需要一个很好的Stripe和Angular工作示例

解决方法

好吧,终于,几天后,我发现了一个最新的教程 tutorial

创建组件

完整文档here

好的,首先,您应该通过NPM安装Stripe。

 npm install ngx-stripe @stripe/stripe-js;

像这样导入条纹。

import { NgxStripeModule } from 'ngx-stripe';

此后,现在在您的导入中包含Stripe

    NgxStripeModule.forRoot('***your-stripe-publishable-key***'),

之后,您现在可以在文件的 在您的TS中导入Stripe元素

import { StripeService,StripeCardComponent } from 'ngx-stripe';
import { StripeCardElementOptions,StripeElementsOptions } from '@stripe/stripe-js';

您可以在此处更改样式和语言的

 cardOptions: StripeCardElementOptions = {
    hidePostalCode: true,style: {
      base: {
        iconColor: '#666EE8',color: '#31325F',fontWeight: '300',fontFamily: '"Helvetica Neue",Helvetica,sans-serif',fontSize: '14px','::placeholder': {
          color: '#CFD7E0',},};

  elementsOptions: StripeElementsOptions = {
    locale: 'nl',};

然后您可以初始化信用卡组件

<ngx-stripe-card
    [options]="cardOptions"
    [elementsOptions]="elementsOptions"
></ngx-stripe-card>

或惯用成分

<ngx-stripe-ideal-bank
    [options]="cardOptions"
    [elementsOptions]="elementsOptions"
></ngx-stripe-ideal-bank>

创建付款

对于付款,您应该向创建和处理付款的后端服务器创建一个http请求。 我是用ExpressJS服务器做到的。 首先是http请求

let data = {
      name: name,email: email,postal: postal,paymentOption: this.paymentOption,products: this.products,userEmail: this.email,};

    const headers = new HttpHeaders()
      .set('Content-Type','application/json')
      .set('Access-Control-Allow-Origin','*')
      .set('Access-Control-Allow-Credentials','true')
      .set('Access-Control-Allow-Methods','POST')
      .set('Access-Control-Allow-Headers','Content-Type')
      .set('Authorization','*');

    this.http
      .post('http://127.0.0.1:3000/pay',JSON.stringify(data),{
        headers: headers,})

现在您已经创建了一个http请求

app.post('/pay',cors(),async function (req,res) {
   const paymentIntent = await stripe.paymentIntents.create({
        amount: price,// watch out in cents
        currency: 'eur',receipt_email: email,payment_method_types: [method],// card or ideal
        description: `Customer named ${name}`,});
)}

将您的回复发送回前端

    res.status(201).json(paymentIntent.client_secret);

并确认付款

this.http
          .post('http://127.0.0.1:3000/pay',{
            headers: headers,}).subscribe(async (data) => {
                console.log(data);
                if (this.paymentOption == 'creditcard') {
                    // confirm creditcard payment
                    this.stripeService
                        .confirmCardPayment(data.toString(),{
                            payment_method: {
                                card: this.card.element,billing_details: {
                                    name: name,})
                        .subscribe((result) => {
                            console.log('result',result);
                        });
                } 
                    
            });

特别感谢的开发者 1ngx-stripe,如果您对此文章有帮助,请给我投票