skip to Main Content

I am integrating a front end app with Stripe for payment processing.

I am following the quick start docs and nearly have everything working, however I am not being automatically redirected. I do get a successful response which contains a link so it wouldn’t be too difficult to pull this out of the response. However, I don’t want to do this if it isn’t the intended implementation.

My backend:

@app.post('/create-checkout-session')
async def create_checkout_session(request: Request):
    data = await request.json()
    price_id = data['price_id']
    try:
        checkout_session = stripe.checkout.Session.create(
            line_items=[
                {
                    # Provide the exact Price ID (for example, pr_1234) of the product you want to sell
                    'price': price_id,
                    'quantity': 1,
                },
            ],
            mode='subscription',
            success_url='http://localhost:3000' + '?success=true',
            cancel_url='http://localhost:3000' + '?canceled=true',
        )
    except Exception as e:
        print(e)
        return str(e)
    return redirect(checkout_session.url, code=303)

My front end api call:

  fetch("{backend}/create-checkout-session", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    credentials: "include",
    body: JSON.stringify({ price_id: "price_1P3O6zRsJS40xuhRCkN4vrML" }),
  });

And the response to the api call

{
    "headers": {
        "Content-Type": "text/html; charset=utf-8",
        "Content-Length": "905",
        "Location": "https://checkout.stripe.com/c/pay/cs_test_a1ODicN9C2lxgpSowo6RVXl8G1FaBFwaJrkgKwtuPKE6LBSIV5izrxyT67#fidkdWxOYHwnPyd1blpxYHZxWjA0Sn9cR1ZXdk9WMTV9cG1Xcnd0N38wN2prTnBHbUcxTDNUd3V0fW9uSFRWUEdhS29WdF1cXH1jbmRSXX1Tdnd2Yn1MazVwaTNkMHU3cXdKY2tIM2J9VTdrNTU8R092cjZudCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl"
    },
    "_status": "303 SEE OTHER",
    "_status_code": 303,
    "direct_passthrough": false,
    "_on_close": [],
    "response": [
        "<!doctype html>n<html lang=en>n<title>Redirecting...</title>n<h1>Redirecting...</h1>n<p>You should be redirected automatically to the target URL: <a href="https://checkout.stripe.com/c/pay/cs_test_a1ODicN9C2lxgpSowo6RVXl8G1FaBFwaJrkgKwtuPKE6LBSIV5izrxyT67#fidkdWxOYHwnPyd1blpxYHZxWjA0Sn9cR1ZXdk9WMTV9cG1Xcnd0N38wN2prTnBHbUcxTDNUd3V0fW9uSFRWUEdhS29WdF1cXH1jbmRSXX1Tdnd2Yn1MazVwaTNkMHU3cXdKY2tIM2J9VTdrNTU8R092cjZudCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl">https://checkout.stripe.com/c/pay/cs_test_a1ODicN9C2lxgpSowo6RVXl8G1FaBFwaJrkgKwtuPKE6LBSIV5izrxyT67#fidkdWxOYHwnPyd1blpxYHZxWjA0Sn9cR1ZXdk9WMTV9cG1Xcnd0N38wN2prTnBHbUcxTDNUd3V0fW9uSFRWUEdhS29WdF1cXH1jbmRSXX1Tdnd2Yn1MazVwaTNkMHU3cXdKY2tIM2J9VTdrNTU8R092cjZudCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl</a>. If not, click the link.n"
    ]
}

If it’s important the redirect call in my python endpoint is from flask

2

Answers


  1. I provide my sample code. I used Node.js/Express backend and React/Redux frontend.

    Backend code :

    const createCheckoutSession = async (req, res) => {
        try {
            const { priceId, type } = req.body;
            const email = req?.decoded?.email;
    
            // Check if user exists
            const user = await User.findOne({ email });
            if (!user) {
                return res.status(404).json({ error: MESSAGE.USER_NOT_FOUND });
            }
    
            // Create a new checkout session
            const session = await stripe.checkout.sessions.create({
                customer_email: email, // Associate session with existing customer
                mode: type, // subscription
                payment_method_types: ['card'],
                line_items: [{ price: priceId, quantity: 1 }],
                allow_promotion_codes: true,
                automatic_tax: { enabled: true },
                success_url: config.STRIPE_SUCCESS_URL,
                cancel_url: config.STRIPE_CANCELED_URL,
            });
    
            // Return the session ID
            return res.status(200).json({ id: session.id });
        } catch (error) {
            // Handle errors
            console.log(error)
            return res.status(500).json({ message: error.message });
        }
    };
    

    Frontend code:

    import { loadStripe } from '@stripe/stripe-js';
    
    const handlePayment = async () => {
        setLoading(true);
        
        try {
            const stripe = await loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);
            const response = await api.post('/api/create-checkout-session', JSON.stringify(item));
            const { id: sessionId } = response.data;
        
            const result = await stripe.redirectToCheckout({ sessionId });
        
            if (result.error) {
               console.error(result.error);
            }
        } catch (error) {
            console.error('Error processing payment:', error);
        } finally {
            setLoading(false);
        }
    };
    

    You can use stripe-js in your react app.

    Login or Signup to reply.
  2. Is your frontend app is configured to follow the server-side redirect? If not, that might be the issue here. You should try tweaking your fetch call to something like:

        fetch(url, { method: 'POST', redirect: 'follow'})
        .then(response => {
            // HTTP 301 response
        })
        .catch(function(err) {
            console.info(err + " url: " + url);
        });```
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search