#valiant_avocado_47819
1 messages · Page 1 of 1 (latest)
Hello is this an endpoint on your flask server?
Or is this a response to an API call that your client or server is making directly to Stripe?
hello, sorry my english is a bit bad, this is my code, this endpoint give an error
Ruta para procesar pago con Stripe
@api.route('/process-payment', methods=['POST'])
@jwt_required()
def process_payment():
try:
stripe_keys = {
"secret_key": os.environ["STRIPE_SECRET_KEY"],
"publishable_key": os.environ["REACT_APP_STRIPE_PUBLIC_KEY"],
}
stripe.api_key = stripe_keys["secret_key"]
user = get_jwt_identity()
data = request.get_json()
intent = stripe.PaymentIntent.create(
amount= data.get('total_price'),
currency='eur',
automatic_payment_methods={
'enabled': True,
},
)
return ({
'clientSecret': intent['client_secret']
})
except Exception as e:
return jsonify(error=str(e)), 403
Can you tell if your code is running and returning the 403 because of the exception?
Or is your server returning the 403 before your code can even process it?
when I am in my frontend where I have the UseEffect it does not show me anything from stripe
import React, { useState, useEffect } from "react";
import { useParams } from 'react-router-dom';
//stripe
import { loadStripe } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import { FormPayment } from "../component/formPayment";
import "../../styles/stripe.css";
export const Payment = () => {
const [totalPrice, setTotalPrice] = useState(null);
let { orderId } = useParams();
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);
const [clientSecret, setClientSecret] = useState("");
const appearance = {
theme: 'stripe',
variables: {
colorPrimary: '#ff7e67',
colorText: '#474852',
},
};
const options = {
clientSecret,
appearance,
};
useEffect(() => {
const token = localStorage.getItem('token');
fetch(process.env.BACKEND_URL + /api/order/${orderId}, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": Bearer ${token},
},
})
.then((res) => res.json())
.then((data) => {
const totalPriceInCents = data.total_price ? Math.round(data.total_price * 100) : null;
if (totalPriceInCents !== null) {
console.log("Total Price en centavos:", totalPriceInCents);
setTotalPrice(totalPriceInCents);
} else {
console.error("El precio no es válido:", data.total_price);
}
})
.catch((error) => {
console.error("Error al hacer el fetch:", error);
});
}, [orderId]);
useEffect(() => {
const token = localStorage.getItem('token');
fetch(process.env.BACKEND_URL + "/api/process-payment", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": Bearer ${token},
},
body: JSON.stringify({ totalPrice }),
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
return (
<div className="Payment">
<p className="fs-1">{orderId}</p>
{totalPrice !== null && (
<p>Total Price: {totalPrice}</p>
)}
{clientSecret && (
<Elements stripe={stripePromise} options={options} >
<FormPayment />
</Elements>
)}
</div>
);
};
import React, { useEffect, useState } from "react";
import { PaymentElement, LinkAuthenticationElement, useStripe, useElements } from "@stripe/react-stripe-js";
export const FormPayment = () => {
const stripe = useStripe();
const elements = useElements();
const returnURL = process.env.FRONTEND_RETURN_URL;
const [name, setName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (!stripe) {
return;
}
const clientSecret = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);
if (!clientSecret) {
return;
}
stripe.retrievePaymentIntent(clientSecret).then(({ paymentIntent }) => {
switch (paymentIntent.status) {
case "succeeded":
setMessage("Payment succeeded!");
break;
case "processing":
setMessage("Your payment is processing.");
break;
case "requires_payment_method":
setMessage("Your payment was not successful, please try again.");
break;
default:
setMessage("Something went wrong.");
break;
}
});
}, [stripe]);
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) {
return;
}
setIsLoading(true);
const { error } = await stripe.createPaymentMethod({
elements,
confirmParams: {
return_url: returnURL,
},
});
if (error.type === "card_error" || error.type === "validation_error") {
setMessage(error.message);
} else {
setMessage("An unexpected error occurred.");
}
setIsLoading(false);
};
const paymentElementOptions = {
layout: "tabs"
}
return (
<form id="payment-form" onSubmit={handleSubmit}>
<LinkAuthenticationElement
id="link-authentication-element"
onChange={(e) => setEmail(e.target.value)}
/>
<PaymentElement id="payment-element" options={paymentElementOptions} />
<button disabled={isLoading || !stripe || !elements} id="submit">
<span id="button-text">
{isLoading ? <div className="spinner" id="spinner"></div> : "Pay now"}
</span>
</button>
{/* Show any error or success messages */}
{message && <div id="payment-message">{message}</div>}
</form>
);
}
Unfortunately I cannot debug all of that code for you. Can you try stepping through your code to see how far it goes?
It sounds like your frontend is sending a request your server, so I think you should investigate what is happening on your server
If you print out that exception in your server-code, do you see an error message?
What steps could I follow? I know that what is wrong in my code is something related to stripe, but I don't know if it is because of the endpoint, or why exactly
I think the two best options would be:
- Put a breakpoint in your server-side code, step through your code when it gets hit
- Put print statements in your code to see what code is executed and what errors happen