0

I am registered for Stripe, and I am working on an e-Commerce website. When I click "GO TO CHECKOUT" button, I get an error which says POST http://localhost:4200/create-checkout-session 404 (Not Found). I will send you a sample version of this project that I am working on, since my goal is only to get the button to work. I am not that experienced with Stripe, and need help from anyone who has been successful with Stripe payments through Angular. The documentation is here (https://docs.ngx-stripe.dev/), but I find it quite confusing due to my little experience with Stripe. The payments must NOT be Legacy Checkout.

The aim is to get the "GO TO CHECKOUT" button to eventually link to the Stripe payment page.

error image

The GitHub link is https://github.com/Aacgectyuoki/testing123, if you want to try the code yourself.

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}!`));

1 Answers1

0

The reason why you're seeing that error message is because your application is making a request to a route that doesn't exist i.e. http://localhost:4200/create-checkout-session.

This line of code uses a relative URL - it will use the root domain of your page to make the request e.g. http://localhost:4200/create-checkout-session

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

However, your server is configured to listen on port 4242. The simplest way to fix this would be to update the line to an absolute URL

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

Although a better fix would be to configure and use a environment variable

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

After fixing that issue, if you try clicking on the button, you'll see the below error.

CORS error

Since you're making a request from a different domain i.e. localhost:4200 -> localhost:4242, you will also need to enable/allow cross-origin requests on your server. You can refer to this : Javascript - Response to preflight request doesn't pass access control check

alex
  • 1,923
  • 11
  • 9