如何从导入的booking.js中访问Stripe函数定制Timekit预订组件
Hey there! Let's walk through how to get your Timekit Booking component integrated with Stripe so you can process payments before confirming a booking. The key here is making sure your scripts can talk to each other and intercept the booking flow at the right moment.
1. Get the Script Loading Order Right
First, you need to ensure Stripe loads before your Timekit component and custom script. This way, the Stripe object is available globally when your other code runs. Here's how to structure your script tags:
<!-- Load Stripe first – it attaches to the global window object --> <script src="https://js.stripe.com/v3/"></script> <!-- Load your customized Timekit booking-js --> <script src="/path/to/your/custom-booking.js"></script> <!-- Load your custom logic script last --> <script src="/path/to/your/payment-handler.js"></script>
By loading Stripe first, any subsequent script can access window.Stripe (or just Stripe directly, since it's global).
2. Use Timekit's Event Hooks to Insert Payment Flow
Timekit's booking-js emits events at different stages of the booking process. We'll use the timekit-booking.pre-confirm event to pause the default booking flow, process Stripe payment, and only continue if payment succeeds.
Here's an example of what your custom payment-handler.js might look like:
// Initialize Stripe with your publishable key const stripe = Stripe('your-stripe-publishable-key'); // Optional: Set up Stripe Elements if you need a custom card input const elements = stripe.elements(); const cardElement = elements.create('card'); cardElement.mount('#card-element'); // Listen for the pre-confirm event to intercept booking document.addEventListener('timekit-booking.pre-confirm', async (event) => { // Stop the default booking flow from proceeding immediately event.preventDefault(); // Grab booking details from the event (e.g., total amount, customer info) const bookingData = event.detail; try { // Step 1: Create a payment intent via your backend (critical for security) const paymentIntentResponse = await fetch('/your-backend/create-payment-intent', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: bookingData.totalAmount * 100, // Stripe uses smallest currency unit (e.g., cents) customerEmail: bookingData.customer.email }) }); const { clientSecret } = await paymentIntentResponse.json(); // Step 2: Trigger Stripe's payment confirmation const { error } = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: cardElement, billing_details: { name: bookingData.customer.name, email: bookingData.customer.email } } }); if (error) { // Handle payment failure (show error message to user) alert(`Oops, payment failed: ${error.message}`); } else { // Payment succeeded – resume the Timekit booking flow event.detail.continue(); } } catch (err) { console.error('Error processing payment:', err); alert('Something went wrong with your payment. Please try again.'); } });
Key Notes:
- The
event.preventDefault()stops Timekit from confirming the booking right away. - You must use a backend to create the Stripe payment intent (never generate client secrets client-side – it's a security risk).
- After successful payment,
event.detail.continue()tells Timekit to proceed with confirming the booking.
3. Troubleshooting Common Issues
Stripe is not definederror: Double-check your script loading order – Stripe needs to load first.- Timekit events not firing: Verify you're using the correct event names (refer to Timekit's official documentation for the full list of available hooks).
- Payment intent errors: Ensure your backend is correctly configured to generate valid client secrets and communicate with Stripe's API.
内容的提问来源于stack exchange,提问作者user7896385

