How To Connect Shopify With Stripe Checkout Using External Script?
To implement an external Stripe Checkout script for a Shopify store while bypassing Shopify Payments, you'll need to carefully integrate Stripe’s Checkout flow with Shopify’s cart and order information. Below are the steps to achieve this:
Key Considerations :
Step 1: Create a Custom Payment Button
In the Shopify checkout or cart page, replace the default payment button with a custom one that triggers your external script.
Edit Shopify Theme:
<button id="custom-payment-button" class="btn">Pay with Stripe</button>
Attach an Event Listener:
document.getElementById('custom-payment-button').addEventListener('click', async () => {
const cartData = await fetch('/cart.js').then(res => res.json());
const response = await fetch('https://your-external-server.com/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(cartData),
});
const { checkoutUrl } = await response.json();
window.location.href = checkoutUrl; // Redirect to Stripe Checkout
});
Step 2: External Script for Stripe Checkout
Your external script will:
领英推荐
Sample External Script (Node.js/Express):
const express = require('express');
const stripe = require('stripe')('your-stripe-secret-key');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/checkout', async (req, res) => {
const cartData = req.body; // Received cart data from Shopify
// Prepare Stripe line items
const lineItems = cartData.items.map(item => ({
price_data: {
currency: 'usd',
product_data: {
name: item.title,
},
unit_amount: Math.round(item.price * 100), // Stripe expects the amount in cents
},
quantity: item.quantity,
}));
// Create Stripe Checkout Session
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: lineItems,
mode: 'payment',
success_url: 'https://your-shopify-store.com/success',
cancel_url: 'https://your-shopify-store.com/cancel',
});
res.json({ checkoutUrl: session.url });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Step 3: Handling Post-Payment
Once the payment is successful, Stripe will redirect the user to the success_url. To complete the order in Shopify:
const shopifyAdminUrl = 'https://your-store.myshopify.com/admin/api/2023-01/orders.json';
const orderData = {
order: {
id: cartData.order_id,
financial_status: 'paid',
},
};
await fetch(shopifyAdminUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': 'your-shopify-access-token',
},
body: JSON.stringify(orderData),
});
The above steps will help you connecting the Shopify to external Stripe using Script.
Looking to Build or Upgrade Your E-commerce Store?
?? Contact us today at [email protected]
?? Visit us at: https://w3nuts.co.uk/
Ecommerce with Stripe & Shopify as Easy as Pie ??