v1.1.0.0
StocketBase
- <?php
-
- declare(strict_types=1);
-
- require_once __DIR__ . '/includes/config.php';
- require_once __DIR__ . '/includes/database.php';
- require_once __DIR__ . '/includes/user-auth.php';
- require_once __DIR__ . '/includes/csrf.php';
- require_once __DIR__ . '/includes/language.php';
- require_once __DIR__ . '/includes/site-front.php';
- require_once __DIR__ . '/includes/cart.php';
- require_once __DIR__ . '/includes/currency.php';
- require_once __DIR__ . '/includes/shop.php';
- require_once __DIR__ . '/includes/countries.php';
- require_once __DIR__ . '/includes/orders.php';
-
- if (is_file(__DIR__ . '/includes/payments/stripe-client.php')) {
- require_once __DIR__ . '/includes/payments/stripe-client.php';
- }
- if (is_file(__DIR__ . '/includes/payments/polar-client.php')) {
- require_once __DIR__ . '/includes/payments/polar-client.php';
- }
-
- UserAuth::boot();
- Cart::boot();
-
- $db = Database::site();
- $usersDb = Database::users();
- $settings = SiteFront::settings();
-
- function checkoutBaseUrl(): string
- {
- return rtrim((string) Config::get('APP_URL', ''), '/') . Config::get('APP_BASE_PATH', '');
- }
-
- function checkoutGenerateOrderNumber(PDO $usersDb): string
- {
- do {
- $candidate = 'ORD-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));
- $statement = $usersDb->prepare('SELECT id FROM orders WHERE order_number = :n LIMIT 1');
- $statement->execute(['n' => $candidate]);
- } while ($statement->fetch());
-
- return $candidate;
- }
-
- function checkoutText(string $value, int $max): string
- {
- $value = trim((string) preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $value));
-
- return mb_substr($value, 0, $max);
- }
-
- $isSubmit = $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'submit_order';
- $requestProductId = (int) ($_REQUEST['product_id'] ?? 0);
- $mode = $requestProductId > 0 ? 'single' : 'cart';
- $provider = (string) ($_REQUEST['provider'] ?? $settings['payment_provider']);
- if (!in_array($provider, ['stripe', 'polar'], true)) {
- $provider = 'stripe';
- }
- if ($provider === 'polar' && ($settings['store_category'] ?? 'general') !== 'saas') {
- $provider = 'stripe';
- }
-
- $errorMessage = null;
- $fieldErrors = [];
- $singleProduct = null;
-
- if ($isSubmit && !Csrf::verify($_POST['csrf_token'] ?? null)) {
- $isSubmit = false;
- $errorMessage = Language::get('form_security_failed', 'Security check failed, please try again.');
- }
-
- if ($mode === 'single') {
- $statement = $db->prepare("SELECT * FROM products WHERE id = :id AND status = 'published' LIMIT 1");
- $statement->execute(['id' => $requestProductId]);
- $singleProduct = $statement->fetch();
-
- if (!$singleProduct) {
- http_response_code(404);
- $pageTitle = Language::get('page_title_not_found', 'Not found') . ' - ' . $settings['site_name'];
- require __DIR__ . '/includes/front-header.php';
- echo '<p>' . htmlspecialchars(Language::get('product_not_found', 'Product not found.')) . '</p>';
- require __DIR__ . '/includes/front-footer.php';
- exit;
- }
-
- $singleIsAllowed = ($settings['pricing_model'] ?? 'per_product') === 'subscription' || $provider === 'polar';
- if (!$singleIsAllowed) {
- header('Location: ' . SiteFront::productUrl((string) $singleProduct['slug']));
- exit;
- }
- } elseif (Cart::isEmpty()) {
- header('Location: cart.php');
- exit;
- }
-
- $loggedInCustomer = UserAuth::user();
-
- if ($loggedInCustomer === null && ($mode === 'single' || ($settings['require_account_to_purchase'] ?? '0') === '1')) {
- $checkoutReturnTo = 'checkout.php';
- if ($mode === 'single') {
- $checkoutReturnTo .= '?product_id=' . $requestProductId . ($provider === 'polar' ? '&provider=polar' : '');
- }
- header('Location: user-login.php?redirect=' . urlencode($checkoutReturnTo));
- exit;
- }
-
- if ($isSubmit && $mode === 'single') {
- $customerEmail = $loggedInCustomer['email'] ?? trim((string) ($_POST['email'] ?? ''));
- if ($customerEmail === '' || !filter_var($customerEmail, FILTER_VALIDATE_EMAIL)) {
- $errorMessage = Language::get('checkout_error_email', 'Please provide a valid email address.');
- } else {
- $productCurrency = (string) ($singleProduct['currency'] ?: $settings['store_currency']);
- $billingInterval = (string) ($singleProduct['billing_interval'] ?: 'month');
- $successUrl = checkoutBaseUrl() . '/order-confirmation.php?session_id={CHECKOUT_SESSION_ID}';
- $cancelUrl = checkoutBaseUrl() . SiteFront::productUrl((string) $singleProduct['slug']);
- $metadata = ['product_id' => (string) $singleProduct['id'], 'checkout_kind' => 'subscription'];
- if ($loggedInCustomer !== null) {
- $metadata['user_account_id'] = (string) $loggedInCustomer['id'];
- }
-
- if ($provider === 'polar') {
- if (!class_exists('PolarClient')) {
- $errorMessage = Language::get('checkout_error_polar_config', 'Polar checkout is not configured yet. Please try again later.');
- } else {
- $polarProductId = (string) ($singleProduct['polar_product_id'] ?? '');
- if ($polarProductId === '') {
- $errorMessage = Language::get('checkout_error_polar_product', 'This product is not linked to a Polar plan yet.');
- } else {
- $session = (new PolarClient())->createCheckoutSession($polarProductId, $successUrl, $customerEmail, $metadata);
- if (is_array($session) && !empty($session['url'])) {
- header('Location: ' . $session['url']);
- exit;
- }
- $errorMessage = Language::get('checkout_error_polar_start', 'Could not start Polar checkout. Please try again.');
- }
- }
- } else {
- if (!class_exists('StripeClient')) {
- $errorMessage = Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.');
- } elseif (empty($singleProduct['price_cents'])) {
- $errorMessage = Language::get('checkout_error_no_price', 'This product does not have a price configured.');
- } else {
- $isOneTime = $billingInterval === 'one_time';
- $lineItems = [[
- 'name' => (string) $singleProduct['title'],
- 'unit_amount_cents' => (int) $singleProduct['price_cents'],
- 'currency' => strtolower($productCurrency),
- 'quantity' => 1,
- 'recurring_interval' => $isOneTime ? null : ($billingInterval === 'year' ? 'year' : 'month'),
- ]];
- if ($isOneTime) {
- $metadata['checkout_kind'] = 'one_time';
- }
-
- $session = (new StripeClient())->createCheckoutSession($lineItems, $isOneTime ? 'payment' : 'subscription', $successUrl, $cancelUrl, $customerEmail, $metadata);
- if (is_array($session) && !empty($session['url'])) {
- header('Location: ' . $session['url']);
- exit;
- }
- $errorMessage = Language::get('checkout_error_stripe_start', 'Could not start the payment. Please try again.');
- }
- }
- }
- }
-
- $savedAddresses = [];
- if ($loggedInCustomer !== null) {
- try {
- $addressStatement = $usersDb->prepare('SELECT * FROM user_addresses WHERE user_account_id = :id ORDER BY is_default_shipping DESC, updated_at DESC LIMIT 20');
- $addressStatement->execute(['id' => (int) $loggedInCustomer['id']]);
- $savedAddresses = $addressStatement->fetchAll();
- } catch (PDOException $exception) {
- $savedAddresses = [];
- }
- }
-
- $addressFields = ['name', 'address_line1', 'address_line2', 'city', 'region', 'postal_code', 'country'];
- $formValues = [
- 'email' => $loggedInCustomer['email'] ?? '',
- 'shipping_phone' => (string) ($loggedInCustomer['phone'] ?? ''),
- 'billing_same_as_shipping' => '1',
- 'billing_company' => '',
- 'billing_tax_id' => '',
- 'wants_invoice' => '0',
- 'shipping_method' => '',
- 'payment_method' => '',
- 'customer_note' => '',
- 'accept_terms' => '0',
- 'save_address' => $loggedInCustomer !== null && empty($savedAddresses) ? '1' : '0',
- ];
- foreach ($addressFields as $field) {
- $formValues['shipping_' . $field] = '';
- $formValues['billing_' . $field] = '';
- }
-
- $defaultShipping = null;
- $defaultBilling = null;
- foreach ($savedAddresses as $savedAddress) {
- if ($defaultShipping === null && (int) $savedAddress['is_default_shipping'] === 1) {
- $defaultShipping = $savedAddress;
- }
- if ($defaultBilling === null && (int) $savedAddress['is_default_billing'] === 1) {
- $defaultBilling = $savedAddress;
- }
- }
- $defaultShipping ??= $savedAddresses[0] ?? null;
- $fillFromAddress = static function (array &$values, string $prefix, array $address): void {
- $values[$prefix . '_name'] = (string) $address['full_name'];
- $values[$prefix . '_address_line1'] = (string) $address['address_line1'];
- $values[$prefix . '_address_line2'] = (string) ($address['address_line2'] ?? '');
- $values[$prefix . '_city'] = (string) $address['city'];
- $values[$prefix . '_region'] = (string) ($address['region'] ?? '');
- $values[$prefix . '_postal_code'] = (string) $address['postal_code'];
- $values[$prefix . '_country'] = (string) $address['country'];
- };
- if ($defaultShipping !== null) {
- $fillFromAddress($formValues, 'shipping', $defaultShipping);
- if (!empty($defaultShipping['phone'])) {
- $formValues['shipping_phone'] = (string) $defaultShipping['phone'];
- }
- }
- if ($defaultBilling !== null && $defaultShipping !== null && (int) $defaultBilling['id'] !== (int) $defaultShipping['id']) {
- $fillFromAddress($formValues, 'billing', $defaultBilling);
- $formValues['billing_same_as_shipping'] = '0';
- }
- $invoiceSource = $defaultBilling ?? $defaultShipping;
- if ($invoiceSource !== null && (!empty($invoiceSource['company']) || !empty($invoiceSource['tax_id']))) {
- $formValues['billing_company'] = (string) ($invoiceSource['company'] ?? '');
- $formValues['billing_tax_id'] = (string) ($invoiceSource['tax_id'] ?? '');
- $formValues['wants_invoice'] = '1';
- }
-
- $countryOptions = Shop::countryOptions();
- if ($formValues['shipping_country'] === '' && count($countryOptions) === 1) {
- $formValues['shipping_country'] = (string) array_key_first($countryOptions);
- }
- if ($formValues['shipping_country'] === '') {
- $storeCountry = strtoupper(trim(Shop::setting('shop_default_country', '')));
- if (isset($countryOptions[$storeCountry])) {
- $formValues['shipping_country'] = $storeCountry;
- }
- }
-
- $termsUrl = Shop::termsUrl();
- $privacyUrl = Shop::privacyUrl();
- $phoneMode = Shop::phoneFieldMode();
-
- if ($isSubmit && $mode === 'cart') {
- foreach ($formValues as $field => $default) {
- if (in_array($field, ['billing_same_as_shipping', 'wants_invoice', 'accept_terms', 'save_address'], true)) {
- $formValues[$field] = ($_POST[$field] ?? '') === '1' ? '1' : '0';
- continue;
- }
- $formValues[$field] = checkoutText((string) ($_POST[$field] ?? ''), $field === 'customer_note' ? 2000 : 190);
- }
- $formValues['shipping_country'] = strtoupper(substr($formValues['shipping_country'], 0, 2));
- $formValues['billing_country'] = strtoupper(substr($formValues['billing_country'], 0, 2));
- if ($loggedInCustomer !== null) {
- $formValues['email'] = (string) $loggedInCustomer['email'];
- }
-
- $items = Cart::items();
- if (empty($items)) {
- header('Location: cart.php');
- exit;
- }
-
- $requiresShipping = Cart::requiresShipping($items);
- $sameAsShipping = $requiresShipping && $formValues['billing_same_as_shipping'] === '1';
- $customerEmail = (string) $formValues['email'];
- $itemCurrencies = array_unique(array_map(static fn(array $item): string => strtoupper((string) $item['currency']), $items));
- $stockProblems = Orders::stockProblems($items);
-
- if (count($itemCurrencies) > 1) {
- $errorMessage = Language::get('checkout_error_currencies', 'Your cart contains products priced in different currencies. Please check out products in one currency at a time.');
- } elseif (!empty($stockProblems)) {
- $errorMessage = Language::get('checkout_error_stock', 'Some products are no longer available in the quantity you chose:') . ' ' . implode(', ', $stockProblems);
- }
-
- if ($customerEmail === '' || !filter_var($customerEmail, FILTER_VALIDATE_EMAIL)) {
- $fieldErrors['email'] = Language::get('checkout_error_email', 'Please provide a valid email address.');
- }
-
- if ($requiresShipping) {
- foreach (['shipping_name', 'shipping_address_line1', 'shipping_city', 'shipping_postal_code'] as $requiredField) {
- if ($formValues[$requiredField] === '') {
- $fieldErrors[$requiredField] = Language::get('checkout_error_required', 'This field is required.');
- }
- }
- if (!Shop::isCountryAllowed($formValues['shipping_country'])) {
- $fieldErrors['shipping_country'] = Language::get('checkout_error_country', 'We do not ship to this country.');
- }
- if ($phoneMode === 'required' && $formValues['shipping_phone'] === '') {
- $fieldErrors['shipping_phone'] = Language::get('checkout_error_required', 'This field is required.');
- }
- }
-
- $needsBillingAddress = !$sameAsShipping && ($formValues['wants_invoice'] === '1' || $requiresShipping);
- if ($needsBillingAddress) {
- foreach (['billing_name', 'billing_address_line1', 'billing_city', 'billing_postal_code'] as $requiredField) {
- if ($formValues[$requiredField] === '') {
- $fieldErrors[$requiredField] = Language::get('checkout_error_required', 'This field is required.');
- }
- }
- if (!Countries::isValid($formValues['billing_country'])) {
- $fieldErrors['billing_country'] = Language::get('checkout_error_required', 'This field is required.');
- }
- }
-
- if ($termsUrl !== '' && $formValues['accept_terms'] !== '1') {
- $fieldErrors['accept_terms'] = Language::get('checkout_error_terms', 'Please accept the terms to place your order.');
- }
-
- $cartCurrency = Cart::currency();
- $appliedCode = Cart::appliedDiscountCode();
- $discount = $appliedCode !== null ? Cart::findDiscount($appliedCode, $cartCurrency) : null;
- if ($appliedCode !== null && $discount === null) {
- Cart::setDiscountCode(null);
- $appliedCode = null;
- }
-
- $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], $formValues['payment_method']);
- if ($requiresShipping && !isset($fieldErrors['shipping_country'])) {
- if (empty($quote['shipping_options']) && !empty(Shop::shippingMethods())) {
- $fieldErrors['shipping_country'] = Language::get('checkout_error_no_shipping', 'There is no delivery option for this country.');
- } elseif (!empty($quote['shipping_options']) && $quote['shipping_method'] === null) {
- $fieldErrors['shipping_method'] = Language::get('checkout_error_shipping_method', 'Please choose how you want it delivered.');
- }
- }
-
- $paymentMethods = Shop::paymentMethods($requiresShipping, $quote['shipping_method']);
- $paymentMethod = $formValues['payment_method'];
- if ($quote['total_cents'] === 0) {
- $paymentMethod = 'free';
- $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], 'free');
- } elseif (empty($paymentMethods)) {
- $errorMessage ??= Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.');
- } elseif (!isset($paymentMethods[$paymentMethod])) {
- if (count($paymentMethods) === 1) {
- $paymentMethod = (string) array_key_first($paymentMethods);
- $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], $paymentMethod);
- } else {
- $fieldErrors['payment_method'] = Language::get('checkout_error_payment_method', 'Please choose how you want to pay.');
- }
- }
-
- if ($paymentMethod === 'card' && !class_exists('StripeClient')) {
- $errorMessage ??= Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.');
- }
-
- if ($errorMessage === null && !empty($fieldErrors)) {
- $errorMessage = Language::get('checkout_error_fields', 'Please check the highlighted fields.');
- }
-
- if ($errorMessage === null) {
- $shippingAddress = [];
- foreach ($addressFields as $field) {
- $shippingAddress[$field] = $requiresShipping ? $formValues['shipping_' . $field] : '';
- }
- $billingAddress = [];
- foreach ($addressFields as $field) {
- $billingAddress[$field] = $sameAsShipping ? $shippingAddress[$field] : ($needsBillingAddress ? $formValues['billing_' . $field] : '');
- }
- if (!$sameAsShipping && !$needsBillingAddress) {
- $billingAddress['name'] = $formValues['billing_name'];
- }
- $nullable = static fn(string $value): ?string => $value !== '' ? $value : null;
- $orderNumber = checkoutGenerateOrderNumber($usersDb);
- $accessToken = bin2hex(random_bytes(32));
- $wantsInvoice = $formValues['wants_invoice'] === '1';
-
- try {
- $usersDb->beginTransaction();
-
- $insertOrder = $usersDb->prepare(
- "INSERT INTO orders (
- order_number, user_account_id, guest_email, status, provider, payment_method, currency,
- subtotal_cents, discount_cents, shipping_cents, shipping_method, cod_fee_cents, tax_cents, prices_include_tax, tax_rate_bp, total_cents, discount_code,
- shipping_name, shipping_address_line1, shipping_address_line2, shipping_city, shipping_region, shipping_postal_code, shipping_country, shipping_phone,
- billing_same_as_shipping, billing_name, billing_company, billing_tax_id, billing_address_line1, billing_address_line2, billing_city, billing_region, billing_postal_code, billing_country,
- customer_note, access_token
- ) VALUES (
- :order_number, :user_account_id, :guest_email, 'pending', :provider, :payment_method, :currency,
- :subtotal_cents, :discount_cents, :shipping_cents, :shipping_method, :cod_fee_cents, :tax_cents, :prices_include_tax, :tax_rate_bp, :total_cents, :discount_code,
- :shipping_name, :shipping_address_line1, :shipping_address_line2, :shipping_city, :shipping_region, :shipping_postal_code, :shipping_country, :shipping_phone,
- :billing_same_as_shipping, :billing_name, :billing_company, :billing_tax_id, :billing_address_line1, :billing_address_line2, :billing_city, :billing_region, :billing_postal_code, :billing_country,
- :customer_note, :access_token
- )"
- );
- $insertOrder->execute([
- 'order_number' => $orderNumber,
- 'user_account_id' => $loggedInCustomer['id'] ?? null,
- 'guest_email' => $customerEmail,
- 'provider' => $paymentMethod === 'card' ? 'stripe' : ($paymentMethod === 'free' ? 'free' : 'manual'),
- 'payment_method' => $paymentMethod,
- 'currency' => $cartCurrency,
- 'subtotal_cents' => $quote['subtotal_cents'],
- 'discount_cents' => $quote['discount_cents'],
- 'shipping_cents' => $quote['shipping_cents'],
- 'shipping_method' => $quote['shipping_method'] !== null ? mb_substr((string) $quote['shipping_method']['name'], 0, 160) : null,
- 'cod_fee_cents' => $quote['cod_fee_cents'],
- 'tax_cents' => $quote['tax_cents'],
- 'prices_include_tax' => $quote['prices_include_tax'] ? 1 : 0,
- 'tax_rate_bp' => $quote['tax_rate_bp'],
- 'total_cents' => $quote['total_cents'],
- 'discount_code' => $discount !== null ? $appliedCode : null,
- 'shipping_name' => $nullable($shippingAddress['name']),
- 'shipping_address_line1' => $nullable($shippingAddress['address_line1']),
- 'shipping_address_line2' => $nullable($shippingAddress['address_line2']),
- 'shipping_city' => $nullable($shippingAddress['city']),
- 'shipping_region' => $nullable($shippingAddress['region']),
- 'shipping_postal_code' => $nullable($shippingAddress['postal_code']),
- 'shipping_country' => $nullable($shippingAddress['country']),
- 'shipping_phone' => $requiresShipping ? $nullable($formValues['shipping_phone']) : null,
- 'billing_same_as_shipping' => $sameAsShipping ? 1 : 0,
- 'billing_name' => $nullable($billingAddress['name']),
- 'billing_company' => $wantsInvoice ? $nullable($formValues['billing_company']) : null,
- 'billing_tax_id' => $wantsInvoice ? $nullable($formValues['billing_tax_id']) : null,
- 'billing_address_line1' => $nullable($billingAddress['address_line1']),
- 'billing_address_line2' => $nullable($billingAddress['address_line2']),
- 'billing_city' => $nullable($billingAddress['city']),
- 'billing_region' => $nullable($billingAddress['region']),
- 'billing_postal_code' => $nullable($billingAddress['postal_code']),
- 'billing_country' => Countries::isValid($billingAddress['country']) ? $billingAddress['country'] : null,
- 'customer_note' => $nullable($formValues['customer_note']),
- 'access_token' => $accessToken,
- ]);
- $orderId = (int) $usersDb->lastInsertId();
-
- $insertItem = $usersDb->prepare(
- "INSERT INTO order_items (order_id, product_id, variant_id, product_title_snapshot, variant_name_snapshot, unit_price_cents, quantity, total_cents)
- VALUES (:order_id, :product_id, :variant_id, :title, :variant_name, :unit_price_cents, :quantity, :total_cents)"
- );
- foreach ($items as $item) {
- $insertItem->execute([
- 'order_id' => $orderId,
- 'product_id' => $item['product_id'],
- 'variant_id' => $item['variant_id'],
- 'title' => $item['title'],
- 'variant_name' => $item['variant_name'],
- 'unit_price_cents' => $item['unit_price_cents'],
- 'quantity' => $item['quantity'],
- 'total_cents' => $item['total_cents'],
- ]);
- }
-
- $usersDb->prepare("INSERT INTO order_status_history (order_id, status, note) VALUES (:order_id, 'pending', :note)")
- ->execute(['order_id' => $orderId, 'note' => 'Order placed · ' . Shop::paymentLabel($paymentMethod)]);
-
- $usersDb->commit();
- } catch (Throwable $exception) {
- if ($usersDb->inTransaction()) {
- $usersDb->rollBack();
- }
- error_log('StocketBase: could not create order: ' . $exception->getMessage());
- $orderId = null;
- }
-
- if ($orderId === null) {
- $errorMessage = Language::get('checkout_error_order', 'Could not create your order. Please try again.');
- } else {
- if (!isset($_SESSION['checkout_order_ids']) || !is_array($_SESSION['checkout_order_ids'])) {
- $_SESSION['checkout_order_ids'] = [];
- }
- $_SESSION['checkout_order_ids'][] = $orderId;
- $_SESSION['checkout_order_ids'] = array_slice(array_values(array_unique($_SESSION['checkout_order_ids'])), -20);
-
- if ($loggedInCustomer !== null && $formValues['save_address'] === '1' && $requiresShipping) {
- try {
- $hasDefault = false;
- foreach ($savedAddresses as $savedAddress) {
- if ((int) $savedAddress['is_default_shipping'] === 1) {
- $hasDefault = true;
- }
- }
- $usersDb->prepare(
- 'INSERT INTO user_addresses (user_account_id, full_name, company, tax_id, address_line1, address_line2, city, region, postal_code, country, phone, is_default_shipping, is_default_billing)
- VALUES (:user_id, :full_name, :company, :tax_id, :line1, :line2, :city, :region, :postal_code, :country, :phone, :default_shipping, :default_billing)'
- )->execute([
- 'user_id' => (int) $loggedInCustomer['id'],
- 'full_name' => $shippingAddress['name'],
- 'company' => $wantsInvoice && $sameAsShipping ? $nullable($formValues['billing_company']) : null,
- 'tax_id' => $wantsInvoice && $sameAsShipping ? $nullable($formValues['billing_tax_id']) : null,
- 'line1' => $shippingAddress['address_line1'],
- 'line2' => $nullable($shippingAddress['address_line2']),
- 'city' => $shippingAddress['city'],
- 'region' => $nullable($shippingAddress['region']),
- 'postal_code' => $shippingAddress['postal_code'],
- 'country' => $shippingAddress['country'],
- 'phone' => $nullable($formValues['shipping_phone']),
- 'default_shipping' => $hasDefault ? 0 : 1,
- 'default_billing' => $hasDefault ? 0 : 1,
- ]);
- } catch (Throwable $exception) {
- error_log('StocketBase: could not save the address: ' . $exception->getMessage());
- }
- }
-
- $confirmationUrl = 'order-confirmation.php?order_id=' . $orderId . '&token=' . $accessToken;
-
- if ($paymentMethod === 'free') {
- Orders::markPaid($orderId, ['provider' => 'free'], 'Free order');
- Cart::clear();
- header('Location: ' . $confirmationUrl);
- exit;
- }
-
- if (Shop::isOfflineMethod($paymentMethod)) {
- Orders::reserveStock($orderId);
- $placedOrder = Orders::find($orderId);
- if ($placedOrder !== null) {
- Orders::sendAwaitingPayment($placedOrder, Orders::items($orderId));
- }
- Cart::clear();
- header('Location: ' . $confirmationUrl);
- exit;
- }
-
- $lineItems = [];
- foreach ($items as $item) {
- $lineItems[] = [
- 'name' => $item['title'] . ($item['variant_name'] !== null ? ' — ' . $item['variant_name'] : ''),
- 'unit_amount_cents' => (int) $item['unit_price_cents'],
- 'currency' => strtolower($item['currency']),
- 'quantity' => (int) $item['quantity'],
- ];
- }
- if ($quote['shipping_cents'] > 0) {
- $lineItems[] = [
- 'name' => Language::get('order_shipping_label', 'Shipping') . ($quote['shipping_method'] !== null ? ' — ' . $quote['shipping_method']['name'] : ''),
- 'unit_amount_cents' => (int) $quote['shipping_cents'],
- 'currency' => strtolower($cartCurrency),
- 'quantity' => 1,
- ];
- }
- if (!$quote['prices_include_tax'] && $quote['tax_cents'] > 0) {
- $lineItems[] = [
- 'name' => Shop::taxLabel() . ' ' . Shop::formatRate((int) $quote['tax_rate_bp']),
- 'unit_amount_cents' => (int) $quote['tax_cents'],
- 'currency' => strtolower($cartCurrency),
- 'quantity' => 1,
- ];
- }
-
- $successUrl = checkoutBaseUrl() . '/' . $confirmationUrl . '&session_id={CHECKOUT_SESSION_ID}';
- $cancelUrl = checkoutBaseUrl() . '/cart.php';
- $metadata = ['order_id' => (string) $orderId, 'checkout_kind' => 'order'];
- if ($loggedInCustomer !== null) {
- $metadata['user_account_id'] = (string) $loggedInCustomer['id'];
- }
-
- $stripe = new StripeClient();
- $couponId = null;
- if ($quote['discount_cents'] > 0) {
- $couponId = $stripe->createOneTimeCoupon((int) $quote['discount_cents'], $cartCurrency, Language::get('checkout_discount_name', 'Discount') . ' ' . (string) $appliedCode);
- }
-
- if ($quote['discount_cents'] > 0 && $couponId === null) {
- $errorMessage = Language::get('checkout_error_discount', 'Could not apply your discount at payment. Please try again.');
- } else {
- $session = $stripe->createCheckoutSession($lineItems, 'payment', $successUrl, $cancelUrl, $customerEmail, $metadata, $couponId);
- if (is_array($session) && !empty($session['url'])) {
- $usersDb->prepare('UPDATE orders SET provider_checkout_id = :checkout_id WHERE id = :id')
- ->execute(['checkout_id' => (string) ($session['id'] ?? ''), 'id' => $orderId]);
- header('Location: ' . $session['url']);
- exit;
- }
- $errorMessage = Language::get('checkout_error_stripe_start', 'Could not start the payment. Please try again.');
- }
-
- $usersDb->prepare("UPDATE orders SET status = 'failed' WHERE id = :id AND status = 'pending'")->execute(['id' => $orderId]);
- }
- }
- }
-
- $pageTitle = Language::get('checkout_title', 'Checkout') . ' - ' . $settings['site_name'];
- $pageDescription = '';
- $pageNoindex = true;
-
- require __DIR__ . '/includes/front-header.php';
-
- $fieldError = static function (string $field) use ($fieldErrors): string {
- return isset($fieldErrors[$field]) ? '<span class="checkout-field-error">' . htmlspecialchars($fieldErrors[$field]) . '</span>' : '';
- };
- $invalid = static fn(string $field): string => isset($fieldErrors[$field]) ? ' aria-invalid="true"' : '';
- $value = static fn(string $field): string => htmlspecialchars((string) ($formValues[$field] ?? ''), ENT_QUOTES);
-
- ?>
- <h1 class="article-title"><?= htmlspecialchars(Language::get('checkout_title', 'Checkout')) ?></h1>
-
- <?php foreach (SiteFront::activeAds('checkout') as $checkoutAd): ?>
- <?= SiteFront::renderAd($checkoutAd) ?>
- <?php endforeach; ?>
-
- <?php if ($errorMessage !== null): ?>
- <div class="checkout-alert" role="alert"><?= htmlspecialchars($errorMessage) ?></div>
- <?php endif; ?>
-
- <?php if ($mode === 'single'): ?>
- <?php
- $productCurrency = (string) ($singleProduct['currency'] ?: $settings['store_currency']);
- $billingInterval = (string) ($singleProduct['billing_interval'] ?: 'month');
- ?>
- <div class="checkout-summary">
- <h2><?= htmlspecialchars($singleProduct['title']) ?></h2>
- <p>
- <?= htmlspecialchars(Currency::format((int) $singleProduct['price_cents'], $productCurrency)) ?>
- / <?= htmlspecialchars($billingInterval === 'year' ? Language::get('subscription_per_year', 'year') : Language::get('subscription_per_month', 'month')) ?>
- <?= $provider === 'polar' ? ' · Polar' : ' · Stripe' ?>
- </p>
- </div>
-
- <form method="post" class="checkout-form">
- <?= Csrf::field() ?>
- <input type="hidden" name="action" value="submit_order">
- <input type="hidden" name="product_id" value="<?= (int) $singleProduct['id'] ?>">
- <input type="hidden" name="provider" value="<?= htmlspecialchars($provider, ENT_QUOTES) ?>">
-
- <?php if ($loggedInCustomer === null): ?>
- <label for="email"><?= htmlspecialchars(Language::get('checkout_email_label', 'Email address')) ?></label>
- <input type="email" name="email" id="email" required value="<?= $value('email') ?>">
- <?php endif; ?>
-
- <button type="submit" class="unlock-btn" style="border:none;cursor:pointer;margin-top:16px;">
- <?= $provider === 'polar' ? htmlspecialchars(Language::get('product_subscribe_polar_button', 'Subscribe via Polar')) : htmlspecialchars(Language::get('product_subscribe_button', 'Subscribe')) ?>
- </button>
- </form>
- <?php else: ?>
- <?php
- $items = Cart::items();
- $cartCurrency = Cart::currency();
- $requiresShipping = Cart::requiresShipping($items);
- $appliedCode = Cart::appliedDiscountCode();
- $discount = $appliedCode !== null ? Cart::findDiscount($appliedCode, $cartCurrency) : null;
- $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], $formValues['payment_method']);
- $allShippingMethods = $requiresShipping ? Shop::shippingMethods() : [];
- $paymentMethods = Shop::paymentMethods($requiresShipping, null);
- $selectedPayment = $formValues['payment_method'] !== '' && isset($paymentMethods[$formValues['payment_method']]) ? $formValues['payment_method'] : (string) (array_key_first($paymentMethods) ?? '');
- if ($quote['shipping_method'] === null && !empty($quote['shipping_options']) && !isset($fieldErrors['shipping_method'])) {
- $quote = Shop::quote($items, $discount, (string) $quote['shipping_options'][0]['id'], $formValues['shipping_country'], $formValues['payment_method']);
- }
- $selectedShipping = $quote['shipping_method']['id'] ?? $formValues['shipping_method'];
- $checkoutConfig = [
- 'currency' => $cartCurrency,
- 'decimals' => Currency::decimals($cartCurrency),
- 'goods' => max(0, $quote['subtotal_cents'] - $quote['discount_cents']),
- 'taxRate' => $quote['tax_rate_bp'],
- 'taxInclusive' => $quote['prices_include_tax'],
- 'taxShipping' => Shop::setting('shop_tax_shipping', '1') === '1',
- 'codFee' => max(0, (int) Shop::setting('shop_cod_fee_cents', '0')),
- 'requiresShipping' => $requiresShipping,
- 'methods' => array_map(static fn(array $method): array => [
- 'id' => $method['id'],
- 'price' => (int) $method['price_cents'],
- 'freeOver' => $method['free_over_cents'],
- 'countries' => $method['countries'],
- 'cod' => (bool) $method['cod'],
- ], $allShippingMethods),
- 'codRestricted' => count(array_filter($allShippingMethods, static fn(array $method): bool => !empty($method['cod']))) > 0,
- 'freeLabel' => Language::get('checkout_shipping_free', 'Free'),
- 'sample' => Currency::format(123456, $cartCurrency),
- ];
- ?>
- <form method="post" class="checkout-layout" id="checkout-form" novalidate>
- <?= Csrf::field() ?>
- <input type="hidden" name="action" value="submit_order">
-
- <div class="checkout-main">
- <section class="checkout-section">
- <h2><span class="checkout-step">1</span><?= htmlspecialchars(Language::get('checkout_contact_title', 'Contact')) ?></h2>
- <?php if ($loggedInCustomer === null): ?>
- <label for="email"><?= htmlspecialchars(Language::get('checkout_email_label', 'Email address')) ?></label>
- <input type="email" name="email" id="email" required autocomplete="email" value="<?= $value('email') ?>"<?= $invalid('email') ?>>
- <?= $fieldError('email') ?>
- <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_email_hint', 'We send the order confirmation and any download links here.')) ?>
- <a href="user-login.php?redirect=checkout.php"><?= htmlspecialchars(Language::get('checkout_have_account', 'Have an account? Log in')) ?></a></p>
- <?php else: ?>
- <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_logged_in_as', 'Ordering as')) ?> <strong><?= htmlspecialchars((string) $loggedInCustomer['email']) ?></strong></p>
- <?php endif; ?>
- </section>
-
- <?php if ($requiresShipping): ?>
- <section class="checkout-section">
- <h2><span class="checkout-step">2</span><?= htmlspecialchars(Language::get('checkout_shipping_title', 'Shipping address')) ?></h2>
- <?php if (count($savedAddresses) > 1): ?>
- <label for="saved-address"><?= htmlspecialchars(Language::get('checkout_saved_address', 'Use a saved address')) ?></label>
- <select id="saved-address" data-addresses='<?= htmlspecialchars((string) json_encode(array_map(static fn(array $address): array => [
- 'name' => $address['full_name'], 'address_line1' => $address['address_line1'], 'address_line2' => $address['address_line2'] ?? '',
- 'city' => $address['city'], 'region' => $address['region'] ?? '', 'postal_code' => $address['postal_code'], 'country' => $address['country'], 'phone' => $address['phone'] ?? '',
- ], $savedAddresses), JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'>
- <?php foreach ($savedAddresses as $addressIndex => $savedAddress): ?>
- <option value="<?= (int) $addressIndex ?>"><?= htmlspecialchars(trim(($savedAddress['label'] ? $savedAddress['label'] . ' · ' : '') . $savedAddress['full_name'] . ', ' . $savedAddress['address_line1'] . ', ' . $savedAddress['city'])) ?></option>
- <?php endforeach; ?>
- </select>
- <?php endif; ?>
-
- <label for="shipping_name"><?= htmlspecialchars(Language::get('checkout_full_name', 'Full name')) ?></label>
- <input type="text" name="shipping_name" id="shipping_name" required autocomplete="shipping name" value="<?= $value('shipping_name') ?>"<?= $invalid('shipping_name') ?>>
- <?= $fieldError('shipping_name') ?>
-
- <label for="shipping_country"><?= htmlspecialchars(Language::get('checkout_country_label', 'Country')) ?></label>
- <select name="shipping_country" id="shipping_country" required autocomplete="shipping country"<?= $invalid('shipping_country') ?>>
- <option value=""><?= htmlspecialchars(Language::get('checkout_choose_country', 'Choose a country')) ?></option>
- <?php foreach ($countryOptions as $countryCode => $countryName): ?>
- <option value="<?= htmlspecialchars($countryCode) ?>" <?= $formValues['shipping_country'] === $countryCode ? 'selected' : '' ?>><?= htmlspecialchars($countryName) ?></option>
- <?php endforeach; ?>
- </select>
- <?= $fieldError('shipping_country') ?>
-
- <label for="shipping_address_line1"><?= htmlspecialchars(Language::get('checkout_address_line1', 'Address')) ?></label>
- <input type="text" name="shipping_address_line1" id="shipping_address_line1" required autocomplete="shipping address-line1" value="<?= $value('shipping_address_line1') ?>"<?= $invalid('shipping_address_line1') ?>>
- <?= $fieldError('shipping_address_line1') ?>
- <label for="shipping_address_line2"><?= htmlspecialchars(Language::get('checkout_address_line2', 'Address line 2 (optional)')) ?></label>
- <input type="text" name="shipping_address_line2" id="shipping_address_line2" autocomplete="shipping address-line2" value="<?= $value('shipping_address_line2') ?>">
-
- <div class="checkout-grid">
- <div>
- <label for="shipping_postal_code"><?= htmlspecialchars(Language::get('checkout_postal_code', 'Postal code')) ?></label>
- <input type="text" name="shipping_postal_code" id="shipping_postal_code" required autocomplete="shipping postal-code" value="<?= $value('shipping_postal_code') ?>"<?= $invalid('shipping_postal_code') ?>>
- <?= $fieldError('shipping_postal_code') ?>
- </div>
- <div>
- <label for="shipping_city"><?= htmlspecialchars(Language::get('checkout_city', 'City')) ?></label>
- <input type="text" name="shipping_city" id="shipping_city" required autocomplete="shipping address-level2" value="<?= $value('shipping_city') ?>"<?= $invalid('shipping_city') ?>>
- <?= $fieldError('shipping_city') ?>
- </div>
- </div>
- <label for="shipping_region"><?= htmlspecialchars(Language::get('checkout_region', 'State / Region')) ?></label>
- <input type="text" name="shipping_region" id="shipping_region" autocomplete="shipping address-level1" value="<?= $value('shipping_region') ?>">
-
- <?php if ($phoneMode !== 'hidden'): ?>
- <label for="shipping_phone"><?= htmlspecialchars($phoneMode === 'required' ? Language::get('checkout_phone', 'Phone number') : Language::get('checkout_phone_optional', 'Phone number (optional, for the courier)')) ?></label>
- <input type="tel" name="shipping_phone" id="shipping_phone" autocomplete="tel" <?= $phoneMode === 'required' ? 'required' : '' ?> value="<?= $value('shipping_phone') ?>"<?= $invalid('shipping_phone') ?>>
- <?= $fieldError('shipping_phone') ?>
- <?php endif; ?>
-
- <?php if ($loggedInCustomer !== null): ?>
- <label class="checkout-check"><input type="checkbox" name="save_address" value="1" <?= $formValues['save_address'] === '1' ? 'checked' : '' ?>> <?= htmlspecialchars(Language::get('checkout_save_address', 'Save this address in my account')) ?></label>
- <?php endif; ?>
- </section>
-
- <section class="checkout-section">
- <h2><span class="checkout-step">3</span><?= htmlspecialchars(Language::get('checkout_delivery_title', 'Delivery')) ?></h2>
- <?php if (empty($allShippingMethods)): ?>
- <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_delivery_included', 'Delivery is included in the price.')) ?></p>
- <?php else: ?>
- <div class="checkout-options" id="shipping-options">
- <?php foreach ($allShippingMethods as $method): ?>
- <?php
- $methodCost = (int) $method['price_cents'];
- if ($method['free_over_cents'] !== null && $checkoutConfig['goods'] >= (int) $method['free_over_cents']) {
- $methodCost = 0;
- }
- $methodVisible = empty($method['countries']) || in_array($formValues['shipping_country'], $method['countries'], true);
- ?>
- <label class="checkout-option" data-method="<?= htmlspecialchars($method['id']) ?>" <?= $methodVisible ? '' : 'hidden' ?>>
- <input type="radio" name="shipping_method" value="<?= htmlspecialchars($method['id']) ?>" <?= $selectedShipping === $method['id'] ? 'checked' : '' ?> <?= $methodVisible ? '' : 'disabled' ?>>
- <span class="checkout-option-body">
- <span class="checkout-option-title"><?= htmlspecialchars($method['name']) ?></span>
- <?php if ($method['note'] !== '' || $method['free_over_cents'] !== null): ?>
- <span class="checkout-option-note"><?= htmlspecialchars($method['note']) ?><?= $method['note'] !== '' && $method['free_over_cents'] !== null ? ' · ' : '' ?><?= $method['free_over_cents'] !== null ? htmlspecialchars(str_replace('{amount}', Currency::format((int) $method['free_over_cents'], $cartCurrency), Language::get('checkout_free_over', 'Free from {amount}'))) : '' ?></span>
- <?php endif; ?>
- </span>
- <span class="checkout-option-price" data-price><?= htmlspecialchars($methodCost === 0 ? $checkoutConfig['freeLabel'] : Currency::format($methodCost, $cartCurrency)) ?></span>
- </label>
- <?php endforeach; ?>
- </div>
- <p class="checkout-hint" id="shipping-none" <?= empty($quote['shipping_options']) && $formValues['shipping_country'] !== '' ? '' : 'hidden' ?>><?= htmlspecialchars(Language::get('checkout_error_no_shipping', 'There is no delivery option for this country.')) ?></p>
- <?= $fieldError('shipping_method') ?>
- <?php endif; ?>
- </section>
- <?php endif; ?>
-
- <section class="checkout-section">
- <h2><span class="checkout-step"><?= $requiresShipping ? '4' : '2' ?></span><?= htmlspecialchars(Language::get('checkout_billing_title', 'Billing details')) ?></h2>
- <?php if ($requiresShipping): ?>
- <label class="checkout-check">
- <input type="checkbox" name="billing_same_as_shipping" value="1" id="billing_same_as_shipping" <?= $formValues['billing_same_as_shipping'] === '1' ? 'checked' : '' ?>>
- <?= htmlspecialchars(Language::get('checkout_billing_same', 'Billing address same as shipping')) ?>
- </label>
- <?php endif; ?>
- <label class="checkout-check">
- <input type="checkbox" name="wants_invoice" value="1" id="wants_invoice" <?= $formValues['wants_invoice'] === '1' ? 'checked' : '' ?>>
- <?= htmlspecialchars(Language::get('checkout_wants_invoice', 'I need an invoice for a company')) ?>
- </label>
-
- <div id="invoice-fields" <?= $formValues['wants_invoice'] === '1' ? '' : 'hidden' ?>>
- <div class="checkout-grid">
- <div>
- <label for="billing_company"><?= htmlspecialchars(Language::get('checkout_company', 'Company name')) ?></label>
- <input type="text" name="billing_company" id="billing_company" autocomplete="organization" value="<?= $value('billing_company') ?>">
- </div>
- <div>
- <label for="billing_tax_id"><?= htmlspecialchars(Language::get('checkout_tax_id', 'Tax ID (VAT number)')) ?></label>
- <input type="text" name="billing_tax_id" id="billing_tax_id" value="<?= $value('billing_tax_id') ?>">
- </div>
- </div>
- </div>
-
- <div id="billing-fields" <?= (!$requiresShipping && $formValues['wants_invoice'] === '1') || ($requiresShipping && $formValues['billing_same_as_shipping'] !== '1') ? '' : 'hidden' ?>>
- <label for="billing_name"><?= htmlspecialchars(Language::get('checkout_full_name', 'Full name')) ?></label>
- <input type="text" name="billing_name" id="billing_name" autocomplete="billing name" value="<?= $value('billing_name') ?>"<?= $invalid('billing_name') ?>>
- <?= $fieldError('billing_name') ?>
- <label for="billing_country"><?= htmlspecialchars(Language::get('checkout_country_label', 'Country')) ?></label>
- <select name="billing_country" id="billing_country" autocomplete="billing country"<?= $invalid('billing_country') ?>>
- <option value=""><?= htmlspecialchars(Language::get('checkout_choose_country', 'Choose a country')) ?></option>
- <?php foreach (Countries::all() as $countryCode => $countryName): ?>
- <option value="<?= htmlspecialchars($countryCode) ?>" <?= $formValues['billing_country'] === $countryCode ? 'selected' : '' ?>><?= htmlspecialchars($countryName) ?></option>
- <?php endforeach; ?>
- </select>
- <?= $fieldError('billing_country') ?>
- <label for="billing_address_line1"><?= htmlspecialchars(Language::get('checkout_address_line1', 'Address')) ?></label>
- <input type="text" name="billing_address_line1" id="billing_address_line1" autocomplete="billing address-line1" value="<?= $value('billing_address_line1') ?>"<?= $invalid('billing_address_line1') ?>>
- <?= $fieldError('billing_address_line1') ?>
- <label for="billing_address_line2"><?= htmlspecialchars(Language::get('checkout_address_line2', 'Address line 2 (optional)')) ?></label>
- <input type="text" name="billing_address_line2" id="billing_address_line2" autocomplete="billing address-line2" value="<?= $value('billing_address_line2') ?>">
- <div class="checkout-grid">
- <div>
- <label for="billing_postal_code"><?= htmlspecialchars(Language::get('checkout_postal_code', 'Postal code')) ?></label>
- <input type="text" name="billing_postal_code" id="billing_postal_code" autocomplete="billing postal-code" value="<?= $value('billing_postal_code') ?>"<?= $invalid('billing_postal_code') ?>>
- <?= $fieldError('billing_postal_code') ?>
- </div>
- <div>
- <label for="billing_city"><?= htmlspecialchars(Language::get('checkout_city', 'City')) ?></label>
- <input type="text" name="billing_city" id="billing_city" autocomplete="billing address-level2" value="<?= $value('billing_city') ?>"<?= $invalid('billing_city') ?>>
- <?= $fieldError('billing_city') ?>
- </div>
- </div>
- <label for="billing_region"><?= htmlspecialchars(Language::get('checkout_region', 'State / Region')) ?></label>
- <input type="text" name="billing_region" id="billing_region" autocomplete="billing address-level1" value="<?= $value('billing_region') ?>">
- </div>
- </section>
-
- <section class="checkout-section" id="payment-section" <?= $quote['total_cents'] === 0 ? 'hidden' : '' ?>>
- <h2><span class="checkout-step"><?= $requiresShipping ? '5' : '3' ?></span><?= htmlspecialchars(Language::get('checkout_payment_title', 'Payment')) ?></h2>
- <?php if (empty($paymentMethods)): ?>
- <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.')) ?></p>
- <?php else: ?>
- <div class="checkout-options">
- <?php foreach ($paymentMethods as $methodKey => $methodLabel): ?>
- <label class="checkout-option" data-payment="<?= htmlspecialchars($methodKey) ?>">
- <input type="radio" name="payment_method" value="<?= htmlspecialchars($methodKey) ?>" <?= $selectedPayment === $methodKey ? 'checked' : '' ?>>
- <span class="checkout-option-body">
- <span class="checkout-option-title"><?= htmlspecialchars($methodLabel) ?></span>
- <span class="checkout-option-note"><?= htmlspecialchars(match ($methodKey) {
- 'card' => Language::get('payment_method_card_note', 'Pay securely online. You will be redirected to the payment page.'),
- 'bank_transfer' => Language::get('payment_method_bank_note', 'We send the bank details after you place the order. We ship once the money arrives.'),
- 'cod' => (int) $checkoutConfig['codFee'] > 0
- ? str_replace('{amount}', Currency::format((int) $checkoutConfig['codFee'], $cartCurrency), Language::get('payment_method_cod_fee_note', 'Pay the courier when it arrives. Extra fee: {amount}.'))
- : Language::get('payment_method_cod_note', 'Pay the courier when it arrives.'),
- default => '',
- }) ?></span>
- </span>
- </label>
- <?php endforeach; ?>
- </div>
- <?= $fieldError('payment_method') ?>
- <?php endif; ?>
- </section>
-
- <section class="checkout-section">
- <label for="customer_note"><?= htmlspecialchars(Language::get('checkout_note_label', 'Order note (optional)')) ?></label>
- <textarea name="customer_note" id="customer_note" rows="3" maxlength="2000"><?= $value('customer_note') ?></textarea>
-
- <?php if ($termsUrl !== ''): ?>
- <label class="checkout-check checkout-terms">
- <input type="checkbox" name="accept_terms" value="1" required <?= $formValues['accept_terms'] === '1' ? 'checked' : '' ?><?= $invalid('accept_terms') ?>>
- <span><?= str_replace(
- ['{terms}', '{privacy}'],
- [
- '<a href="' . htmlspecialchars($termsUrl, ENT_QUOTES) . '" target="_blank" rel="noopener">' . htmlspecialchars(Language::get('checkout_terms_link', 'terms of sale')) . '</a>',
- $privacyUrl !== '' ? '<a href="' . htmlspecialchars($privacyUrl, ENT_QUOTES) . '" target="_blank" rel="noopener">' . htmlspecialchars(Language::get('checkout_privacy_link', 'privacy policy')) . '</a>' : htmlspecialchars(Language::get('checkout_privacy_link', 'privacy policy')),
- ],
- htmlspecialchars(Language::get('checkout_accept_terms', 'I accept the {terms} and the {privacy}.'))
- ) ?></span>
- </label>
- <?= $fieldError('accept_terms') ?>
- <?php endif; ?>
- </section>
- </div>
-
- <aside class="checkout-aside">
- <div class="checkout-summary-card">
- <h2><?= htmlspecialchars(Language::get('checkout_summary_title', 'Your order')) ?></h2>
- <ul class="checkout-lines">
- <?php foreach ($items as $item): ?>
- <li>
- <?php if (!empty($item['cover_image_path'])): ?>
- <img src="<?= htmlspecialchars((string) $item['cover_image_path']) ?>" alt="" loading="lazy">
- <?php endif; ?>
- <span class="checkout-line-name"><?= htmlspecialchars($item['title']) ?><?php if ($item['variant_name'] !== null): ?><small><?= htmlspecialchars($item['variant_name']) ?></small><?php endif; ?><small>× <?= (int) $item['quantity'] ?></small></span>
- <span class="checkout-line-price"><?= htmlspecialchars(Currency::format($item['total_cents'], $item['currency'])) ?></span>
- </li>
- <?php endforeach; ?>
- </ul>
- <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_subtotal', 'Subtotal')) ?></span><span><?= htmlspecialchars(Currency::format($quote['subtotal_cents'], $cartCurrency)) ?></span></div>
- <?php if ($quote['discount_cents'] > 0): ?>
- <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_discount', 'Discount')) ?><?= $appliedCode !== null ? ' (' . htmlspecialchars($appliedCode) . ')' : '' ?></span><span>-<?= htmlspecialchars(Currency::format($quote['discount_cents'], $cartCurrency)) ?></span></div>
- <?php endif; ?>
- <?php if ($requiresShipping): ?>
- <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('order_shipping_label', 'Shipping')) ?></span><span id="summary-shipping"><?= htmlspecialchars($quote['shipping_method'] === null && !empty($allShippingMethods) ? '—' : ($quote['shipping_cents'] === 0 ? $checkoutConfig['freeLabel'] : Currency::format($quote['shipping_cents'], $cartCurrency))) ?></span></div>
- <?php endif; ?>
- <div class="cart-summary-row" id="summary-cod-row" <?= $quote['cod_fee_cents'] > 0 ? '' : 'hidden' ?>><span><?= htmlspecialchars(Language::get('order_cod_fee_label', 'Cash on delivery fee')) ?></span><span id="summary-cod"><?= htmlspecialchars(Currency::format($quote['cod_fee_cents'], $cartCurrency)) ?></span></div>
- <?php if ($quote['tax_rate_bp'] > 0): ?>
- <div class="cart-summary-row"><span><?= htmlspecialchars(Shop::taxLabel() . ' ' . Shop::formatRate($quote['tax_rate_bp'])) ?><?= $quote['prices_include_tax'] ? ' (' . htmlspecialchars(Language::get('cart_tax_included', 'included')) . ')' : '' ?></span><span id="summary-tax"><?= htmlspecialchars(Currency::format($quote['tax_cents'], $cartCurrency)) ?></span></div>
- <?php endif; ?>
- <div class="cart-summary-row cart-summary-total"><span><?= htmlspecialchars(Language::get('cart_total', 'Total')) ?></span><span id="summary-total"><?= htmlspecialchars(Currency::format($quote['total_cents'], $cartCurrency)) ?></span></div>
-
- <button type="submit" class="unlock-btn checkout-submit" id="checkout-submit"
- data-label-card="<?= htmlspecialchars(Language::get('checkout_pay_button', 'Continue to payment'), ENT_QUOTES) ?>"
- data-label-offline="<?= htmlspecialchars(Language::get('checkout_place_order', 'Place order'), ENT_QUOTES) ?>">
- <?= htmlspecialchars($quote['total_cents'] === 0 || Shop::isOfflineMethod($selectedPayment) ? Language::get('checkout_place_order', 'Place order') : Language::get('checkout_pay_button', 'Continue to payment')) ?>
- </button>
- <p class="checkout-secure"><?= Icons::icon('lock', 'icon icon-sm') ?><?= htmlspecialchars(Language::get('checkout_secure_note', 'Your details are sent securely.')) ?></p>
- <a href="cart.php" class="checkout-back">← <?= htmlspecialchars(Language::get('checkout_back_to_cart', 'Back to cart')) ?></a>
- </div>
- </aside>
- </form>
-
- <script>
- (function () {
- var config = <?= json_encode($checkoutConfig, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) ?>;
- var form = document.getElementById('checkout-form');
- if (!form) {
- return;
- }
- var format = (function () {
- var sample = config.sample;
- var digits = sample.replace(/[^0-9]/g, '');
- var start = sample.search(/[0-9]/);
- var end = sample.length - sample.split('').reverse().join('').search(/[0-9]/);
- var prefix = sample.slice(0, start);
- var suffix = sample.slice(end);
- var middle = sample.slice(start, end);
- var decimalSep = config.decimals > 0 ? middle.charAt(middle.length - config.decimals - 1) : '';
- var groupMatch = middle.slice(0, middle.length - (config.decimals > 0 ? config.decimals + 1 : 0)).replace(/[0-9]/g, '');
- var groupSep = groupMatch.charAt(0) || '';
- return function (cents) {
- var negative = cents < 0;
- cents = Math.abs(cents);
- var factor = Math.pow(10, config.decimals);
- var whole = Math.floor(cents / factor).toString();
- var fraction = config.decimals > 0 ? (cents % factor).toString().padStart(config.decimals, '0') : '';
- whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, groupSep);
- return (negative ? '-' : '') + prefix + whole + (config.decimals > 0 ? decimalSep + fraction : '') + suffix;
- };
- })();
-
- function selected(name) {
- var input = form.querySelector('input[name="' + name + '"]:checked');
- return input && !input.disabled ? input.value : '';
- }
-
- function computeTax(base) {
- if (config.taxRate <= 0 || base <= 0) {
- return 0;
- }
- if (config.taxInclusive) {
- return base - Math.round(base * 10000 / (10000 + config.taxRate));
- }
- return Math.round(base * config.taxRate / 10000);
- }
-
- function refresh() {
- var country = (form.querySelector('#shipping_country') || {}).value || '';
- var shippingCost = 0;
- var shippingChosen = !config.requiresShipping || config.methods.length === 0;
- var available = 0;
- var chosenMethod = null;
- config.methods.forEach(function (method) {
- var row = form.querySelector('[data-method="' + method.id + '"]');
- if (!row) {
- return;
- }
- var visible = method.countries.length === 0 || method.countries.indexOf(country) !== -1;
- var input = row.querySelector('input');
- row.hidden = !visible;
- input.disabled = !visible;
- if (!visible && input.checked) {
- input.checked = false;
- }
- var cost = method.freeOver !== null && config.goods >= method.freeOver ? 0 : method.price;
- row.querySelector('[data-price]').textContent = cost === 0 ? config.freeLabel : format(cost);
- if (visible) {
- available++;
- }
- if (visible && input.checked) {
- shippingCost = cost;
- shippingChosen = true;
- chosenMethod = method;
- }
- });
- if (config.requiresShipping && config.methods.length > 0 && available === 1 && !shippingChosen) {
- config.methods.forEach(function (method) {
- var row = form.querySelector('[data-method="' + method.id + '"]');
- if (row && !row.hidden) {
- row.querySelector('input').checked = true;
- shippingCost = method.freeOver !== null && config.goods >= method.freeOver ? 0 : method.price;
- shippingChosen = true;
- chosenMethod = method;
- }
- });
- }
- var none = document.getElementById('shipping-none');
- if (none) {
- none.hidden = !(config.requiresShipping && config.methods.length > 0 && country !== '' && available === 0);
- }
-
- var codRow = form.querySelector('[data-payment="cod"]');
- if (codRow) {
- var codAllowed = !config.codRestricted || !chosenMethod || chosenMethod.cod;
- codRow.hidden = !codAllowed;
- codRow.querySelector('input').disabled = !codAllowed;
- if (!codAllowed && codRow.querySelector('input').checked) {
- codRow.querySelector('input').checked = false;
- }
- }
-
- var payment = selected('payment_method');
- var codFee = payment === 'cod' ? config.codFee : 0;
- var taxable = config.goods + (config.taxShipping ? shippingCost + codFee : 0);
- var tax = computeTax(taxable);
- var total = config.goods + shippingCost + codFee + (config.taxInclusive ? 0 : tax);
-
- var shippingCell = document.getElementById('summary-shipping');
- if (shippingCell) {
- shippingCell.textContent = !shippingChosen ? '—' : (shippingCost === 0 ? config.freeLabel : format(shippingCost));
- }
- var codCell = document.getElementById('summary-cod-row');
- if (codCell) {
- codCell.hidden = codFee <= 0;
- document.getElementById('summary-cod').textContent = format(codFee);
- }
- var taxCell = document.getElementById('summary-tax');
- if (taxCell) {
- taxCell.textContent = format(tax);
- }
- document.getElementById('summary-total').textContent = format(total);
-
- var paymentSection = document.getElementById('payment-section');
- if (paymentSection) {
- paymentSection.hidden = total === 0;
- }
- var submit = document.getElementById('checkout-submit');
- submit.textContent = total === 0 || payment === 'bank_transfer' || payment === 'cod' ? submit.dataset.labelOffline : submit.dataset.labelCard;
- }
-
- function toggleBilling() {
- var same = document.getElementById('billing_same_as_shipping');
- var invoice = document.getElementById('wants_invoice');
- var billing = document.getElementById('billing-fields');
- var invoiceFields = document.getElementById('invoice-fields');
- if (invoiceFields) {
- invoiceFields.hidden = !invoice.checked;
- }
- if (billing) {
- billing.hidden = same ? same.checked : !invoice.checked;
- }
- }
-
- var saved = document.getElementById('saved-address');
- if (saved) {
- saved.addEventListener('change', function () {
- var addresses = JSON.parse(saved.dataset.addresses || '[]');
- var address = addresses[parseInt(saved.value, 10)];
- if (!address) {
- return;
- }
- ['name', 'address_line1', 'address_line2', 'city', 'region', 'postal_code', 'country'].forEach(function (field) {
- var input = document.getElementById('shipping_' + field);
- if (input) {
- input.value = address[field] || '';
- }
- });
- var phone = document.getElementById('shipping_phone');
- if (phone && address.phone) {
- phone.value = address.phone;
- }
- refresh();
- });
- }
-
- form.addEventListener('change', function (event) {
- if (event.target.id === 'billing_same_as_shipping' || event.target.id === 'wants_invoice') {
- toggleBilling();
- }
- refresh();
- });
- form.addEventListener('submit', function () {
- var submit = document.getElementById('checkout-submit');
- window.setTimeout(function () {
- submit.disabled = true;
- }, 0);
- });
- toggleBilling();
- refresh();
- })();
- </script>
- <?php endif; ?>
-
- <?php require __DIR__ . '/includes/front-footer.php'; ?>
-