Iam making a basic react website that has a payment feature
So, Iam using Stripe Hosted Checkout page, so i used WebHooks to track events, but thats only on the server. I want to notify or basically send a reponse to the frontend that the payment was successfully done and proceed with further operations
heres how iam creating a stripe session //frontend
export default function Checkout() {
async function toCheckOut(){
fetch("/checkout", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(user),
})
.then(res=>res.json())
.then((data)=>{
window.location.href = data.url;
})
}
let user = {
prod_name: "FlimFair Monthly Subscription",
price: "49",
id: "price_1OJsBfSAzab3NSzcquCNBDJJ"
}
return (
<div>
<button type='button'>Redirect To Checkout</button>
<button type='button' onClick={toCheckOut}>Checkout</button>
</div>
)
}
//server
const express = require("express");
const cors = require('cors');
const bodyParser = require('body-parser');
const stripe = require('stripe')('sk_test_************************************************************************************************');
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
//WEBHOOK
app.post("/hooks", express.raw({type: 'application/json'}), (req,res)=>{
let signingsecret = "whsec_70a70718d689eff658076268d708ed65c6d610f0f8edd23742efbe5bdc7e5119"
const payload = req.body
const sig = req.headers['stripe-signature'];
//matching
let event
try{
event = stripe.webhooks.constructEvent(payload,sig,signingsecret)
} catch(e){
console.log("Attention PIYUSH WEBHOOK ERROR (line 235)" + e);
res.status(400).json({success: false});
return
}
//if successfull i.e no error
res.status(200).json({success:true})
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} was successful! hoooorrrryaaaaay!!!!!!!!!`);
res.json("PaymentIntent for ${paymentIntent.amount} was successful! hoooorrrryaaaaay!!!!!!!!!")
// Then define and call a method to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
case 'customer.subscription.created':
const subscription_created = event.data.object;
console.log("Subscription Created successfully hoooorrrryaaaaay!!!!!!!!!")
res.json("PaymentIntent for ${paymentIntent.amount} was successful! hoooorrrryaaaaay!!!!!!!!!")
break;
case 'payment_method.attached':
const paymentMethod = event.data.object;
console.log("payment method webhook triggered")
// Then define and call a method to handle the successful attachment of a PaymentMethod.
// handlePaymentMethodAttached(paymentMethod);
break;
case 'checkout.session.async_payment_failed':
const checkoutSessionAsyncPaymentFailed = event.data.object;
console.log("checkout session payment failed");
// Then define and call a function to handle the event checkout.session.async_payment_failed
break;
case 'checkout.session.async_payment_succeeded':
const checkoutSessionAsyncPaymentSucceeded = event.data.object;
console.log("checkout session payment succeeded");
// Then define and call a function to handle the event checkout.session.async_payment_succeeded
break;
default:
// Unexpected event type
// console.log(`Unhandled event type ${event.type}.`);
console.log('Unhandled event type');
}
})
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({extended:false}));
app.use(require('body-parser').text({type: '*/*'}));
app.post('/checkout', async (req, res) => {
const user = req.body;
try {
console.log("new request------------------------------------------------------->")
const session = await stripe.checkout.sessions.create({
line_items: [
{
price: user.id,
quantity: 1,
},
],
mode: 'subscription',
success_url: `http://localhost:3000/success`,
cancel_url: `http://localhost:3000/cancel`,
});
res.json({ url: session.url });
} catch (err) {
console.log(err);
res.status(500).json({ error: 'An error occurred' });
}
});
app.listen(port, ()=>{
console.log(`Server running successfully on port no. ${port}`);
})
So, everything is working as expected, webhooks are functioning. I just want to send a response to the client informing whether the payment was successfull or not
I tried finding answer to my question but instead ended up getting more confused