Custom Stripe checkout embedded – listen for user changes in checkout

Hello everyone 🙂 I hope I can find a good developer who would have time to help develop my problem.

I have a problem with integrating custom embedded stripe checkout for my web application.

The problem is that I want to implement parcel locker logic.
Parcel lockers have their own iframe, so based on the user’s selection in the “shipment” radio buttons, a specific modal should be launched, which will contain an iframe map of this specific supplier.

For example, the user selects “DHL Parcel” from the list of available delivery options. Now I need to somehow get a listener that will respond to me that the user has selected a specific option. This is to trigger my modal, which will allow me to select a parcel locker and after selecting it, enter the value of this parcel locker in the custom field.

I already have the logic that allows me to enter the selected parcel machine into the form fields. The main problem is listening for the user’s change in the scope of delivery. Stripe does not allow delving into the query selector of this iframe checkout so I can’t implement any addEventListner.

Checkout.html:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Accept a payment</title>
<meta content="A demo of a payment on Stripe" name="description"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<link href="style.css" rel="stylesheet"/>
<script src="https://js.stripe.com/v3/"></script>
<script defer src="checkout.js"></script>
</head>
<body>
<div id="checkout">
</div>
</body>
</html>
</code>
<code><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Accept a payment</title> <meta content="A demo of a payment on Stripe" name="description"/> <meta content="width=device-width, initial-scale=1" name="viewport"/> <link href="style.css" rel="stylesheet"/> <script src="https://js.stripe.com/v3/"></script> <script defer src="checkout.js"></script> </head> <body> <div id="checkout"> </div> </body> </html> </code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Accept a payment</title>
    <meta content="A demo of a payment on Stripe" name="description"/>
    <meta content="width=device-width, initial-scale=1" name="viewport"/>
    <link href="style.css" rel="stylesheet"/>
    <script src="https://js.stripe.com/v3/"></script>
    <script defer src="checkout.js"></script>
</head>
<body>
<div id="checkout">

</div>
</body>
</html>

