#i am a noob-API-authentication

1 messages ยท Page 1 of 1 (latest)

late aurora
#

๐Ÿ‘‹ Happy to help

#

I'd suggest using Stripe Node library instead of using your own API call

#

Secret key should be used at backend, not frontend

dusk granite
#

Also, I am using <CardElement/>, so I am not redirecting to stripe to complete payment, everything is done on my website. I am getting the error after i click the 'pay' button

#

pay button is the submit button for the form that contains the CardElement

late aurora
#

Can you share the code at /payment where you make request to Stripe?

dusk granite
#

app.post("/payment", async (req, res) => {
const { id } = req.body;

try {
const paymentIntent = await stripe.paymentIntents.create({
amount: 15000,
currency: "USD",
payment_method: id,
confirm: true,
});

res.json({
  // clientSecret: paymentIntent.client_secret,
  message: "Payment Successful",
  success: true,
});

} catch (error) {
console.log("Error", error);
res.json({
message: "Payment failed",
success: false,
});
}
});

rocky dock
#

๐Ÿ‘‹ Stepping in, give me a few mins to catch up

dusk granite
#

.
.
.
this is the frontend code for the onsubmit button, if it helps

#

const handleSubmit = async (e) => {
e.preventDefault();

const { error, paymentMethod } = await stripe.createPaymentMethod({
  type: "card",
  card: elements.getElement(CardElement),
});

if (!error) {
  try {
    const { id } = paymentMethod;
    const response = await axios.post("/payment", {
      id: id,
      headers: {
        Authorization: `Bearer ${process.env.REACT_APP_STRIPE_SECRET_KEY}`,
      },
    });

    if (response.data.success) {
      console.log("Successful Payment");
      setSuccess(true);
      setMessage("Successful Payment");
    }
  } catch (error) {
    console.log("Error", error);
  }
} else {
  console.log(error.message);
}

};

rocky dock
#

Are you including secret key in frontend? It's incorrect. Secret key should only be used in backend

dusk granite
#

I will remove it

rocky dock
#

The error you see seems to come from backend

dusk granite
#

do you have any ideas on how to include authorization in the headers to authenticate stripe

#

yes it is from backend, it printed in my vscode terminal

rocky dock
#

To fix it you have 2 choices:

  1. Include secret key in authorization header and do a raw REST request to Stripe endpoint
  2. Use Stripe official Node API and you just set the key in our SDK's instance once you imported
#

I strongly recommend 2, like 99% of Stripe user would do that

#

Please take a look here

dusk granite