I'm attempting to retrieve the total order amount on a Stripe charge. It's different for every order. I need this value for Google Ads Dynamic conversions. My Question: How to I retrieve/return the order value after a payment?
//Stripe Payment Backend
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
line_items: [
{
// Provide the exact Price ID (for example, pr_1234) of the product you want to sell
price: 'price_mypriceID',
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/dashboard?success=true`,
cancel_url: `${YOUR_DOMAIN}/dashboard?canceled=true`,
});
res.json({url: session.url})
});
This code runs on a successful payment, triggering a Google Ads Conversion.
if (location == "?success=true"){
window.gtag('config', 'AW-myaccount');
window.gtag('event', 'conversion', {'send_to': 'AW-myaccount',
'value': {needToReturnDynamicValueHere}, <--------- This
'currency': 'USD'
});
}, [location])
Nearly a year later I've figured this out:
On the success item below add &session_id={CHECKOUT_SESSION_ID}
app.post('/create-checkout-payWithCourse', async (req, res) => {
const session = await stripe.checkout.sessions.create({
line_items: [
{
price: 'price_ID',
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/?success=true&session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${YOUR_DOMAIN}/?canceled=true`,
});
res.json({ url: session.url });
});
Then on your backend add a new route as shown below:
app.get('/retrieve-session', async (req, res) => {
const { session_id } = req.query;
try {
const session = await stripe.checkout.sessions.retrieve(session_id);
res.json(session);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to retrieve session data from Stripe' });
}
});
Then on the front end:
if (window.location.href.includes("success=true")) {
const sessionID = getParameterByName('session_id');
// Retrieve the session from your server
const response = await fetch(`/retrieve-session?session_id=${sessionID}`);
const sessionData = await response.json();
if (sessionData) {
console.log(sessionData); // Log the entire sessionData object to inspect its structure
if (sessionData.amount_total) {
const dynamicAmount = sessionData.amount_total / 100; // Convert amount from cents to dollars
console.log(dynamicAmount);
}
}