【问题标题】:How do I get my Stripe payments to work on Angular and Node.js?如何让我的 Stripe 付款在 Angular 和 Node.js 上工作?
【发布时间】:2022-02-06 15:12:20
【问题描述】:

我注册了 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”按钮最终链接到 Stripe 支付页面。

error image

GitHub 链接是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}!`));

【问题讨论】:

    标签: node.js angularjs typescript stripe-payments


    【解决方案1】:

    您看到该错误消息的原因是您的应用程序正在向不存在的路由发出请求,即 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 发出请求,您还需要在您的服务器上启用/允许cross-origin requests。你可以参考这个:Javascript - Response to preflight request doesn't pass access control check

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2018-09-12
      • 2017-04-16
      • 2023-04-11
      • 2017-03-13
      • 2021-07-28
      相关资源
      最近更新 更多