Overview
- I am running a Netlify hosted site as a staging mirror for my main site
- The staging site: https://thirsty-lovelace-bf2b31.netlify.app/
- The main site: cbessential.services
- Both are using Gatsby, React
Problem
I need to get the form on this page to both submit to Netlify and open Stripe checkout page. Stripe checkout page is working good. Netlify form submissions without Stripe work as well. Mixing the two is where I am running into problems. The form is listed in the Forms section of Netlify but there are no submissions. Here is my code
import React, { useState } from "react";
import { loadStripe } from "@stripe/stripe-js";
function encode(data) {
return Object.keys(data)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
}
let stripePromise
const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe("pk_test_RlvibjeKdvwY81acv2YLwvTM00I3UsWXIi")
}
return stripePromise
}
const Checkout = () => {
const [loading, setLoading] = useState(false)
const redirectToCheckout = async event => {
event.preventDefault()
setLoading(true)
const stripe = await getStripe()
const { error } = await stripe.redirectToCheckout({
mode: "subscription",
lineItems: [{ price: "price_1Gva5YAeKYVunD5viRkFzoR7", quantity: 1 }],
successUrl: `http://localhost:8000/thanks/`,
cancelUrl: `http://localhost:8000/404`,
})
if (error) {
console.warn("Error:", error)
setLoading(false)
}
}
return (
<form
name="transfer"
method="POST"
action="/thanks"
data-netlify-honeypot="bot-field"
data-netlify="true"
id="transfer"
className="transfer"
<p className="screen-reader-text">
<label>Don't fill this out if you're human: <input name="bot-field" /></label>
</p>
<p className="form-row">
<label htmlFor="transfer-name" className="form-label">Name</label>
<input type="text" name="name" id="transfer-name" className="form-input" />
</p>
<p className="form-row">
<label htmlFor="transfer-email" className="form-label">Email address</label>
<input type="email" name="email" id="transfer-email" className="form-input" />
</p>
<input type="hidden" name="form-name" value="transfer" />
<p className="form-row form-submit">
<button type="submit" className="button"
disabled={loading}
onClick={redirectToCheckout}>
Pay
</button>
</p>
</form>
)
}
export default Checkout
You can find it here on Github also.
Continued
I’m not a great coder, and have the sneaking suspicion my error lays in the insertion of a javascript element into the Neltify form:
<button type=“submit” className=“button”
disabled={loading}
onClick={redirectToCheckout}>
Pay
Specific Questions
- — Is the onClick event the proper way to handle redirect to Stripe checkout in a Netlify form?
- ------- Can I make it an ‘action’ as in
<form...action="/thanks"
? - ---------------- Or am I overall better trying to make a custom Stripe.js element to accept payment on the page (be aware I am a n00b)