Skip to content

Instantly share code, notes, and snippets.

@btownrippleman
Created June 25, 2020 23:58
Show Gist options
  • Select an option

  • Save btownrippleman/bd6abd14aa6f777051d21e5a03f7e36f to your computer and use it in GitHub Desktop.

Select an option

Save btownrippleman/bd6abd14aa6f777051d21e5a03f7e36f to your computer and use it in GitHub Desktop.
this allows you now to post to your python server, specifically in useEffect() in the fetch function, now you just need to modify whatever is inside fetch
import React, { useEffect, useState } from "react";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import "./CheckoutForm.css";
import api from "../api";
export default function CheckoutForm() {
const [amount, setAmount] = useState(0);
const [currency, setCurrency] = useState("");
const [clientSecret, setClientSecret] = useState(null);
const [error, setError] = useState(null);
const [metadata, setMetadata] = useState(null);
const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState(false);
const [postId, setPostId] = useState(null);
const stripe = useStripe();
const elements = useElements();
let randomString = () =>{ return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);}
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Hooks POST Request Example' })
};
fetch('http://localhost:8080/post/{ "userId": 1, "id": '+randomString()+', "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions we are the champions "}') //, requestOptions)
// .then(response => json())response.
// .then(data => setPostId(data.id));
// Step 1: Fetch product details such as amount and currency from
// API to make sure it can't be tampered with in the client.
api.getProductDetails().then((productDetails) => {
setAmount(productDetails.amount / 100);
setCurrency(productDetails.currency);
});
// Step 2: Create PaymentIntent over Stripe API
api
.createPaymentIntent()
.then((clientSecret) => {
setClientSecret(clientSecret);
})
.catch((err) => {
setError(err.message);
});
}, []);
const handleSubmit = async (ev) => {
ev.preventDefault();
setProcessing(true);
// Step 3: Use clientSecret from PaymentIntent and the CardElement
// to confirm payment with stripe.confirmCardPayment()
const payload = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement),
billing_details: {
name: ev.target.name.value,
},
},
});
if (payload.error) {
setError(`Payment failed: ${payload.error.message}`);
setProcessing(false);
console.log("[error]", payload.error);
} else {
setError(null);
setSucceeded(true);
setProcessing(false);
setMetadata(payload.paymentIntent);
console.log("[PaymentIntent]", payload.paymentIntent);
}
};
const renderSuccess = () => {
return (
<div className="sr-field-success message">
<h1>Your test payment succeeded</h1>
<p>View PaymentIntent response:</p>
<pre className="sr-callout">
<code>{JSON.stringify(metadata, null, 2)}</code>
</pre>
</div>
);
};
const renderForm = () => {
const options = {
style: {
base: {
color: "#32325d",
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: "antialiased",
fontSize: "16px",
"::placeholder": {
color: "#aab7c4",
},
},
invalid: {
color: "#fa755a",
iconColor: "#fa755a",
},
},
};
return (
<form onSubmit={handleSubmit}>
<h1>
{currency.toLocaleUpperCase()}{" "}
{amount.toLocaleString(navigator.language, {
minimumFractionDigits: 2,
})}{" "}
</h1>
<h4>Pre-order the Pasha package</h4>
<div className="sr-combo-inputs">
<div className="sr-combo-inputs-row">
<input
type="text"
id="name"
name="name"
placeholder="Name"
autoComplete="cardholder"
className="sr-input"
/>
</div>
<div className="sr-combo-inputs-row">
<CardElement
className="sr-input sr-card-element"
options={options}
/>
</div>
</div>
{error && <div className="message sr-field-error">{error}</div>}
<button
className="btn"
disabled={processing || !clientSecret || !stripe}
>
{processing ? "Processing…" : "Pay"}
</button>
</form>
);
};
return (
<div className="checkout-form">
<div className="sr-payment-form">
<div className="sr-form-row" />
{succeeded ? renderSuccess() : renderForm()}
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment