Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API request to Stripe fails (Error: Not a valid URL)

I want to build a simple checkout page using the Stripe Prebuilt Checkout Page in a Node application.

I follow all the necessary steps in the Stripe docs but the API request doesn't seem to work.

server.js -

const express = require("express");
const stripe = require("stripe")(
  "<mySecretKey>"
);

const app = express();

app.get("/checkout-sucess", (req, res) => {
  res.send("<h1>Success</h1>");
});

app.get("/checkout-cancel", (req, res) => {
  res.send("<h1>Cancelled</h1>");
});

app.post("/create-checkout-session", async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "inr",
          product_data: {
            name: "Cewa",
          },
          unit_amount: 200,
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: "/checkout-success",
    cancel_url: "/checkout-cancel",
  });

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

app.listen(4242, () => {
  console.log("Server is live on Port 4242!");
});

checkout.html -

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Stripe API Test</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <button
      type="button"
      id="checkout-button"
      style="
        padding: 20px;
        background-color: beige;
        cursor: pointer;
        outline: none;
      "
    >
      Checkout
    </button>
  </body>

  <script type="text/javascript">
    var stripe = Stripe(
      "<myPublishableAPIKey"
    );
    var checkoutButton = document.getElementById("checkout-button");
    checkoutButton.addEventListener("click", function () {
      fetch("http://localhost:4242/create-checkout-session", {
        method: "POST",
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (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);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
  </script>
</html>

When I make this request, I get the following error in the console coming from checkout.html -

Error: Not a valid URL

I don't think I've missed anything from the docs. Any idea what's going wrong? Thanks in advance.

like image 860
vaibhav deep Avatar asked Jan 28 '21 06:01

vaibhav deep


People also ask

Is Stripe API down?

We're currently investigating elevated error rates and response times with the API. We'll post an update soon. From 20:10–20:54 UTC, we saw elevated error rates and response times with the API. This is now resolved.

What does Stripe payment error mean?

An error occurred while processing the card. The payment needs to be attempted again. If it still can't be processed, try again later.

How do you handle stripe errors?

Errors and HTTP If an immediate problem prevents an API call from continuing, the Stripe Ruby library raises an exception. It's a best practice to catch and handle exceptions. To catch an exception, use Ruby's rescue keyword. Catch Stripe::StripeError or its subclassses to handle Stripe-specific exceptions only.

What does errors Code Card_decline_rate_limit_exceeded mean?

card_decline_rate_limit_exceeded. This card has been declined too many times. You can try to charge this card again after 24 hours. We suggest reaching out to your customer to make sure they have entered all of their information correctly and that there are no issues with their card.


Video Answer


2 Answers

You need to add real success and cancel url, please check below code:

const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "inr",
          product_data: {
            name: "Cewa",
          },
          unit_amount: 200,
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: "http://sitename.com/checkout-success",
    cancel_url: "http://sitename.com/checkout-cancel",
  });
like image 166
ZealousWeb Avatar answered Oct 08 '22 02:10

ZealousWeb


The success_url and cancel_url fields need to be a real URL accessible on the internet. /checkout-success won't work, you have to pass in the full URL e.g. https://your-site.com/checkout-success.

like image 31
Paul Asjes Avatar answered Oct 08 '22 02:10

Paul Asjes