Files
bodyshop/client/src/pages/mobile-payment/mobile-payment.component.jsx
2021-11-23 14:24:48 -08:00

82 lines
2.4 KiB
JavaScript

import {
PaymentRequestButtonElement,
useStripe,
} from "@stripe/react-stripe-js";
import React, { useEffect, useState } from "react";
export default function MobilePaymentComponent() {
const stripe = useStripe();
const [paymentRequest, setPaymentRequest] = useState(null);
useEffect(() => {
if (stripe) {
const pr = stripe.paymentRequest({
country: "CA",
displayItems: [{ label: "Deductible", amount: 1 }],
currency: "cad",
total: {
label: "Demo total",
amount: 1,
},
requestPayerName: true,
requestPayerEmail: true,
});
// Check the availability of the Payment Request API.
pr.canMakePayment().then((result) => {
if (result) {
setPaymentRequest(pr);
} else {
// var details = {
// total: { label: "", amount: { currency: "CAD", value: "0.00" } },
// };
// new PaymentRequest(
// [{ supportedMethods: ["basic-card"] }],
// {}
// // details
// ).show();
}
});
}
}, [stripe]);
if (paymentRequest) {
paymentRequest.on("paymentmethod", async (ev) => {
//Call server side to get the client secret
// Confirm the PaymentIntent without handling potential next actions (yet).
const { error: confirmError } = await stripe.confirmCardPayment(
"clientSecret",
{ payment_method: ev.paymentMethod.id },
{ handleActions: false }
);
if (confirmError) {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete("fail");
} else {
// Report to the browser that the confirmation was successful, prompting
// it to close the browser payment method collection interface.
ev.complete("success");
// Let Stripe.js handle the rest of the payment flow.
const {
error, //paymentIntent
} = await stripe.confirmCardPayment("clientSecret");
if (error) {
// The payment failed -- ask your customer for a new payment method.
} else {
// The payment has succeeded.
}
}
});
return (
<div style={{ height: "300px" }}>
<PaymentRequestButtonElement options={{ paymentRequest }} />
</div>
);
}
return <div></div>;
}