如何让我的 Stripe 付款在 Angular 和 Node.js 上工作?

How do I get my Stripe payments to work on Angular and Node.js?

我注册了 Stripe,我在电子商务网站上工作。当我点击“GO TO CHECKOUT”按钮时,我收到一条错误消息 POST http://localhost:4200/create-checkout-session 404 (Not Found)。我将向您发送我正在处理的这个项目的示例版本,因为我的目标只是让按钮工作。我对 Stripe 没有那么多经验,需要通过 Angular 成功使用 Stripe 付款的任何人的帮助。文档在这里 (https://docs.ngx-stripe.dev/),但由于我对 Stripe 的经验不多,我觉得它很混乱。付款不能是 Legacy Checkout。

目的是让“GO TO CHECKOUT”按钮最终link进入 Stripe 支付页面。

error image

GitHub link 是 https://github.com/Aacgectyuoki/testing123 ,如果你想自己尝试代码。

checkout.component.html

<button (click)="checkout()">
    GO TO CHECKOUT
</button>

checkout.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';

import { StripeService } from 'ngx-stripe';

@Component({
  selector: 'app-checkout',
  templateUrl: './checkout.component.html'
})
export class CheckoutComponent {
  constructor(
    private http: HttpClient,
    private stripeService: StripeService
  ) {}

  checkout() {
    // Check the server.js tab to see an example implementation
    this.http.post('/create-checkout-session', {})
      .pipe(
        switchMap(session => {
          //@ts-ignore
          return this.stripeService.redirectToCheckout({ sessionId: session.id })
        })
      )
      .subscribe(result => {
        // If `redirectToCheckout` fails due to a browser or network
        // error, you should display the localized error message to your
        // customer using `error.message`.
        if (result.error) {
          alert(result.error.message);
        }
      });
  }
}

app.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgxStripeModule } from 'ngx-stripe';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CheckoutComponent } from './checkout/checkout.component';

@NgModule({
  declarations: [
    AppComponent,
    CheckoutComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    NgxStripeModule.forRoot('INSERT PK HERE'),
    ReactiveFormsModule//, 
   // LibraryModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule { }

server.js

const express = require('express');
const app = express();
// @ts-ignore
const stripe = require('stripe')('INSERT SECRET KEY HERE');

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'T-shirt',
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/cancel',
  });

  res.json({ id: session.id });
});

app.listen(4242, () => console.log(`Listening on port ${4242}!`));

您看到该错误消息的原因是您的应用程序正在向不存在的路由发出请求,即 http://localhost:4200/create-checkout-session.

这行代码使用相对 URL - 它将使用您页面的根域来发出请求,例如http://localhost:4200/create-checkout-session

this.http.post('/create-checkout-session', {})

但是,您的服务器配置为侦听端口 4242。解决此问题的最简单方法是将行更新为绝对 URL

this.http.post('http://localhost:4242/create-checkout-session', {})

虽然更好的解决方法是配置和使用环境变量

this.http.post(SERVER_DOMAIN + '/create-checkout-session', {})

解决该问题后,如果您尝试单击该按钮,您将看到以下错误。

由于您从不同的域发出请求,即 localhost:4200 -> localhost:4242,您还需要 enable/allow cross-origin requests on your server. You can refer to this :