提交 3c90066
在您繼續閱讀之前,僅供參考,我自己學習和編碼來建立我們經營業務所需的內容。因此,請按原樣獲取以下資訊。這是我們自己使用的現實世界的例子嗎?關於共享辦公的黃皮書。當時我們找不到更好的解決方案,所以我為我們的電子商務網站建立了以下內容。
在線銷售單一產品(例如一本書)可以很簡單,直到您遇到國際運費、多種貨幣和不同數量的複雜性 - 特別是因為 Stripe Checkout 默認情況下只允許一種運費。在本文中,我們將介紹如何使用 Netlify Functions 和 Stripe 建立自訂運費計算器來應對這些挑戰。最後,您將擁有一個專為銷售最多三本圖書而定制的可行解決方案,並根據客戶的貨幣(歐元/美元)、數量動態運輸成本,以及位置。
雖然這個範例非常適合我們的需求,但您可以對其進行調整以滿足您自己的要求。請隨時分享您的解決方案、升級或所做的任何改進。
在我們深入之前,請確保您具備以下條件:
讓我們打造無縫結帳體驗:
下面我將介紹前端(HTML 和 JavaScript)和後端(Netlify 函數)元件。
專案應包含下列資料夾和檔案:
/functions - create-checkout-session.js /index.html .env netlify.toml package.json
在 /functions 目錄中建立一個名為 create-checkout-session.js 的新檔案。
/functions - create-checkout-session.js /index.html .env netlify.toml package.json
// functions/create-checkout-session.js // Add Stripe secret key const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); exports.handler = async (event) => { // Parse the order data sent from the frontend const order = JSON.parse(event.body); // Define country groups const euCountries = ['AL', 'AM', 'AT', ...]; // Add the EU countries you ship to const worldCountries = ['AE', 'AR', 'AU', ...]; // Add worldwide countries you ship to let allowedCountries = []; // Payment methods based on currency let paymentMethods = []; // Determine shipping rates and allowed countries if (order.currency === 'EUR') { paymentMethods = ['card', 'sepa_debit', 'ideal', 'bancontact', 'p24', 'eps', 'giropay', 'sofort']; if (order.shippingOption === 'europe-eur') { allowedCountries = euCountries; // Set shipping rate IDs for Europe in EUR order.shippingRate = process.env[`SHIPPING_RATE_EUR_EU_${order.items}`]; } else if (order.shippingOption === 'world-eur') { allowedCountries = worldCountries; // Set shipping rate IDs for World in EUR order.shippingRate = process.env[`SHIPPING_RATE_EUR_W_${order.items}`]; } } else if (order.currency === 'USD') { paymentMethods = ['card']; if (order.shippingOption === 'europe-usd') { allowedCountries = euCountries; // Set shipping rate IDs for Europe in USD order.shippingRate = process.env[`SHIPPING_RATE_USD_EU_${order.items}`]; } else if (order.shippingOption === 'world-usd') { allowedCountries = worldCountries; // Set shipping rate IDs for World in USD order.shippingRate = process.env[`SHIPPING_RATE_USD_W_${order.items}`]; } } // Create the Stripe Checkout session const session = await stripe.checkout.sessions.create({ payment_method_types: paymentMethods, line_items: [ { price: order.priceId, // The price ID of your product quantity: order.items, }, ], mode: 'payment', billing_address_collection: 'auto', shipping_rates: [order.shippingRate], shipping_address_collection: { allowed_countries: allowedCountries, }, success_url: `${process.env.URL}/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${process.env.URL}/cancel`, }); return { statusCode: 200, body: JSON.stringify({ sessionId: session.id, publishableKey: process.env.STRIPE_PUBLISHABLE_KEY, }), }; };
使用您的金鑰初始化 Stripe SDK。
解析前端傳入的訂單資料。
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
exports.handler = async (event) => { const order = JSON.parse(event.body); // Rest of the code... };
根據幣種決定可用的付款方式。
const euCountries = [/* ... */]; const worldCountries = [/* ... */]; let allowedCountries = [];
let paymentMethods = [];
if (order.currency === 'EUR') { paymentMethods = [/* ... */]; if (order.shippingOption === 'europe-eur') { allowedCountries = euCountries; order.shippingRate = process.env[`SHIPPING_RATE_EUR_EU_${order.items}`]; } else if (order.shippingOption === 'world-eur') { allowedCountries = worldCountries; order.shippingRate = process.env[`SHIPPING_RATE_EUR_W_${order.items}`]; } } else if (order.currency === 'USD') { // Similar logic for USD }
以下是與我們的 Netlify 函數互動的 HTML 和 JavaScript 程式碼的簡短範例。
const session = await stripe.checkout.sessions.create({ payment_method_types: paymentMethods, line_items: [/* ... */], mode: 'payment', billing_address_collection: 'auto', shipping_rates: [order.shippingRate], shipping_address_collection: { allowed_countries: allowedCountries, }, success_url: `${process.env.URL}/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${process.env.URL}/cancel`, });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Book Pre-Order</title> <!-- Include any CSS or Meta tags here --> </head> <body> <!-- Book Purchase Section --> <section id="pricing"> <div class="pricing-content"> <!-- Currency Tabs --> <ul class="tabs-menu"> <li id="active_currency_eur" class="current"><a href="#tab-1">Buy in ?? EUR</a></li> <li id="active_currency"><a href="#tab-2">Buy in ?? USD</a></li> </ul> <!-- EUR Tab Content --> <div id="tab-1" class="tab-content"> <h3>1 Print Book</h3> <p>A beautiful, 350 pages book.</p> <p>Price: <span id="book-price-eur">€95</span></p> <!-- Number of Books --> <label for="num-books">Number of Books (Max 3)</label> <select name="num-books" id="num-books" required> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <!-- Shipping Destination --> <label for="shipping-amount-eur">Select Shipping Destination</label> <select name="shipping-amount" id="shipping-amount-eur" required> <optgroup label="Europe €14"> <option value="europe-eur">Austria</option> <option value="europe-eur">Belgium</option> <!-- Add other European countries --> </optgroup> <optgroup label="Worldwide €22"> <option value="world-eur">United States</option> <option value="world-eur">Canada</option> <!-- Add other worldwide countries --> </optgroup> </select> <!-- Checkout Button --> <button id="checkout-button-eur" type="button">PRE-ORDER</button> </div> <!-- USD Tab Content --> <div id="tab-2" class="tab-content"> <h3>1 Print Book</h3> <p>A beautiful, 350 pages book.</p> <p>Price: <span id="book-price-usd"></span></p> <!-- Number of Books --> <label for="num-books-usd">Number of Books (Max 3)</label> <select name="num-books-usd" id="num-books-usd" required> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <!-- Shipping Destination --> <label for="shipping-amount-usd">Select Shipping Destination</label> <select name="shipping-amount" id="shipping-amount-usd" required> <optgroup label="Europe "> <option value="europe-usd">Austria</option> <option value="europe-usd">Belgium</option> <!-- Add other European countries --> </optgroup> <optgroup label="Worldwide "> <option value="world-usd">United States</option> <option value="world-usd">Canada</option> <!-- Add other worldwide countries --> </optgroup> </select> <!-- Checkout Button --> <button id="checkout-button-usd" type="button">PRE-ORDER</button> </div> </div> </section> <!-- Include Stripe.js --> <script src="https://js.stripe.com/v3/"></script> <!-- Include your JavaScript file --> <script src="script.js"></script> </body> </html>
確保在 Stirpe Dashboard 上添加您的產品和運費。
條紋:
在 Netlify 上:
在專案的根目錄中建立一個 .env 檔案並新增環境變數(或在 Netlify UI 上執行,如上所示「站點配置 > 環境變數」):
/functions - create-checkout-session.js /index.html .env netlify.toml package.json
設定 Netlify 在函數中使用環境變數:
// functions/create-checkout-session.js // Add Stripe secret key const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); exports.handler = async (event) => { // Parse the order data sent from the frontend const order = JSON.parse(event.body); // Define country groups const euCountries = ['AL', 'AM', 'AT', ...]; // Add the EU countries you ship to const worldCountries = ['AE', 'AR', 'AU', ...]; // Add worldwide countries you ship to let allowedCountries = []; // Payment methods based on currency let paymentMethods = []; // Determine shipping rates and allowed countries if (order.currency === 'EUR') { paymentMethods = ['card', 'sepa_debit', 'ideal', 'bancontact', 'p24', 'eps', 'giropay', 'sofort']; if (order.shippingOption === 'europe-eur') { allowedCountries = euCountries; // Set shipping rate IDs for Europe in EUR order.shippingRate = process.env[`SHIPPING_RATE_EUR_EU_${order.items}`]; } else if (order.shippingOption === 'world-eur') { allowedCountries = worldCountries; // Set shipping rate IDs for World in EUR order.shippingRate = process.env[`SHIPPING_RATE_EUR_W_${order.items}`]; } } else if (order.currency === 'USD') { paymentMethods = ['card']; if (order.shippingOption === 'europe-usd') { allowedCountries = euCountries; // Set shipping rate IDs for Europe in USD order.shippingRate = process.env[`SHIPPING_RATE_USD_EU_${order.items}`]; } else if (order.shippingOption === 'world-usd') { allowedCountries = worldCountries; // Set shipping rate IDs for World in USD order.shippingRate = process.env[`SHIPPING_RATE_USD_W_${order.items}`]; } } // Create the Stripe Checkout session const session = await stripe.checkout.sessions.create({ payment_method_types: paymentMethods, line_items: [ { price: order.priceId, // The price ID of your product quantity: order.items, }, ], mode: 'payment', billing_address_collection: 'auto', shipping_rates: [order.shippingRate], shipping_address_collection: { allowed_countries: allowedCountries, }, success_url: `${process.env.URL}/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${process.env.URL}/cancel`, }); return { statusCode: 200, body: JSON.stringify({ sessionId: session.id, publishableKey: process.env.STRIPE_PUBLISHABLE_KEY, }), }; };
執行以下命令安裝 Stripe SDK:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
exports.handler = async (event) => { const order = JSON.parse(event.body); // Rest of the code... };
瞧!您已設定自訂運費計算器功能,該功能可根據貨幣、數量和位置動態調整運費。
您可以隨意調整和擴展此設置,以適應您自己的產品和運輸政策。
注意:本文基於預訂/銷售最多三本一本書的真實場景,並演示了一種處理涉及貨幣、數量和位置變量的運輸計算的方法。根據您的具體需求,可能會有更有效的方法。
以上是使用 Stripe 和 Netlify 功能建立自訂運費計算器,以支援多貨幣 (€/$)、數量和位置的詳細內容。更多資訊請關注PHP中文網其他相關文章!