Server.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const stripe = require('stripe')('sk_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
const express = require('express');
const app = express();
// Serve static files from the 'public' directory
app.use(express.static('public'));
const YOUR_DOMAIN = 'http://localhost:63342';
app.post('/create-checkout-session', async (req, res) => {
try {
const session = await stripe.checkout.sessions.create({
ui_mode: 'embedded',
payment_method_types: ['card', 'p24', 'blik'],
billing_address_collection: 'auto',
shipping_address_collection: {
allowed_countries: ['PL'],
},
line_items: [
{
// Replace '{{PRICE_ID}}' with your actual Price ID
price: 'price_XXXXXXXXXXX',
quantity: 1,
},
{
// Replace '{{PRICE_ID}}' with your actual Price ID
price: 'price_XXXXXXXXXXX',
quantity: 1,
},
],
phone_number_collection: {
enabled: true,
},
mode: 'payment',
return_url: `${YOUR_DOMAIN}/return.html?session_id={CHECKOUT_SESSION_ID}`,
automatic_tax: { enabled: true },
custom_fields: [
{
key: 'nip',
label: {
type: 'custom',
custom: 'NIP',
},
type: 'text',
},
{
key: 'paczkomat',
label: {
type: 'custom',
custom: 'Paczkomat',
},
type: 'text',
},
],
shipping_options: [
{
shipping_rate_data: {
type: 'fixed_amount',
fixed_amount: {
amount: 2000,
currency: 'pln',
},
display_name: 'Kurier',
delivery_estimate: {
minimum: {
unit: 'business_day',
value: 1,
},
maximum: {
unit: 'business_day',
value: 1,
},
},
},
},
{
shipping_rate_data: {
type: 'fixed_amount',
fixed_amount: {
amount: 2000,
currency: 'pln',
},
display_name: 'Paczkomat InPost',
delivery_estimate: {
minimum: {
unit: 'business_day',
value: 1,
},
maximum: {
unit: 'business_day',
value: 1,
},
},
},
},
{
shipping_rate_data: {
type: 'fixed_amount',
fixed_amount: {
amount: 2000,
currency: 'pln',
},
display_name: 'Paczkomat DHL',
delivery_estimate: {
minimum: {
unit: 'business_day',
value: 1,
},
maximum: {
unit: 'business_day',
value: 1,
},
},
},
},
{
shipping_rate_data: {
type: 'fixed_amount',
fixed_amount: {
amount: 0,
currency: 'pln',
},
display_name: 'Odbiór osobisty',
delivery_estimate: {
minimum: {
unit: 'business_day',
value: 1,
},
maximum: {
unit: 'business_day',
value: 1,
},
},
},
},
],
});
// Ensure the clientSecret is being sent correctly
if (!session.client_secret) {
throw new Error('Failed to retrieve client secret');
}
res.json({ clientSecret: session.client_secret });
} catch (error) {
console.error('Error creating checkout session:', error);
res.status(500).json({ error: error.message });
}
});
app.get('/session-status', async (req, res) => {
try {
const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
res.send({
status: session.status,
customer_email: session.customer_details.email,
});
} catch (error) {
res.status(500).send({error: error.message});
}
});
app.listen(63342, () => console.log('Running on port 63342'));
</code>
<code>const stripe = require('stripe')('sk_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); const express = require('express'); const app = express(); // Serve static files from the 'public' directory app.use(express.static('public')); const YOUR_DOMAIN = 'http://localhost:63342'; app.post('/create-checkout-session', async (req, res) => { try { const session = await stripe.checkout.sessions.create({ ui_mode: 'embedded', payment_method_types: ['card', 'p24', 'blik'], billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['PL'], }, line_items: [ { // Replace '{{PRICE_ID}}' with your actual Price ID price: 'price_XXXXXXXXXXX', quantity: 1, }, { // Replace '{{PRICE_ID}}' with your actual Price ID price: 'price_XXXXXXXXXXX', quantity: 1, }, ], phone_number_collection: { enabled: true, }, mode: 'payment', return_url: `${YOUR_DOMAIN}/return.html?session_id={CHECKOUT_SESSION_ID}`, automatic_tax: { enabled: true }, custom_fields: [ { key: 'nip', label: { type: 'custom', custom: 'NIP', }, type: 'text', }, { key: 'paczkomat', label: { type: 'custom', custom: 'Paczkomat', }, type: 'text', }, ], shipping_options: [ { shipping_rate_data: { type: 'fixed_amount', fixed_amount: { amount: 2000, currency: 'pln', }, display_name: 'Kurier', delivery_estimate: { minimum: { unit: 'business_day', value: 1, }, maximum: { unit: 'business_day', value: 1, }, }, }, }, { shipping_rate_data: { type: 'fixed_amount', fixed_amount: { amount: 2000, currency: 'pln', }, display_name: 'Paczkomat InPost', delivery_estimate: { minimum: { unit: 'business_day', value: 1, }, maximum: { unit: 'business_day', value: 1, }, }, }, }, { shipping_rate_data: { type: 'fixed_amount', fixed_amount: { amount: 2000, currency: 'pln', }, display_name: 'Paczkomat DHL', delivery_estimate: { minimum: { unit: 'business_day', value: 1, }, maximum: { unit: 'business_day', value: 1, }, }, }, }, { shipping_rate_data: { type: 'fixed_amount', fixed_amount: { amount: 0, currency: 'pln', }, display_name: 'Odbiór osobisty', delivery_estimate: { minimum: { unit: 'business_day', value: 1, }, maximum: { unit: 'business_day', value: 1, }, }, }, }, ], }); // Ensure the clientSecret is being sent correctly if (!session.client_secret) { throw new Error('Failed to retrieve client secret'); } res.json({ clientSecret: session.client_secret }); } catch (error) { console.error('Error creating checkout session:', error); res.status(500).json({ error: error.message }); } }); app.get('/session-status', async (req, res) => { try { const session = await stripe.checkout.sessions.retrieve(req.query.session_id); res.send({ status: session.status, customer_email: session.customer_details.email, }); } catch (error) { res.status(500).send({error: error.message}); } }); app.listen(63342, () => console.log('Running on port 63342')); </code>
const stripe = require('stripe')('sk_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
const express = require('express');
const app = express();

// Serve static files from the 'public' directory
app.use(express.static('public'));

const YOUR_DOMAIN = 'http://localhost:63342';

app.post('/create-checkout-session', async (req, res) => {
  try {
    const session = await stripe.checkout.sessions.create({
      ui_mode: 'embedded',
      payment_method_types: ['card', 'p24', 'blik'],
      billing_address_collection: 'auto',
      shipping_address_collection: {
        allowed_countries: ['PL'],
      },
      line_items: [
        {
          // Replace '{{PRICE_ID}}' with your actual Price ID
          price: 'price_XXXXXXXXXXX',
          quantity: 1,
        },
        {
          // Replace '{{PRICE_ID}}' with your actual Price ID
          price: 'price_XXXXXXXXXXX',
          quantity: 1,
        },
      ],
      phone_number_collection: {
        enabled: true,
      },
      mode: 'payment',
      return_url: `${YOUR_DOMAIN}/return.html?session_id={CHECKOUT_SESSION_ID}`,
      automatic_tax: { enabled: true },
      custom_fields: [
        {
          key: 'nip',
          label: {
            type: 'custom',
            custom: 'NIP',
          },
          type: 'text',
        },
        {
          key: 'paczkomat',
          label: {
            type: 'custom',
            custom: 'Paczkomat',
          },
          type: 'text',
        },
      ],
      shipping_options: [
        {
          shipping_rate_data: {
            type: 'fixed_amount',
            fixed_amount: {
              amount: 2000,
              currency: 'pln',
            },
            display_name: 'Kurier',
            delivery_estimate: {
              minimum: {
                unit: 'business_day',
                value: 1,
              },
              maximum: {
                unit: 'business_day',
                value: 1,
              },
            },
          },
        },
        {
          shipping_rate_data: {
            type: 'fixed_amount',
            fixed_amount: {
              amount: 2000,
              currency: 'pln',
            },
            display_name: 'Paczkomat InPost',
            delivery_estimate: {
              minimum: {
                unit: 'business_day',
                value: 1,
              },
              maximum: {
                unit: 'business_day',
                value: 1,
              },
            },
          },
        },
        {
          shipping_rate_data: {
            type: 'fixed_amount',
            fixed_amount: {
              amount: 2000,
              currency: 'pln',
            },
            display_name: 'Paczkomat DHL',
            delivery_estimate: {
              minimum: {
                unit: 'business_day',
                value: 1,
              },
              maximum: {
                unit: 'business_day',
                value: 1,
              },
            },
          },
        },
        {
          shipping_rate_data: {
            type: 'fixed_amount',
            fixed_amount: {
              amount: 0,
              currency: 'pln',
            },
            display_name: 'Odbiór osobisty',
            delivery_estimate: {
              minimum: {
                unit: 'business_day',
                value: 1,
              },
              maximum: {
                unit: 'business_day',
                value: 1,
              },
            },
          },
        },
      ],
    });

    // Ensure the clientSecret is being sent correctly
    if (!session.client_secret) {
      throw new Error('Failed to retrieve client secret');
    }

    res.json({ clientSecret: session.client_secret });
  } catch (error) {
    console.error('Error creating checkout session:', error);
    res.status(500).json({ error: error.message });
  }
});


app.get('/session-status', async (req, res) => {
  try {
    const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
    res.send({
      status: session.status,
      customer_email: session.customer_details.email,
    });
  } catch (error) {
    res.status(500).send({error: error.message});
  }
});

app.listen(63342, () => console.log('Running on port 63342'));

Checkout.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const stripe = Stripe("pk_live_XXXXXXXXXXXX");
initialize();
// Create a Checkout Session
async function initialize() {
const fetchClientSecret = async () => {
try {
const response = await fetch("/create-checkout-session", {
method: "POST",
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
if (!data.clientSecret) {
throw new Error('Client secret not found in the response');
}
return data.clientSecret;
} catch (error) {
console.error('Error fetching client secret:', error);
return undefined; // Ensure that an undefined value is not returned, triggering the error
}
};
const checkout = await stripe.initEmbeddedCheckout({
fetchClientSecret,
});
// Mount Checkout
checkout.mount('#checkout');
// Nasłuchiwanie na zmiany w metodzie dostawy
checkout.on('change', (event) => {
if (event.shippingOption) {
console.log('Wybrana metoda dostawy:', event.shippingOption);
}
});
}
</code>
<code>const stripe = Stripe("pk_live_XXXXXXXXXXXX"); initialize(); // Create a Checkout Session async function initialize() { const fetchClientSecret = async () => { try { const response = await fetch("/create-checkout-session", { method: "POST", }); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); if (!data.clientSecret) { throw new Error('Client secret not found in the response'); } return data.clientSecret; } catch (error) { console.error('Error fetching client secret:', error); return undefined; // Ensure that an undefined value is not returned, triggering the error } }; const checkout = await stripe.initEmbeddedCheckout({ fetchClientSecret, }); // Mount Checkout checkout.mount('#checkout'); // Nasłuchiwanie na zmiany w metodzie dostawy checkout.on('change', (event) => { if (event.shippingOption) { console.log('Wybrana metoda dostawy:', event.shippingOption); } }); } </code>
const stripe = Stripe("pk_live_XXXXXXXXXXXX");

initialize();

// Create a Checkout Session
async function initialize() {
  const fetchClientSecret = async () => {
    try {
      const response = await fetch("/create-checkout-session", {
        method: "POST",
      });

      if (!response.ok) {
        throw new Error('Network response was not ok');
      }

      const data = await response.json();

      if (!data.clientSecret) {
        throw new Error('Client secret not found in the response');
      }

      return data.clientSecret;
    } catch (error) {
      console.error('Error fetching client secret:', error);
      return undefined; // Ensure that an undefined value is not returned, triggering the error
    }
  };

  const checkout = await stripe.initEmbeddedCheckout({
    fetchClientSecret,
  });

  // Mount Checkout
  checkout.mount('#checkout');

  // Nasłuchiwanie na zmiany w metodzie dostawy
  checkout.on('change', (event) => {
    if (event.shippingOption) {
      console.log('Wybrana metoda dostawy:', event.shippingOption);
    }
  });
}

checkout.on(‘change’, (event) not working…

Even if it turns out that I can’t listen for changes in delivery options and do my logic for this, I plan to do multi-step in cart at worst. This means that I will select a delivery option there and possibly a parcel locker from InPost or DHL maps, but then there is another problem, how to pass this information to a custom field called “PARCEL” and immediately set the selected delivery option? The user should no longer be able to change these things (unless they go back to cart) and then click “go to payment” which will again generate a session checkout for me.

I have a lot of ambiguities in my mind, I don’t know how to approach this. I’m implementing Stripe to Webflow, my client has requirements for Polish payment gateways, Webflow doesn’t allow it, I have to use custom checkout. I don’t want to choose another option like Foxy.io or Snipcart.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật