Le paiement se rend sur stripes!

This commit is contained in:
Victor Turgeon 2022-12-08 19:40:40 -05:00
parent 41ddc7d0e3
commit 72e7193580
4 changed files with 103 additions and 81 deletions

View File

@ -10,7 +10,7 @@
"DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=GrossesMitainesDB; Trusted_Connection=True; MultipleActiveResultSets=true" "DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=GrossesMitainesDB; Trusted_Connection=True; MultipleActiveResultSets=true"
}, },
"StripeTest": { "StripeTest": {
"PublicKey": "pk_test_", "PublicKey": "pk_test_51M8mzOEerenEZcQIUmJIrmsaZeeNlOil2G1JcMvvO68w50MJr8rDwUjVO44a8dDhSlsRH4GdzH9rDqtkg4Rtbzco00NqkHdn3H",
"SecretKey": "sk_test_" "SecretKey": "sk_test_51M8mzOEerenEZcQIyHb9AdeluhDsSy9PaxTeqDq6XUhSRCbbqvReHA2KoFb3a8Ru5PAzMgMlCKmj8UDpLKWzUUmr00rta511y8"
} }
} }

View File

@ -1,6 +1,11 @@
import React, { useState } from "react" import React, { useState, useContext } from "react"
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js" import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"
import { Button } from "react-bootstrap" import { Button } from "react-bootstrap"
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { CartContext } from "../components/Cart";
import { useNavigate } from "react-router-dom";
const CARD_OPTIONS = { const CARD_OPTIONS = {
iconStyle: "solid", iconStyle: "solid",
@ -24,16 +29,18 @@ const CARD_OPTIONS = {
const PaymentForm = ({ cost }) => { const PaymentForm = ({ cost, invoice }) => {
const navigate = useNavigate();
const [success, setSuccess] = useState(false); const mySwal = withReactContent(Swal);
const [cardName, setCardName] = useState(""); const [cardName, setCardName] = useState("");
const stripe = useStripe(); const stripe = useStripe();
const elements = useElements(); const elements = useElements();
const cart = useContext(CartContext);
const handleSubmit = async (e) => { const handleSubmit = async (e) => {
e.preventDefault(); e.preventDefault();
const { error, paymentMethod } = await stripe.createPaymentMethod({ const { error } = await stripe.createPaymentMethod({
type: "card", type: "card",
card: elements.getElement(CardElement) card: elements.getElement(CardElement)
}) })
@ -44,12 +51,22 @@ const PaymentForm = ({ cost }) => {
} }
if (!error) { if (!error) {
const { id } = paymentMethod; stripe.createToken(elements.getElement(CardElement), { name: cardName })
.then((result) => {
if (!result.error) {
const json = JSON.stringify({ amount: cost, stripeId: id }); console.log(invoice);
invoice.token = result.token.id;
invoice.description = `Payement de ${cost} à GM`;
invoice.amountInCents = cost;
invoice.currencyCode = "CAD";
invoice.name = cardName;
invoice.email = invoice.emailAddress;
invoice.phone = invoice.phoneNumber;
const json = JSON.stringify(invoice);
fetch(`https://localhost:7292/api/Payment`, { fetch(`https://localhost:7292/api/Invoice`, {
method: 'POST', method: 'POST',
credentials: 'include', credentials: 'include',
mode: 'cors', mode: 'cors',
@ -59,17 +76,29 @@ const PaymentForm = ({ cost }) => {
}, },
body: json body: json
}).then((response) => { }).then((response) => {
console.log(response);
if (response.ok) { if (response.ok) {
console.log("Successful payment"); mySwal.fire({
setSuccess(true); title: 'Commande envoyée avec succès!',
timer: 2000,
icon: "success"
}).then(
() => {
cart.emptyCart();
navigate('/morceaux');
}
);
} }
else { else {
console.log(response); mySwal.fire({
title: 'Erreur!',
timer: 2000,
icon: "error"
});
} }
}).catch((error) => { });
console.log("Error: ", error); }
}) });
} }
else { else {
console.log(error.message); console.log(error.message);
@ -80,7 +109,7 @@ const PaymentForm = ({ cost }) => {
return ( return (
<> <>
{!success ? {
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<fieldset className="FormGroup"> <fieldset className="FormGroup">
<input className="FormRow" placeholder="Cardholder Name" id="cardholder-name" type="text" value={cardName} onChange={e => setCardName(e.target.value)} /> <input className="FormRow" placeholder="Cardholder Name" id="cardholder-name" type="text" value={cardName} onChange={e => setCardName(e.target.value)} />
@ -92,12 +121,6 @@ const PaymentForm = ({ cost }) => {
<Button className="Payment-btn" type="submit">Payer</Button> <Button className="Payment-btn" type="submit">Payer</Button>
</div> </div>
</form> </form>
:
<div>
<h2>
L'achat s'est déroulé avec succès
</h2>
</div>
} }
</> </>
) )

View File

@ -7,10 +7,10 @@ const PUBLIC_KEY = "pk_test_51M8mzOEerenEZcQIUmJIrmsaZeeNlOil2G1JcMvvO68w50MJr8r
const stripeTestPromise = loadStripe(PUBLIC_KEY); const stripeTestPromise = loadStripe(PUBLIC_KEY);
const StripeContainer = ({cost}) => { const StripeContainer = ({cost, invoice}) => {
return ( return (
<Elements stripe={stripeTestPromise}> <Elements stripe={stripeTestPromise}>
<PaymentForm cost={cost}/> <PaymentForm cost={cost} invoice={invoice} />
</Elements> </Elements>
) )
} }

View File

@ -4,8 +4,6 @@ import ReviewProdList from "../components/ReviewProdList";
import TotalProductsPrice from "../components/TotalProductsPrice"; import TotalProductsPrice from "../components/TotalProductsPrice";
import { Row, Col, Button } from "react-bootstrap"; import { Row, Col, Button } from "react-bootstrap";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { CartContext } from "../components/Cart"; import { CartContext } from "../components/Cart";
import StripeContainer from "../components/StripeContainer" import StripeContainer from "../components/StripeContainer"
@ -13,7 +11,7 @@ const ReviewInvoice = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const mySwal = withReactContent(Swal);
const cart = useContext(CartContext); const cart = useContext(CartContext);
@ -90,41 +88,42 @@ const ReviewInvoice = () => {
navigate("/formulaire") navigate("/formulaire")
} }
const handleConfirmer = async () => {
const json = JSON.stringify(thisInvoice);
const response = await fetch(`https://localhost:7292/api/Invoice`, { // const handleConfirmer = async () => {
method: 'POST', // const json = JSON.stringify(thisInvoice);
credentials: 'include',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: json
})
if (response.ok) {
mySwal.fire({
title: 'Commande envoyée avec succès!',
timer: 2000,
icon: "success"
}).then(
() => {
cart.emptyCart();
navigate('/morceaux');
}
)
}
else {
console.log("Erreur de creation la commande #" + thisInvoice.id);
mySwal.fire({
title: 'Erreur!',
timer: 2000,
icon: "error"
})
}
} // const response = await fetch(`https://localhost:7292/api/Invoice`, {
// method: 'POST',
// credentials: 'include',
// mode: 'cors',
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// },
// body: json
// })
// if (response.ok) {
// mySwal.fire({
// title: 'Commande envoyée avec succès!',
// timer: 2000,
// icon: "success"
// }).then(
// () => {
// cart.emptyCart();
// navigate('/morceaux');
// }
// )
// }
// else {
// console.log("Erreur de creation la commande #" + thisInvoice.id);
// mySwal.fire({
// title: 'Erreur!',
// timer: 2000,
// icon: "error"
// })
// }
// }
return ( return (
<> <>
@ -191,7 +190,7 @@ const ReviewInvoice = () => {
/> />
</Col> </Col>
</Row> </Row>
<StripeContainer cost={total} /> <StripeContainer cost={total} invoice={thisInvoice} />
</> </>
); );