WebOrbiton
v1.1.0.0

StocketBase

1,104 lines · 66.7 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. require_once __DIR__ . '/includes/config.php';
  6. require_once __DIR__ . '/includes/database.php';
  7. require_once __DIR__ . '/includes/user-auth.php';
  8. require_once __DIR__ . '/includes/csrf.php';
  9. require_once __DIR__ . '/includes/language.php';
  10. require_once __DIR__ . '/includes/site-front.php';
  11. require_once __DIR__ . '/includes/cart.php';
  12. require_once __DIR__ . '/includes/currency.php';
  13. require_once __DIR__ . '/includes/shop.php';
  14. require_once __DIR__ . '/includes/countries.php';
  15. require_once __DIR__ . '/includes/orders.php';
  16. ​
  17. if (is_file(__DIR__ . '/includes/payments/stripe-client.php')) {
  18. require_once __DIR__ . '/includes/payments/stripe-client.php';
  19. }
  20. if (is_file(__DIR__ . '/includes/payments/polar-client.php')) {
  21. require_once __DIR__ . '/includes/payments/polar-client.php';
  22. }
  23. ​
  24. UserAuth::boot();
  25. Cart::boot();
  26. ​
  27. $db = Database::site();
  28. $usersDb = Database::users();
  29. $settings = SiteFront::settings();
  30. ​
  31. function checkoutBaseUrl(): string
  32. {
  33. return rtrim((string) Config::get('APP_URL', ''), '/') . Config::get('APP_BASE_PATH', '');
  34. }
  35. ​
  36. function checkoutGenerateOrderNumber(PDO $usersDb): string
  37. {
  38. do {
  39. $candidate = 'ORD-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));
  40. $statement = $usersDb->prepare('SELECT id FROM orders WHERE order_number = :n LIMIT 1');
  41. $statement->execute(['n' => $candidate]);
  42. } while ($statement->fetch());
  43. ​
  44. return $candidate;
  45. }
  46. ​
  47. function checkoutText(string $value, int $max): string
  48. {
  49. $value = trim((string) preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $value));
  50. ​
  51. return mb_substr($value, 0, $max);
  52. }
  53. ​
  54. $isSubmit = $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'submit_order';
  55. $requestProductId = (int) ($_REQUEST['product_id'] ?? 0);
  56. $mode = $requestProductId > 0 ? 'single' : 'cart';
  57. $provider = (string) ($_REQUEST['provider'] ?? $settings['payment_provider']);
  58. if (!in_array($provider, ['stripe', 'polar'], true)) {
  59. $provider = 'stripe';
  60. }
  61. if ($provider === 'polar' && ($settings['store_category'] ?? 'general') !== 'saas') {
  62. $provider = 'stripe';
  63. }
  64. ​
  65. $errorMessage = null;
  66. $fieldErrors = [];
  67. $singleProduct = null;
  68. ​
  69. if ($isSubmit && !Csrf::verify($_POST['csrf_token'] ?? null)) {
  70. $isSubmit = false;
  71. $errorMessage = Language::get('form_security_failed', 'Security check failed, please try again.');
  72. }
  73. ​
  74. if ($mode === 'single') {
  75. $statement = $db->prepare("SELECT * FROM products WHERE id = :id AND status = 'published' LIMIT 1");
  76. $statement->execute(['id' => $requestProductId]);
  77. $singleProduct = $statement->fetch();
  78. ​
  79. if (!$singleProduct) {
  80. http_response_code(404);
  81. $pageTitle = Language::get('page_title_not_found', 'Not found') . ' - ' . $settings['site_name'];
  82. require __DIR__ . '/includes/front-header.php';
  83. echo '<p>' . htmlspecialchars(Language::get('product_not_found', 'Product not found.')) . '</p>';
  84. require __DIR__ . '/includes/front-footer.php';
  85. exit;
  86. }
  87. ​
  88. $singleIsAllowed = ($settings['pricing_model'] ?? 'per_product') === 'subscription' || $provider === 'polar';
  89. if (!$singleIsAllowed) {
  90. header('Location: ' . SiteFront::productUrl((string) $singleProduct['slug']));
  91. exit;
  92. }
  93. } elseif (Cart::isEmpty()) {
  94. header('Location: cart.php');
  95. exit;
  96. }
  97. ​
  98. $loggedInCustomer = UserAuth::user();
  99. ​
  100. if ($loggedInCustomer === null && ($mode === 'single' || ($settings['require_account_to_purchase'] ?? '0') === '1')) {
  101. $checkoutReturnTo = 'checkout.php';
  102. if ($mode === 'single') {
  103. $checkoutReturnTo .= '?product_id=' . $requestProductId . ($provider === 'polar' ? '&provider=polar' : '');
  104. }
  105. header('Location: user-login.php?redirect=' . urlencode($checkoutReturnTo));
  106. exit;
  107. }
  108. ​
  109. if ($isSubmit && $mode === 'single') {
  110. $customerEmail = $loggedInCustomer['email'] ?? trim((string) ($_POST['email'] ?? ''));
  111. if ($customerEmail === '' || !filter_var($customerEmail, FILTER_VALIDATE_EMAIL)) {
  112. $errorMessage = Language::get('checkout_error_email', 'Please provide a valid email address.');
  113. } else {
  114. $productCurrency = (string) ($singleProduct['currency'] ?: $settings['store_currency']);
  115. $billingInterval = (string) ($singleProduct['billing_interval'] ?: 'month');
  116. $successUrl = checkoutBaseUrl() . '/order-confirmation.php?session_id={CHECKOUT_SESSION_ID}';
  117. $cancelUrl = checkoutBaseUrl() . SiteFront::productUrl((string) $singleProduct['slug']);
  118. $metadata = ['product_id' => (string) $singleProduct['id'], 'checkout_kind' => 'subscription'];
  119. if ($loggedInCustomer !== null) {
  120. $metadata['user_account_id'] = (string) $loggedInCustomer['id'];
  121. }
  122. ​
  123. if ($provider === 'polar') {
  124. if (!class_exists('PolarClient')) {
  125. $errorMessage = Language::get('checkout_error_polar_config', 'Polar checkout is not configured yet. Please try again later.');
  126. } else {
  127. $polarProductId = (string) ($singleProduct['polar_product_id'] ?? '');
  128. if ($polarProductId === '') {
  129. $errorMessage = Language::get('checkout_error_polar_product', 'This product is not linked to a Polar plan yet.');
  130. } else {
  131. $session = (new PolarClient())->createCheckoutSession($polarProductId, $successUrl, $customerEmail, $metadata);
  132. if (is_array($session) && !empty($session['url'])) {
  133. header('Location: ' . $session['url']);
  134. exit;
  135. }
  136. $errorMessage = Language::get('checkout_error_polar_start', 'Could not start Polar checkout. Please try again.');
  137. }
  138. }
  139. } else {
  140. if (!class_exists('StripeClient')) {
  141. $errorMessage = Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.');
  142. } elseif (empty($singleProduct['price_cents'])) {
  143. $errorMessage = Language::get('checkout_error_no_price', 'This product does not have a price configured.');
  144. } else {
  145. $isOneTime = $billingInterval === 'one_time';
  146. $lineItems = [[
  147. 'name' => (string) $singleProduct['title'],
  148. 'unit_amount_cents' => (int) $singleProduct['price_cents'],
  149. 'currency' => strtolower($productCurrency),
  150. 'quantity' => 1,
  151. 'recurring_interval' => $isOneTime ? null : ($billingInterval === 'year' ? 'year' : 'month'),
  152. ]];
  153. if ($isOneTime) {
  154. $metadata['checkout_kind'] = 'one_time';
  155. }
  156. ​
  157. $session = (new StripeClient())->createCheckoutSession($lineItems, $isOneTime ? 'payment' : 'subscription', $successUrl, $cancelUrl, $customerEmail, $metadata);
  158. if (is_array($session) && !empty($session['url'])) {
  159. header('Location: ' . $session['url']);
  160. exit;
  161. }
  162. $errorMessage = Language::get('checkout_error_stripe_start', 'Could not start the payment. Please try again.');
  163. }
  164. }
  165. }
  166. }
  167. ​
  168. $savedAddresses = [];
  169. if ($loggedInCustomer !== null) {
  170. try {
  171. $addressStatement = $usersDb->prepare('SELECT * FROM user_addresses WHERE user_account_id = :id ORDER BY is_default_shipping DESC, updated_at DESC LIMIT 20');
  172. $addressStatement->execute(['id' => (int) $loggedInCustomer['id']]);
  173. $savedAddresses = $addressStatement->fetchAll();
  174. } catch (PDOException $exception) {
  175. $savedAddresses = [];
  176. }
  177. }
  178. ​
  179. $addressFields = ['name', 'address_line1', 'address_line2', 'city', 'region', 'postal_code', 'country'];
  180. $formValues = [
  181. 'email' => $loggedInCustomer['email'] ?? '',
  182. 'shipping_phone' => (string) ($loggedInCustomer['phone'] ?? ''),
  183. 'billing_same_as_shipping' => '1',
  184. 'billing_company' => '',
  185. 'billing_tax_id' => '',
  186. 'wants_invoice' => '0',
  187. 'shipping_method' => '',
  188. 'payment_method' => '',
  189. 'customer_note' => '',
  190. 'accept_terms' => '0',
  191. 'save_address' => $loggedInCustomer !== null && empty($savedAddresses) ? '1' : '0',
  192. ];
  193. foreach ($addressFields as $field) {
  194. $formValues['shipping_' . $field] = '';
  195. $formValues['billing_' . $field] = '';
  196. }
  197. ​
  198. $defaultShipping = null;
  199. $defaultBilling = null;
  200. foreach ($savedAddresses as $savedAddress) {
  201. if ($defaultShipping === null && (int) $savedAddress['is_default_shipping'] === 1) {
  202. $defaultShipping = $savedAddress;
  203. }
  204. if ($defaultBilling === null && (int) $savedAddress['is_default_billing'] === 1) {
  205. $defaultBilling = $savedAddress;
  206. }
  207. }
  208. $defaultShipping ??= $savedAddresses[0] ?? null;
  209. $fillFromAddress = static function (array &$values, string $prefix, array $address): void {
  210. $values[$prefix . '_name'] = (string) $address['full_name'];
  211. $values[$prefix . '_address_line1'] = (string) $address['address_line1'];
  212. $values[$prefix . '_address_line2'] = (string) ($address['address_line2'] ?? '');
  213. $values[$prefix . '_city'] = (string) $address['city'];
  214. $values[$prefix . '_region'] = (string) ($address['region'] ?? '');
  215. $values[$prefix . '_postal_code'] = (string) $address['postal_code'];
  216. $values[$prefix . '_country'] = (string) $address['country'];
  217. };
  218. if ($defaultShipping !== null) {
  219. $fillFromAddress($formValues, 'shipping', $defaultShipping);
  220. if (!empty($defaultShipping['phone'])) {
  221. $formValues['shipping_phone'] = (string) $defaultShipping['phone'];
  222. }
  223. }
  224. if ($defaultBilling !== null && $defaultShipping !== null && (int) $defaultBilling['id'] !== (int) $defaultShipping['id']) {
  225. $fillFromAddress($formValues, 'billing', $defaultBilling);
  226. $formValues['billing_same_as_shipping'] = '0';
  227. }
  228. $invoiceSource = $defaultBilling ?? $defaultShipping;
  229. if ($invoiceSource !== null && (!empty($invoiceSource['company']) || !empty($invoiceSource['tax_id']))) {
  230. $formValues['billing_company'] = (string) ($invoiceSource['company'] ?? '');
  231. $formValues['billing_tax_id'] = (string) ($invoiceSource['tax_id'] ?? '');
  232. $formValues['wants_invoice'] = '1';
  233. }
  234. ​
  235. $countryOptions = Shop::countryOptions();
  236. if ($formValues['shipping_country'] === '' && count($countryOptions) === 1) {
  237. $formValues['shipping_country'] = (string) array_key_first($countryOptions);
  238. }
  239. if ($formValues['shipping_country'] === '') {
  240. $storeCountry = strtoupper(trim(Shop::setting('shop_default_country', '')));
  241. if (isset($countryOptions[$storeCountry])) {
  242. $formValues['shipping_country'] = $storeCountry;
  243. }
  244. }
  245. ​
  246. $termsUrl = Shop::termsUrl();
  247. $privacyUrl = Shop::privacyUrl();
  248. $phoneMode = Shop::phoneFieldMode();
  249. ​
  250. if ($isSubmit && $mode === 'cart') {
  251. foreach ($formValues as $field => $default) {
  252. if (in_array($field, ['billing_same_as_shipping', 'wants_invoice', 'accept_terms', 'save_address'], true)) {
  253. $formValues[$field] = ($_POST[$field] ?? '') === '1' ? '1' : '0';
  254. continue;
  255. }
  256. $formValues[$field] = checkoutText((string) ($_POST[$field] ?? ''), $field === 'customer_note' ? 2000 : 190);
  257. }
  258. $formValues['shipping_country'] = strtoupper(substr($formValues['shipping_country'], 0, 2));
  259. $formValues['billing_country'] = strtoupper(substr($formValues['billing_country'], 0, 2));
  260. if ($loggedInCustomer !== null) {
  261. $formValues['email'] = (string) $loggedInCustomer['email'];
  262. }
  263. ​
  264. $items = Cart::items();
  265. if (empty($items)) {
  266. header('Location: cart.php');
  267. exit;
  268. }
  269. ​
  270. $requiresShipping = Cart::requiresShipping($items);
  271. $sameAsShipping = $requiresShipping && $formValues['billing_same_as_shipping'] === '1';
  272. $customerEmail = (string) $formValues['email'];
  273. $itemCurrencies = array_unique(array_map(static fn(array $item): string => strtoupper((string) $item['currency']), $items));
  274. $stockProblems = Orders::stockProblems($items);
  275. ​
  276. if (count($itemCurrencies) > 1) {
  277. $errorMessage = Language::get('checkout_error_currencies', 'Your cart contains products priced in different currencies. Please check out products in one currency at a time.');
  278. } elseif (!empty($stockProblems)) {
  279. $errorMessage = Language::get('checkout_error_stock', 'Some products are no longer available in the quantity you chose:') . ' ' . implode(', ', $stockProblems);
  280. }
  281. ​
  282. if ($customerEmail === '' || !filter_var($customerEmail, FILTER_VALIDATE_EMAIL)) {
  283. $fieldErrors['email'] = Language::get('checkout_error_email', 'Please provide a valid email address.');
  284. }
  285. ​
  286. if ($requiresShipping) {
  287. foreach (['shipping_name', 'shipping_address_line1', 'shipping_city', 'shipping_postal_code'] as $requiredField) {
  288. if ($formValues[$requiredField] === '') {
  289. $fieldErrors[$requiredField] = Language::get('checkout_error_required', 'This field is required.');
  290. }
  291. }
  292. if (!Shop::isCountryAllowed($formValues['shipping_country'])) {
  293. $fieldErrors['shipping_country'] = Language::get('checkout_error_country', 'We do not ship to this country.');
  294. }
  295. if ($phoneMode === 'required' && $formValues['shipping_phone'] === '') {
  296. $fieldErrors['shipping_phone'] = Language::get('checkout_error_required', 'This field is required.');
  297. }
  298. }
  299. ​
  300. $needsBillingAddress = !$sameAsShipping && ($formValues['wants_invoice'] === '1' || $requiresShipping);
  301. if ($needsBillingAddress) {
  302. foreach (['billing_name', 'billing_address_line1', 'billing_city', 'billing_postal_code'] as $requiredField) {
  303. if ($formValues[$requiredField] === '') {
  304. $fieldErrors[$requiredField] = Language::get('checkout_error_required', 'This field is required.');
  305. }
  306. }
  307. if (!Countries::isValid($formValues['billing_country'])) {
  308. $fieldErrors['billing_country'] = Language::get('checkout_error_required', 'This field is required.');
  309. }
  310. }
  311. ​
  312. if ($termsUrl !== '' && $formValues['accept_terms'] !== '1') {
  313. $fieldErrors['accept_terms'] = Language::get('checkout_error_terms', 'Please accept the terms to place your order.');
  314. }
  315. ​
  316. $cartCurrency = Cart::currency();
  317. $appliedCode = Cart::appliedDiscountCode();
  318. $discount = $appliedCode !== null ? Cart::findDiscount($appliedCode, $cartCurrency) : null;
  319. if ($appliedCode !== null && $discount === null) {
  320. Cart::setDiscountCode(null);
  321. $appliedCode = null;
  322. }
  323. ​
  324. $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], $formValues['payment_method']);
  325. if ($requiresShipping && !isset($fieldErrors['shipping_country'])) {
  326. if (empty($quote['shipping_options']) && !empty(Shop::shippingMethods())) {
  327. $fieldErrors['shipping_country'] = Language::get('checkout_error_no_shipping', 'There is no delivery option for this country.');
  328. } elseif (!empty($quote['shipping_options']) && $quote['shipping_method'] === null) {
  329. $fieldErrors['shipping_method'] = Language::get('checkout_error_shipping_method', 'Please choose how you want it delivered.');
  330. }
  331. }
  332. ​
  333. $paymentMethods = Shop::paymentMethods($requiresShipping, $quote['shipping_method']);
  334. $paymentMethod = $formValues['payment_method'];
  335. if ($quote['total_cents'] === 0) {
  336. $paymentMethod = 'free';
  337. $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], 'free');
  338. } elseif (empty($paymentMethods)) {
  339. $errorMessage ??= Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.');
  340. } elseif (!isset($paymentMethods[$paymentMethod])) {
  341. if (count($paymentMethods) === 1) {
  342. $paymentMethod = (string) array_key_first($paymentMethods);
  343. $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], $paymentMethod);
  344. } else {
  345. $fieldErrors['payment_method'] = Language::get('checkout_error_payment_method', 'Please choose how you want to pay.');
  346. }
  347. }
  348. ​
  349. if ($paymentMethod === 'card' && !class_exists('StripeClient')) {
  350. $errorMessage ??= Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.');
  351. }
  352. ​
  353. if ($errorMessage === null && !empty($fieldErrors)) {
  354. $errorMessage = Language::get('checkout_error_fields', 'Please check the highlighted fields.');
  355. }
  356. ​
  357. if ($errorMessage === null) {
  358. $shippingAddress = [];
  359. foreach ($addressFields as $field) {
  360. $shippingAddress[$field] = $requiresShipping ? $formValues['shipping_' . $field] : '';
  361. }
  362. $billingAddress = [];
  363. foreach ($addressFields as $field) {
  364. $billingAddress[$field] = $sameAsShipping ? $shippingAddress[$field] : ($needsBillingAddress ? $formValues['billing_' . $field] : '');
  365. }
  366. if (!$sameAsShipping && !$needsBillingAddress) {
  367. $billingAddress['name'] = $formValues['billing_name'];
  368. }
  369. $nullable = static fn(string $value): ?string => $value !== '' ? $value : null;
  370. $orderNumber = checkoutGenerateOrderNumber($usersDb);
  371. $accessToken = bin2hex(random_bytes(32));
  372. $wantsInvoice = $formValues['wants_invoice'] === '1';
  373. ​
  374. try {
  375. $usersDb->beginTransaction();
  376. ​
  377. $insertOrder = $usersDb->prepare(
  378. "INSERT INTO orders (
  379. order_number, user_account_id, guest_email, status, provider, payment_method, currency,
  380. subtotal_cents, discount_cents, shipping_cents, shipping_method, cod_fee_cents, tax_cents, prices_include_tax, tax_rate_bp, total_cents, discount_code,
  381. shipping_name, shipping_address_line1, shipping_address_line2, shipping_city, shipping_region, shipping_postal_code, shipping_country, shipping_phone,
  382. 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,
  383. customer_note, access_token
  384. ) VALUES (
  385. :order_number, :user_account_id, :guest_email, 'pending', :provider, :payment_method, :currency,
  386. :subtotal_cents, :discount_cents, :shipping_cents, :shipping_method, :cod_fee_cents, :tax_cents, :prices_include_tax, :tax_rate_bp, :total_cents, :discount_code,
  387. :shipping_name, :shipping_address_line1, :shipping_address_line2, :shipping_city, :shipping_region, :shipping_postal_code, :shipping_country, :shipping_phone,
  388. :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,
  389. :customer_note, :access_token
  390. )"
  391. );
  392. $insertOrder->execute([
  393. 'order_number' => $orderNumber,
  394. 'user_account_id' => $loggedInCustomer['id'] ?? null,
  395. 'guest_email' => $customerEmail,
  396. 'provider' => $paymentMethod === 'card' ? 'stripe' : ($paymentMethod === 'free' ? 'free' : 'manual'),
  397. 'payment_method' => $paymentMethod,
  398. 'currency' => $cartCurrency,
  399. 'subtotal_cents' => $quote['subtotal_cents'],
  400. 'discount_cents' => $quote['discount_cents'],
  401. 'shipping_cents' => $quote['shipping_cents'],
  402. 'shipping_method' => $quote['shipping_method'] !== null ? mb_substr((string) $quote['shipping_method']['name'], 0, 160) : null,
  403. 'cod_fee_cents' => $quote['cod_fee_cents'],
  404. 'tax_cents' => $quote['tax_cents'],
  405. 'prices_include_tax' => $quote['prices_include_tax'] ? 1 : 0,
  406. 'tax_rate_bp' => $quote['tax_rate_bp'],
  407. 'total_cents' => $quote['total_cents'],
  408. 'discount_code' => $discount !== null ? $appliedCode : null,
  409. 'shipping_name' => $nullable($shippingAddress['name']),
  410. 'shipping_address_line1' => $nullable($shippingAddress['address_line1']),
  411. 'shipping_address_line2' => $nullable($shippingAddress['address_line2']),
  412. 'shipping_city' => $nullable($shippingAddress['city']),
  413. 'shipping_region' => $nullable($shippingAddress['region']),
  414. 'shipping_postal_code' => $nullable($shippingAddress['postal_code']),
  415. 'shipping_country' => $nullable($shippingAddress['country']),
  416. 'shipping_phone' => $requiresShipping ? $nullable($formValues['shipping_phone']) : null,
  417. 'billing_same_as_shipping' => $sameAsShipping ? 1 : 0,
  418. 'billing_name' => $nullable($billingAddress['name']),
  419. 'billing_company' => $wantsInvoice ? $nullable($formValues['billing_company']) : null,
  420. 'billing_tax_id' => $wantsInvoice ? $nullable($formValues['billing_tax_id']) : null,
  421. 'billing_address_line1' => $nullable($billingAddress['address_line1']),
  422. 'billing_address_line2' => $nullable($billingAddress['address_line2']),
  423. 'billing_city' => $nullable($billingAddress['city']),
  424. 'billing_region' => $nullable($billingAddress['region']),
  425. 'billing_postal_code' => $nullable($billingAddress['postal_code']),
  426. 'billing_country' => Countries::isValid($billingAddress['country']) ? $billingAddress['country'] : null,
  427. 'customer_note' => $nullable($formValues['customer_note']),
  428. 'access_token' => $accessToken,
  429. ]);
  430. $orderId = (int) $usersDb->lastInsertId();
  431. ​
  432. $insertItem = $usersDb->prepare(
  433. "INSERT INTO order_items (order_id, product_id, variant_id, product_title_snapshot, variant_name_snapshot, unit_price_cents, quantity, total_cents)
  434. VALUES (:order_id, :product_id, :variant_id, :title, :variant_name, :unit_price_cents, :quantity, :total_cents)"
  435. );
  436. foreach ($items as $item) {
  437. $insertItem->execute([
  438. 'order_id' => $orderId,
  439. 'product_id' => $item['product_id'],
  440. 'variant_id' => $item['variant_id'],
  441. 'title' => $item['title'],
  442. 'variant_name' => $item['variant_name'],
  443. 'unit_price_cents' => $item['unit_price_cents'],
  444. 'quantity' => $item['quantity'],
  445. 'total_cents' => $item['total_cents'],
  446. ]);
  447. }
  448. ​
  449. $usersDb->prepare("INSERT INTO order_status_history (order_id, status, note) VALUES (:order_id, 'pending', :note)")
  450. ->execute(['order_id' => $orderId, 'note' => 'Order placed · ' . Shop::paymentLabel($paymentMethod)]);
  451. ​
  452. $usersDb->commit();
  453. } catch (Throwable $exception) {
  454. if ($usersDb->inTransaction()) {
  455. $usersDb->rollBack();
  456. }
  457. error_log('StocketBase: could not create order: ' . $exception->getMessage());
  458. $orderId = null;
  459. }
  460. ​
  461. if ($orderId === null) {
  462. $errorMessage = Language::get('checkout_error_order', 'Could not create your order. Please try again.');
  463. } else {
  464. if (!isset($_SESSION['checkout_order_ids']) || !is_array($_SESSION['checkout_order_ids'])) {
  465. $_SESSION['checkout_order_ids'] = [];
  466. }
  467. $_SESSION['checkout_order_ids'][] = $orderId;
  468. $_SESSION['checkout_order_ids'] = array_slice(array_values(array_unique($_SESSION['checkout_order_ids'])), -20);
  469. ​
  470. if ($loggedInCustomer !== null && $formValues['save_address'] === '1' && $requiresShipping) {
  471. try {
  472. $hasDefault = false;
  473. foreach ($savedAddresses as $savedAddress) {
  474. if ((int) $savedAddress['is_default_shipping'] === 1) {
  475. $hasDefault = true;
  476. }
  477. }
  478. $usersDb->prepare(
  479. '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)
  480. VALUES (:user_id, :full_name, :company, :tax_id, :line1, :line2, :city, :region, :postal_code, :country, :phone, :default_shipping, :default_billing)'
  481. )->execute([
  482. 'user_id' => (int) $loggedInCustomer['id'],
  483. 'full_name' => $shippingAddress['name'],
  484. 'company' => $wantsInvoice && $sameAsShipping ? $nullable($formValues['billing_company']) : null,
  485. 'tax_id' => $wantsInvoice && $sameAsShipping ? $nullable($formValues['billing_tax_id']) : null,
  486. 'line1' => $shippingAddress['address_line1'],
  487. 'line2' => $nullable($shippingAddress['address_line2']),
  488. 'city' => $shippingAddress['city'],
  489. 'region' => $nullable($shippingAddress['region']),
  490. 'postal_code' => $shippingAddress['postal_code'],
  491. 'country' => $shippingAddress['country'],
  492. 'phone' => $nullable($formValues['shipping_phone']),
  493. 'default_shipping' => $hasDefault ? 0 : 1,
  494. 'default_billing' => $hasDefault ? 0 : 1,
  495. ]);
  496. } catch (Throwable $exception) {
  497. error_log('StocketBase: could not save the address: ' . $exception->getMessage());
  498. }
  499. }
  500. ​
  501. $confirmationUrl = 'order-confirmation.php?order_id=' . $orderId . '&token=' . $accessToken;
  502. ​
  503. if ($paymentMethod === 'free') {
  504. Orders::markPaid($orderId, ['provider' => 'free'], 'Free order');
  505. Cart::clear();
  506. header('Location: ' . $confirmationUrl);
  507. exit;
  508. }
  509. ​
  510. if (Shop::isOfflineMethod($paymentMethod)) {
  511. Orders::reserveStock($orderId);
  512. $placedOrder = Orders::find($orderId);
  513. if ($placedOrder !== null) {
  514. Orders::sendAwaitingPayment($placedOrder, Orders::items($orderId));
  515. }
  516. Cart::clear();
  517. header('Location: ' . $confirmationUrl);
  518. exit;
  519. }
  520. ​
  521. $lineItems = [];
  522. foreach ($items as $item) {
  523. $lineItems[] = [
  524. 'name' => $item['title'] . ($item['variant_name'] !== null ? ' — ' . $item['variant_name'] : ''),
  525. 'unit_amount_cents' => (int) $item['unit_price_cents'],
  526. 'currency' => strtolower($item['currency']),
  527. 'quantity' => (int) $item['quantity'],
  528. ];
  529. }
  530. if ($quote['shipping_cents'] > 0) {
  531. $lineItems[] = [
  532. 'name' => Language::get('order_shipping_label', 'Shipping') . ($quote['shipping_method'] !== null ? ' — ' . $quote['shipping_method']['name'] : ''),
  533. 'unit_amount_cents' => (int) $quote['shipping_cents'],
  534. 'currency' => strtolower($cartCurrency),
  535. 'quantity' => 1,
  536. ];
  537. }
  538. if (!$quote['prices_include_tax'] && $quote['tax_cents'] > 0) {
  539. $lineItems[] = [
  540. 'name' => Shop::taxLabel() . ' ' . Shop::formatRate((int) $quote['tax_rate_bp']),
  541. 'unit_amount_cents' => (int) $quote['tax_cents'],
  542. 'currency' => strtolower($cartCurrency),
  543. 'quantity' => 1,
  544. ];
  545. }
  546. ​
  547. $successUrl = checkoutBaseUrl() . '/' . $confirmationUrl . '&session_id={CHECKOUT_SESSION_ID}';
  548. $cancelUrl = checkoutBaseUrl() . '/cart.php';
  549. $metadata = ['order_id' => (string) $orderId, 'checkout_kind' => 'order'];
  550. if ($loggedInCustomer !== null) {
  551. $metadata['user_account_id'] = (string) $loggedInCustomer['id'];
  552. }
  553. ​
  554. $stripe = new StripeClient();
  555. $couponId = null;
  556. if ($quote['discount_cents'] > 0) {
  557. $couponId = $stripe->createOneTimeCoupon((int) $quote['discount_cents'], $cartCurrency, Language::get('checkout_discount_name', 'Discount') . ' ' . (string) $appliedCode);
  558. }
  559. ​
  560. if ($quote['discount_cents'] > 0 && $couponId === null) {
  561. $errorMessage = Language::get('checkout_error_discount', 'Could not apply your discount at payment. Please try again.');
  562. } else {
  563. $session = $stripe->createCheckoutSession($lineItems, 'payment', $successUrl, $cancelUrl, $customerEmail, $metadata, $couponId);
  564. if (is_array($session) && !empty($session['url'])) {
  565. $usersDb->prepare('UPDATE orders SET provider_checkout_id = :checkout_id WHERE id = :id')
  566. ->execute(['checkout_id' => (string) ($session['id'] ?? ''), 'id' => $orderId]);
  567. header('Location: ' . $session['url']);
  568. exit;
  569. }
  570. $errorMessage = Language::get('checkout_error_stripe_start', 'Could not start the payment. Please try again.');
  571. }
  572. ​
  573. $usersDb->prepare("UPDATE orders SET status = 'failed' WHERE id = :id AND status = 'pending'")->execute(['id' => $orderId]);
  574. }
  575. }
  576. }
  577. ​
  578. $pageTitle = Language::get('checkout_title', 'Checkout') . ' - ' . $settings['site_name'];
  579. $pageDescription = '';
  580. $pageNoindex = true;
  581. ​
  582. require __DIR__ . '/includes/front-header.php';
  583. ​
  584. $fieldError = static function (string $field) use ($fieldErrors): string {
  585. return isset($fieldErrors[$field]) ? '<span class="checkout-field-error">' . htmlspecialchars($fieldErrors[$field]) . '</span>' : '';
  586. };
  587. $invalid = static fn(string $field): string => isset($fieldErrors[$field]) ? ' aria-invalid="true"' : '';
  588. $value = static fn(string $field): string => htmlspecialchars((string) ($formValues[$field] ?? ''), ENT_QUOTES);
  589. ​
  590. ?>
  591. <h1 class="article-title"><?= htmlspecialchars(Language::get('checkout_title', 'Checkout')) ?></h1>
  592. ​
  593. <?php foreach (SiteFront::activeAds('checkout') as $checkoutAd): ?>
  594. <?= SiteFront::renderAd($checkoutAd) ?>
  595. <?php endforeach; ?>
  596. ​
  597. <?php if ($errorMessage !== null): ?>
  598. <div class="checkout-alert" role="alert"><?= htmlspecialchars($errorMessage) ?></div>
  599. <?php endif; ?>
  600. ​
  601. <?php if ($mode === 'single'): ?>
  602. <?php
  603. $productCurrency = (string) ($singleProduct['currency'] ?: $settings['store_currency']);
  604. $billingInterval = (string) ($singleProduct['billing_interval'] ?: 'month');
  605. ?>
  606. <div class="checkout-summary">
  607. <h2><?= htmlspecialchars($singleProduct['title']) ?></h2>
  608. <p>
  609. <?= htmlspecialchars(Currency::format((int) $singleProduct['price_cents'], $productCurrency)) ?>
  610. / <?= htmlspecialchars($billingInterval === 'year' ? Language::get('subscription_per_year', 'year') : Language::get('subscription_per_month', 'month')) ?>
  611. <?= $provider === 'polar' ? ' · Polar' : ' · Stripe' ?>
  612. </p>
  613. </div>
  614. ​
  615. <form method="post" class="checkout-form">
  616. <?= Csrf::field() ?>
  617. <input type="hidden" name="action" value="submit_order">
  618. <input type="hidden" name="product_id" value="<?= (int) $singleProduct['id'] ?>">
  619. <input type="hidden" name="provider" value="<?= htmlspecialchars($provider, ENT_QUOTES) ?>">
  620. ​
  621. <?php if ($loggedInCustomer === null): ?>
  622. <label for="email"><?= htmlspecialchars(Language::get('checkout_email_label', 'Email address')) ?></label>
  623. <input type="email" name="email" id="email" required value="<?= $value('email') ?>">
  624. <?php endif; ?>
  625. ​
  626. <button type="submit" class="unlock-btn" style="border:none;cursor:pointer;margin-top:16px;">
  627. <?= $provider === 'polar' ? htmlspecialchars(Language::get('product_subscribe_polar_button', 'Subscribe via Polar')) : htmlspecialchars(Language::get('product_subscribe_button', 'Subscribe')) ?>
  628. </button>
  629. </form>
  630. <?php else: ?>
  631. <?php
  632. $items = Cart::items();
  633. $cartCurrency = Cart::currency();
  634. $requiresShipping = Cart::requiresShipping($items);
  635. $appliedCode = Cart::appliedDiscountCode();
  636. $discount = $appliedCode !== null ? Cart::findDiscount($appliedCode, $cartCurrency) : null;
  637. $quote = Shop::quote($items, $discount, $formValues['shipping_method'], $formValues['shipping_country'], $formValues['payment_method']);
  638. $allShippingMethods = $requiresShipping ? Shop::shippingMethods() : [];
  639. $paymentMethods = Shop::paymentMethods($requiresShipping, null);
  640. $selectedPayment = $formValues['payment_method'] !== '' && isset($paymentMethods[$formValues['payment_method']]) ? $formValues['payment_method'] : (string) (array_key_first($paymentMethods) ?? '');
  641. if ($quote['shipping_method'] === null && !empty($quote['shipping_options']) && !isset($fieldErrors['shipping_method'])) {
  642. $quote = Shop::quote($items, $discount, (string) $quote['shipping_options'][0]['id'], $formValues['shipping_country'], $formValues['payment_method']);
  643. }
  644. $selectedShipping = $quote['shipping_method']['id'] ?? $formValues['shipping_method'];
  645. $checkoutConfig = [
  646. 'currency' => $cartCurrency,
  647. 'decimals' => Currency::decimals($cartCurrency),
  648. 'goods' => max(0, $quote['subtotal_cents'] - $quote['discount_cents']),
  649. 'taxRate' => $quote['tax_rate_bp'],
  650. 'taxInclusive' => $quote['prices_include_tax'],
  651. 'taxShipping' => Shop::setting('shop_tax_shipping', '1') === '1',
  652. 'codFee' => max(0, (int) Shop::setting('shop_cod_fee_cents', '0')),
  653. 'requiresShipping' => $requiresShipping,
  654. 'methods' => array_map(static fn(array $method): array => [
  655. 'id' => $method['id'],
  656. 'price' => (int) $method['price_cents'],
  657. 'freeOver' => $method['free_over_cents'],
  658. 'countries' => $method['countries'],
  659. 'cod' => (bool) $method['cod'],
  660. ], $allShippingMethods),
  661. 'codRestricted' => count(array_filter($allShippingMethods, static fn(array $method): bool => !empty($method['cod']))) > 0,
  662. 'freeLabel' => Language::get('checkout_shipping_free', 'Free'),
  663. 'sample' => Currency::format(123456, $cartCurrency),
  664. ];
  665. ?>
  666. <form method="post" class="checkout-layout" id="checkout-form" novalidate>
  667. <?= Csrf::field() ?>
  668. <input type="hidden" name="action" value="submit_order">
  669. ​
  670. <div class="checkout-main">
  671. <section class="checkout-section">
  672. <h2><span class="checkout-step">1</span><?= htmlspecialchars(Language::get('checkout_contact_title', 'Contact')) ?></h2>
  673. <?php if ($loggedInCustomer === null): ?>
  674. <label for="email"><?= htmlspecialchars(Language::get('checkout_email_label', 'Email address')) ?></label>
  675. <input type="email" name="email" id="email" required autocomplete="email" value="<?= $value('email') ?>"<?= $invalid('email') ?>>
  676. <?= $fieldError('email') ?>
  677. <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_email_hint', 'We send the order confirmation and any download links here.')) ?>
  678. <a href="user-login.php?redirect=checkout.php"><?= htmlspecialchars(Language::get('checkout_have_account', 'Have an account? Log in')) ?></a></p>
  679. <?php else: ?>
  680. <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_logged_in_as', 'Ordering as')) ?> <strong><?= htmlspecialchars((string) $loggedInCustomer['email']) ?></strong></p>
  681. <?php endif; ?>
  682. </section>
  683. ​
  684. <?php if ($requiresShipping): ?>
  685. <section class="checkout-section">
  686. <h2><span class="checkout-step">2</span><?= htmlspecialchars(Language::get('checkout_shipping_title', 'Shipping address')) ?></h2>
  687. <?php if (count($savedAddresses) > 1): ?>
  688. <label for="saved-address"><?= htmlspecialchars(Language::get('checkout_saved_address', 'Use a saved address')) ?></label>
  689. <select id="saved-address" data-addresses='<?= htmlspecialchars((string) json_encode(array_map(static fn(array $address): array => [
  690. 'name' => $address['full_name'], 'address_line1' => $address['address_line1'], 'address_line2' => $address['address_line2'] ?? '',
  691. 'city' => $address['city'], 'region' => $address['region'] ?? '', 'postal_code' => $address['postal_code'], 'country' => $address['country'], 'phone' => $address['phone'] ?? '',
  692. ], $savedAddresses), JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'>
  693. <?php foreach ($savedAddresses as $addressIndex => $savedAddress): ?>
  694. <option value="<?= (int) $addressIndex ?>"><?= htmlspecialchars(trim(($savedAddress['label'] ? $savedAddress['label'] . ' · ' : '') . $savedAddress['full_name'] . ', ' . $savedAddress['address_line1'] . ', ' . $savedAddress['city'])) ?></option>
  695. <?php endforeach; ?>
  696. </select>
  697. <?php endif; ?>
  698. ​
  699. <label for="shipping_name"><?= htmlspecialchars(Language::get('checkout_full_name', 'Full name')) ?></label>
  700. <input type="text" name="shipping_name" id="shipping_name" required autocomplete="shipping name" value="<?= $value('shipping_name') ?>"<?= $invalid('shipping_name') ?>>
  701. <?= $fieldError('shipping_name') ?>
  702. ​
  703. <label for="shipping_country"><?= htmlspecialchars(Language::get('checkout_country_label', 'Country')) ?></label>
  704. <select name="shipping_country" id="shipping_country" required autocomplete="shipping country"<?= $invalid('shipping_country') ?>>
  705. <option value=""><?= htmlspecialchars(Language::get('checkout_choose_country', 'Choose a country')) ?></option>
  706. <?php foreach ($countryOptions as $countryCode => $countryName): ?>
  707. <option value="<?= htmlspecialchars($countryCode) ?>" <?= $formValues['shipping_country'] === $countryCode ? 'selected' : '' ?>><?= htmlspecialchars($countryName) ?></option>
  708. <?php endforeach; ?>
  709. </select>
  710. <?= $fieldError('shipping_country') ?>
  711. ​
  712. <label for="shipping_address_line1"><?= htmlspecialchars(Language::get('checkout_address_line1', 'Address')) ?></label>
  713. <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') ?>>
  714. <?= $fieldError('shipping_address_line1') ?>
  715. <label for="shipping_address_line2"><?= htmlspecialchars(Language::get('checkout_address_line2', 'Address line 2 (optional)')) ?></label>
  716. <input type="text" name="shipping_address_line2" id="shipping_address_line2" autocomplete="shipping address-line2" value="<?= $value('shipping_address_line2') ?>">
  717. ​
  718. <div class="checkout-grid">
  719. <div>
  720. <label for="shipping_postal_code"><?= htmlspecialchars(Language::get('checkout_postal_code', 'Postal code')) ?></label>
  721. <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') ?>>
  722. <?= $fieldError('shipping_postal_code') ?>
  723. </div>
  724. <div>
  725. <label for="shipping_city"><?= htmlspecialchars(Language::get('checkout_city', 'City')) ?></label>
  726. <input type="text" name="shipping_city" id="shipping_city" required autocomplete="shipping address-level2" value="<?= $value('shipping_city') ?>"<?= $invalid('shipping_city') ?>>
  727. <?= $fieldError('shipping_city') ?>
  728. </div>
  729. </div>
  730. <label for="shipping_region"><?= htmlspecialchars(Language::get('checkout_region', 'State / Region')) ?></label>
  731. <input type="text" name="shipping_region" id="shipping_region" autocomplete="shipping address-level1" value="<?= $value('shipping_region') ?>">
  732. ​
  733. <?php if ($phoneMode !== 'hidden'): ?>
  734. <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>
  735. <input type="tel" name="shipping_phone" id="shipping_phone" autocomplete="tel" <?= $phoneMode === 'required' ? 'required' : '' ?> value="<?= $value('shipping_phone') ?>"<?= $invalid('shipping_phone') ?>>
  736. <?= $fieldError('shipping_phone') ?>
  737. <?php endif; ?>
  738. ​
  739. <?php if ($loggedInCustomer !== null): ?>
  740. <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>
  741. <?php endif; ?>
  742. </section>
  743. ​
  744. <section class="checkout-section">
  745. <h2><span class="checkout-step">3</span><?= htmlspecialchars(Language::get('checkout_delivery_title', 'Delivery')) ?></h2>
  746. <?php if (empty($allShippingMethods)): ?>
  747. <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_delivery_included', 'Delivery is included in the price.')) ?></p>
  748. <?php else: ?>
  749. <div class="checkout-options" id="shipping-options">
  750. <?php foreach ($allShippingMethods as $method): ?>
  751. <?php
  752. $methodCost = (int) $method['price_cents'];
  753. if ($method['free_over_cents'] !== null && $checkoutConfig['goods'] >= (int) $method['free_over_cents']) {
  754. $methodCost = 0;
  755. }
  756. $methodVisible = empty($method['countries']) || in_array($formValues['shipping_country'], $method['countries'], true);
  757. ?>
  758. <label class="checkout-option" data-method="<?= htmlspecialchars($method['id']) ?>" <?= $methodVisible ? '' : 'hidden' ?>>
  759. <input type="radio" name="shipping_method" value="<?= htmlspecialchars($method['id']) ?>" <?= $selectedShipping === $method['id'] ? 'checked' : '' ?> <?= $methodVisible ? '' : 'disabled' ?>>
  760. <span class="checkout-option-body">
  761. <span class="checkout-option-title"><?= htmlspecialchars($method['name']) ?></span>
  762. <?php if ($method['note'] !== '' || $method['free_over_cents'] !== null): ?>
  763. <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>
  764. <?php endif; ?>
  765. </span>
  766. <span class="checkout-option-price" data-price><?= htmlspecialchars($methodCost === 0 ? $checkoutConfig['freeLabel'] : Currency::format($methodCost, $cartCurrency)) ?></span>
  767. </label>
  768. <?php endforeach; ?>
  769. </div>
  770. <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>
  771. <?= $fieldError('shipping_method') ?>
  772. <?php endif; ?>
  773. </section>
  774. <?php endif; ?>
  775. ​
  776. <section class="checkout-section">
  777. <h2><span class="checkout-step"><?= $requiresShipping ? '4' : '2' ?></span><?= htmlspecialchars(Language::get('checkout_billing_title', 'Billing details')) ?></h2>
  778. <?php if ($requiresShipping): ?>
  779. <label class="checkout-check">
  780. <input type="checkbox" name="billing_same_as_shipping" value="1" id="billing_same_as_shipping" <?= $formValues['billing_same_as_shipping'] === '1' ? 'checked' : '' ?>>
  781. <?= htmlspecialchars(Language::get('checkout_billing_same', 'Billing address same as shipping')) ?>
  782. </label>
  783. <?php endif; ?>
  784. <label class="checkout-check">
  785. <input type="checkbox" name="wants_invoice" value="1" id="wants_invoice" <?= $formValues['wants_invoice'] === '1' ? 'checked' : '' ?>>
  786. <?= htmlspecialchars(Language::get('checkout_wants_invoice', 'I need an invoice for a company')) ?>
  787. </label>
  788. ​
  789. <div id="invoice-fields" <?= $formValues['wants_invoice'] === '1' ? '' : 'hidden' ?>>
  790. <div class="checkout-grid">
  791. <div>
  792. <label for="billing_company"><?= htmlspecialchars(Language::get('checkout_company', 'Company name')) ?></label>
  793. <input type="text" name="billing_company" id="billing_company" autocomplete="organization" value="<?= $value('billing_company') ?>">
  794. </div>
  795. <div>
  796. <label for="billing_tax_id"><?= htmlspecialchars(Language::get('checkout_tax_id', 'Tax ID (VAT number)')) ?></label>
  797. <input type="text" name="billing_tax_id" id="billing_tax_id" value="<?= $value('billing_tax_id') ?>">
  798. </div>
  799. </div>
  800. </div>
  801. ​
  802. <div id="billing-fields" <?= (!$requiresShipping && $formValues['wants_invoice'] === '1') || ($requiresShipping && $formValues['billing_same_as_shipping'] !== '1') ? '' : 'hidden' ?>>
  803. <label for="billing_name"><?= htmlspecialchars(Language::get('checkout_full_name', 'Full name')) ?></label>
  804. <input type="text" name="billing_name" id="billing_name" autocomplete="billing name" value="<?= $value('billing_name') ?>"<?= $invalid('billing_name') ?>>
  805. <?= $fieldError('billing_name') ?>
  806. <label for="billing_country"><?= htmlspecialchars(Language::get('checkout_country_label', 'Country')) ?></label>
  807. <select name="billing_country" id="billing_country" autocomplete="billing country"<?= $invalid('billing_country') ?>>
  808. <option value=""><?= htmlspecialchars(Language::get('checkout_choose_country', 'Choose a country')) ?></option>
  809. <?php foreach (Countries::all() as $countryCode => $countryName): ?>
  810. <option value="<?= htmlspecialchars($countryCode) ?>" <?= $formValues['billing_country'] === $countryCode ? 'selected' : '' ?>><?= htmlspecialchars($countryName) ?></option>
  811. <?php endforeach; ?>
  812. </select>
  813. <?= $fieldError('billing_country') ?>
  814. <label for="billing_address_line1"><?= htmlspecialchars(Language::get('checkout_address_line1', 'Address')) ?></label>
  815. <input type="text" name="billing_address_line1" id="billing_address_line1" autocomplete="billing address-line1" value="<?= $value('billing_address_line1') ?>"<?= $invalid('billing_address_line1') ?>>
  816. <?= $fieldError('billing_address_line1') ?>
  817. <label for="billing_address_line2"><?= htmlspecialchars(Language::get('checkout_address_line2', 'Address line 2 (optional)')) ?></label>
  818. <input type="text" name="billing_address_line2" id="billing_address_line2" autocomplete="billing address-line2" value="<?= $value('billing_address_line2') ?>">
  819. <div class="checkout-grid">
  820. <div>
  821. <label for="billing_postal_code"><?= htmlspecialchars(Language::get('checkout_postal_code', 'Postal code')) ?></label>
  822. <input type="text" name="billing_postal_code" id="billing_postal_code" autocomplete="billing postal-code" value="<?= $value('billing_postal_code') ?>"<?= $invalid('billing_postal_code') ?>>
  823. <?= $fieldError('billing_postal_code') ?>
  824. </div>
  825. <div>
  826. <label for="billing_city"><?= htmlspecialchars(Language::get('checkout_city', 'City')) ?></label>
  827. <input type="text" name="billing_city" id="billing_city" autocomplete="billing address-level2" value="<?= $value('billing_city') ?>"<?= $invalid('billing_city') ?>>
  828. <?= $fieldError('billing_city') ?>
  829. </div>
  830. </div>
  831. <label for="billing_region"><?= htmlspecialchars(Language::get('checkout_region', 'State / Region')) ?></label>
  832. <input type="text" name="billing_region" id="billing_region" autocomplete="billing address-level1" value="<?= $value('billing_region') ?>">
  833. </div>
  834. </section>
  835. ​
  836. <section class="checkout-section" id="payment-section" <?= $quote['total_cents'] === 0 ? 'hidden' : '' ?>>
  837. <h2><span class="checkout-step"><?= $requiresShipping ? '5' : '3' ?></span><?= htmlspecialchars(Language::get('checkout_payment_title', 'Payment')) ?></h2>
  838. <?php if (empty($paymentMethods)): ?>
  839. <p class="checkout-hint"><?= htmlspecialchars(Language::get('checkout_error_payment_config', 'Payment is not configured yet. Please try again later.')) ?></p>
  840. <?php else: ?>
  841. <div class="checkout-options">
  842. <?php foreach ($paymentMethods as $methodKey => $methodLabel): ?>
  843. <label class="checkout-option" data-payment="<?= htmlspecialchars($methodKey) ?>">
  844. <input type="radio" name="payment_method" value="<?= htmlspecialchars($methodKey) ?>" <?= $selectedPayment === $methodKey ? 'checked' : '' ?>>
  845. <span class="checkout-option-body">
  846. <span class="checkout-option-title"><?= htmlspecialchars($methodLabel) ?></span>
  847. <span class="checkout-option-note"><?= htmlspecialchars(match ($methodKey) {
  848. 'card' => Language::get('payment_method_card_note', 'Pay securely online. You will be redirected to the payment page.'),
  849. 'bank_transfer' => Language::get('payment_method_bank_note', 'We send the bank details after you place the order. We ship once the money arrives.'),
  850. 'cod' => (int) $checkoutConfig['codFee'] > 0
  851. ? 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}.'))
  852. : Language::get('payment_method_cod_note', 'Pay the courier when it arrives.'),
  853. default => '',
  854. }) ?></span>
  855. </span>
  856. </label>
  857. <?php endforeach; ?>
  858. </div>
  859. <?= $fieldError('payment_method') ?>
  860. <?php endif; ?>
  861. </section>
  862. ​
  863. <section class="checkout-section">
  864. <label for="customer_note"><?= htmlspecialchars(Language::get('checkout_note_label', 'Order note (optional)')) ?></label>
  865. <textarea name="customer_note" id="customer_note" rows="3" maxlength="2000"><?= $value('customer_note') ?></textarea>
  866. ​
  867. <?php if ($termsUrl !== ''): ?>
  868. <label class="checkout-check checkout-terms">
  869. <input type="checkbox" name="accept_terms" value="1" required <?= $formValues['accept_terms'] === '1' ? 'checked' : '' ?><?= $invalid('accept_terms') ?>>
  870. <span><?= str_replace(
  871. ['{terms}', '{privacy}'],
  872. [
  873. '<a href="' . htmlspecialchars($termsUrl, ENT_QUOTES) . '" target="_blank" rel="noopener">' . htmlspecialchars(Language::get('checkout_terms_link', 'terms of sale')) . '</a>',
  874. $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')),
  875. ],
  876. htmlspecialchars(Language::get('checkout_accept_terms', 'I accept the {terms} and the {privacy}.'))
  877. ) ?></span>
  878. </label>
  879. <?= $fieldError('accept_terms') ?>
  880. <?php endif; ?>
  881. </section>
  882. </div>
  883. ​
  884. <aside class="checkout-aside">
  885. <div class="checkout-summary-card">
  886. <h2><?= htmlspecialchars(Language::get('checkout_summary_title', 'Your order')) ?></h2>
  887. <ul class="checkout-lines">
  888. <?php foreach ($items as $item): ?>
  889. <li>
  890. <?php if (!empty($item['cover_image_path'])): ?>
  891. <img src="<?= htmlspecialchars((string) $item['cover_image_path']) ?>" alt="" loading="lazy">
  892. <?php endif; ?>
  893. <span class="checkout-line-name"><?= htmlspecialchars($item['title']) ?><?php if ($item['variant_name'] !== null): ?><small><?= htmlspecialchars($item['variant_name']) ?></small><?php endif; ?><small>&times; <?= (int) $item['quantity'] ?></small></span>
  894. <span class="checkout-line-price"><?= htmlspecialchars(Currency::format($item['total_cents'], $item['currency'])) ?></span>
  895. </li>
  896. <?php endforeach; ?>
  897. </ul>
  898. <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_subtotal', 'Subtotal')) ?></span><span><?= htmlspecialchars(Currency::format($quote['subtotal_cents'], $cartCurrency)) ?></span></div>
  899. <?php if ($quote['discount_cents'] > 0): ?>
  900. <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>
  901. <?php endif; ?>
  902. <?php if ($requiresShipping): ?>
  903. <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>
  904. <?php endif; ?>
  905. <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>
  906. <?php if ($quote['tax_rate_bp'] > 0): ?>
  907. <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>
  908. <?php endif; ?>
  909. <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>
  910. ​
  911. <button type="submit" class="unlock-btn checkout-submit" id="checkout-submit"
  912. data-label-card="<?= htmlspecialchars(Language::get('checkout_pay_button', 'Continue to payment'), ENT_QUOTES) ?>"
  913. data-label-offline="<?= htmlspecialchars(Language::get('checkout_place_order', 'Place order'), ENT_QUOTES) ?>">
  914. <?= htmlspecialchars($quote['total_cents'] === 0 || Shop::isOfflineMethod($selectedPayment) ? Language::get('checkout_place_order', 'Place order') : Language::get('checkout_pay_button', 'Continue to payment')) ?>
  915. </button>
  916. <p class="checkout-secure"><?= Icons::icon('lock', 'icon icon-sm') ?><?= htmlspecialchars(Language::get('checkout_secure_note', 'Your details are sent securely.')) ?></p>
  917. <a href="cart.php" class="checkout-back">&larr; <?= htmlspecialchars(Language::get('checkout_back_to_cart', 'Back to cart')) ?></a>
  918. </div>
  919. </aside>
  920. </form>
  921. ​
  922. <script>
  923. (function () {
  924. var config = <?= json_encode($checkoutConfig, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) ?>;
  925. var form = document.getElementById('checkout-form');
  926. if (!form) {
  927. return;
  928. }
  929. var format = (function () {
  930. var sample = config.sample;
  931. var digits = sample.replace(/[^0-9]/g, '');
  932. var start = sample.search(/[0-9]/);
  933. var end = sample.length - sample.split('').reverse().join('').search(/[0-9]/);
  934. var prefix = sample.slice(0, start);
  935. var suffix = sample.slice(end);
  936. var middle = sample.slice(start, end);
  937. var decimalSep = config.decimals > 0 ? middle.charAt(middle.length - config.decimals - 1) : '';
  938. var groupMatch = middle.slice(0, middle.length - (config.decimals > 0 ? config.decimals + 1 : 0)).replace(/[0-9]/g, '');
  939. var groupSep = groupMatch.charAt(0) || '';
  940. return function (cents) {
  941. var negative = cents < 0;
  942. cents = Math.abs(cents);
  943. var factor = Math.pow(10, config.decimals);
  944. var whole = Math.floor(cents / factor).toString();
  945. var fraction = config.decimals > 0 ? (cents % factor).toString().padStart(config.decimals, '0') : '';
  946. whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, groupSep);
  947. return (negative ? '-' : '') + prefix + whole + (config.decimals > 0 ? decimalSep + fraction : '') + suffix;
  948. };
  949. })();
  950. ​
  951. function selected(name) {
  952. var input = form.querySelector('input[name="' + name + '"]:checked');
  953. return input && !input.disabled ? input.value : '';
  954. }
  955. ​
  956. function computeTax(base) {
  957. if (config.taxRate <= 0 || base <= 0) {
  958. return 0;
  959. }
  960. if (config.taxInclusive) {
  961. return base - Math.round(base * 10000 / (10000 + config.taxRate));
  962. }
  963. return Math.round(base * config.taxRate / 10000);
  964. }
  965. ​
  966. function refresh() {
  967. var country = (form.querySelector('#shipping_country') || {}).value || '';
  968. var shippingCost = 0;
  969. var shippingChosen = !config.requiresShipping || config.methods.length === 0;
  970. var available = 0;
  971. var chosenMethod = null;
  972. config.methods.forEach(function (method) {
  973. var row = form.querySelector('[data-method="' + method.id + '"]');
  974. if (!row) {
  975. return;
  976. }
  977. var visible = method.countries.length === 0 || method.countries.indexOf(country) !== -1;
  978. var input = row.querySelector('input');
  979. row.hidden = !visible;
  980. input.disabled = !visible;
  981. if (!visible && input.checked) {
  982. input.checked = false;
  983. }
  984. var cost = method.freeOver !== null && config.goods >= method.freeOver ? 0 : method.price;
  985. row.querySelector('[data-price]').textContent = cost === 0 ? config.freeLabel : format(cost);
  986. if (visible) {
  987. available++;
  988. }
  989. if (visible && input.checked) {
  990. shippingCost = cost;
  991. shippingChosen = true;
  992. chosenMethod = method;
  993. }
  994. });
  995. if (config.requiresShipping && config.methods.length > 0 && available === 1 && !shippingChosen) {
  996. config.methods.forEach(function (method) {
  997. var row = form.querySelector('[data-method="' + method.id + '"]');
  998. if (row && !row.hidden) {
  999. row.querySelector('input').checked = true;
  1000. shippingCost = method.freeOver !== null && config.goods >= method.freeOver ? 0 : method.price;
  1001. shippingChosen = true;
  1002. chosenMethod = method;
  1003. }
  1004. });
  1005. }
  1006. var none = document.getElementById('shipping-none');
  1007. if (none) {
  1008. none.hidden = !(config.requiresShipping && config.methods.length > 0 && country !== '' && available === 0);
  1009. }
  1010. ​
  1011. var codRow = form.querySelector('[data-payment="cod"]');
  1012. if (codRow) {
  1013. var codAllowed = !config.codRestricted || !chosenMethod || chosenMethod.cod;
  1014. codRow.hidden = !codAllowed;
  1015. codRow.querySelector('input').disabled = !codAllowed;
  1016. if (!codAllowed && codRow.querySelector('input').checked) {
  1017. codRow.querySelector('input').checked = false;
  1018. }
  1019. }
  1020. ​
  1021. var payment = selected('payment_method');
  1022. var codFee = payment === 'cod' ? config.codFee : 0;
  1023. var taxable = config.goods + (config.taxShipping ? shippingCost + codFee : 0);
  1024. var tax = computeTax(taxable);
  1025. var total = config.goods + shippingCost + codFee + (config.taxInclusive ? 0 : tax);
  1026. ​
  1027. var shippingCell = document.getElementById('summary-shipping');
  1028. if (shippingCell) {
  1029. shippingCell.textContent = !shippingChosen ? '—' : (shippingCost === 0 ? config.freeLabel : format(shippingCost));
  1030. }
  1031. var codCell = document.getElementById('summary-cod-row');
  1032. if (codCell) {
  1033. codCell.hidden = codFee <= 0;
  1034. document.getElementById('summary-cod').textContent = format(codFee);
  1035. }
  1036. var taxCell = document.getElementById('summary-tax');
  1037. if (taxCell) {
  1038. taxCell.textContent = format(tax);
  1039. }
  1040. document.getElementById('summary-total').textContent = format(total);
  1041. ​
  1042. var paymentSection = document.getElementById('payment-section');
  1043. if (paymentSection) {
  1044. paymentSection.hidden = total === 0;
  1045. }
  1046. var submit = document.getElementById('checkout-submit');
  1047. submit.textContent = total === 0 || payment === 'bank_transfer' || payment === 'cod' ? submit.dataset.labelOffline : submit.dataset.labelCard;
  1048. }
  1049. ​
  1050. function toggleBilling() {
  1051. var same = document.getElementById('billing_same_as_shipping');
  1052. var invoice = document.getElementById('wants_invoice');
  1053. var billing = document.getElementById('billing-fields');
  1054. var invoiceFields = document.getElementById('invoice-fields');
  1055. if (invoiceFields) {
  1056. invoiceFields.hidden = !invoice.checked;
  1057. }
  1058. if (billing) {
  1059. billing.hidden = same ? same.checked : !invoice.checked;
  1060. }
  1061. }
  1062. ​
  1063. var saved = document.getElementById('saved-address');
  1064. if (saved) {
  1065. saved.addEventListener('change', function () {
  1066. var addresses = JSON.parse(saved.dataset.addresses || '[]');
  1067. var address = addresses[parseInt(saved.value, 10)];
  1068. if (!address) {
  1069. return;
  1070. }
  1071. ['name', 'address_line1', 'address_line2', 'city', 'region', 'postal_code', 'country'].forEach(function (field) {
  1072. var input = document.getElementById('shipping_' + field);
  1073. if (input) {
  1074. input.value = address[field] || '';
  1075. }
  1076. });
  1077. var phone = document.getElementById('shipping_phone');
  1078. if (phone && address.phone) {
  1079. phone.value = address.phone;
  1080. }
  1081. refresh();
  1082. });
  1083. }
  1084. ​
  1085. form.addEventListener('change', function (event) {
  1086. if (event.target.id === 'billing_same_as_shipping' || event.target.id === 'wants_invoice') {
  1087. toggleBilling();
  1088. }
  1089. refresh();
  1090. });
  1091. form.addEventListener('submit', function () {
  1092. var submit = document.getElementById('checkout-submit');
  1093. window.setTimeout(function () {
  1094. submit.disabled = true;
  1095. }, 0);
  1096. });
  1097. toggleBilling();
  1098. refresh();
  1099. })();
  1100. </script>
  1101. <?php endif; ?>
  1102. ​
  1103. <?php require __DIR__ . '/includes/front-footer.php'; ?>
  1104. ​