$_POST['account_id'] ?? '', 'email' => $_POST['email'] ?? '', 'first_name' => $_POST['first_name'] ?? '', 'last_name' => $_POST['last_name'] ?? '', 'address_street' => $_POST['address_street'] ?? '', 'address_city' => $_POST['address_city'] ?? '', 'address_state' => $_POST['address_state'] ?? '', 'address_zip' => $_POST['address_zip'] ?? '', 'address_country' => $_POST['address_country'] ?? '', 'address_phone' => $_POST['address_phone'] ?? '' ]; $products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : []; $subtotal = 0.00; $total = 0.00; $shippingtotal = 0.00; $discounttotal = 0.00; $taxtotal = 0.00; $tax_rate = ''; $weighttotal = 0; $checkout_input = [ "selected_country" => isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'], "selected_shipment_method" => isset($_POST['shipping_method']) ? $_POST['shipping_method'] : null, "business_type" => 'b2c', "discount_code" => isset($_SESSION['discount']) ? $_SESSION['discount'] : null ]; $selected_shipping_method_name = ''; $shipping_methods_available = []; // Error array, output errors on the form $errors = []; // --------------------------------------- // --------------------------------------- // --------------------------------------- // Redirect the user if the shopping cart is empty if (empty($_SESSION['cart'])) { header('Location: ' . url('index.php?page=cart')); exit; } // Check if user is logged in if (isset($_SESSION['account_loggedin'])) { $stmt = $pdo->prepare('SELECT * FROM accounts WHERE id = ?'); $stmt->execute([ $_SESSION['account_id'] ]); // Fetch the account from the database and return the result as an Array $account = $stmt->fetch(PDO::FETCH_ASSOC); } // Update discount code if (isset($_POST['discount_code']) && !empty($_POST['discount_code'])) { $_SESSION['discount'] = $_POST['discount_code']; } else if (isset($_POST['discount_code']) && empty($_POST['discount_code']) && isset($_SESSION['discount'])) { unset($_SESSION['discount']); } //------------------------------- // If there are products in cart handle the checkout //------------------------------- if ($products_in_cart) { //Calculate shopping_cart $payload = json_encode(array("cart" => $products_in_cart, "checkout_input" => $checkout_input), JSON_UNESCAPED_UNICODE); $products_in_cart = ioAPIv2('/v2/checkout/',$payload,$clientsecret); $products_in_cart = json_decode($products_in_cart,true); //GET SPECIFIC TOTALS FROM API RESULTS $subtotal = $products_in_cart['totals']['subtotal']; $shippingtotal = $products_in_cart['totals']['shippingtotal']; $discounttotal = $products_in_cart['totals']['discounttotal']; $taxtotal = $products_in_cart['totals']['taxtotal']; $tax_rate = $products_in_cart['totals']['tax_rate']; $weighttotal = $products_in_cart['totals']['weighttotal']; $total = $products_in_cart['totals']['total']; $selected_country = isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country']; $selected_shipping_method = isset($_POST['shipping_method']) ? $_POST['shipping_method'] : null; $selected_shipping_method_name = ''; // Retrieve shipping methods $stmt = $pdo->query('SELECT * FROM shipping'); $shipping_methods = $stmt->fetchAll(PDO::FETCH_ASSOC); // Redirect the user if the shopping cart is empty if (empty($products_in_cart)) { header('Location: ' . url('index.php?page=cart')); exit; } //------------------------------- // END Checkout handler //------------------------------- } //------------------------------- //Place order //------------------------------- // Make sure when the user submits the form all data was submitted and shopping cart is not empty if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $_POST['address_phone'], $_SESSION['cart']) && !isset($_POST['update'])) { $account_id = null; // If the user is already logged in if (isset($_SESSION['account_loggedin'])) { // Account logged-in, update the user's details $stmt = $pdo->prepare('UPDATE accounts SET first_name = ?, last_name = ?, address_street = ?, address_city = ?, address_state = ?, address_zip = ?, address_country = ?, address_phone = ? WHERE id = ?'); $stmt->execute([ $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $_POST['address_phone'], $_SESSION['account_id'] ]); $account_id = $_SESSION['account_id']; } else if (isset($_POST['email'], $_POST['password'], $_POST['cpassword']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && !empty($_POST['password']) && !empty($_POST['cpassword'])) { // User is not logged in, check if the account already exists with the email they submitted $stmt = $pdo->prepare('SELECT id FROM accounts WHERE email = ?'); $stmt->execute([ $_POST['email'] ]); if ($stmt->fetch(PDO::FETCH_ASSOC)) { // Email exists, user should login instead... $errors[] = $error_account_name; } if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) { // Password must be between 5 and 20 characters long. $errors[] = $error_account_password_rules; } if ($_POST['password'] != $_POST['cpassword']) { // Password and confirm password fields do not match... $errors[] = $error_account_password_match; } if (!$errors) { // Hash the password $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Email doesnt exist, create new account $stmt = $pdo->prepare('INSERT INTO accounts (email, password, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, address_phone) VALUES (?,?,?,?,?,?,?,?,?,?)'); $stmt->execute([ $_POST['email'], $password, $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $_POST['address_phone'] ]); $account_id = $pdo->lastInsertId(); $stmt = $pdo->prepare('SELECT * FROM accounts WHERE id = ?'); $stmt->execute([ $account_id ]); // Fetch the account from the database and return the result as an Array $account = $stmt->fetch(PDO::FETCH_ASSOC); } } else if (account_required) { $errors[] = $error_account; } if (!$errors && $products_in_cart) { //Process checkout //Calculate shopping_cart $payload = json_encode(array("cart" => $products_in_cart, "checkout_input" => $checkout_input, "customer_details" => $account), JSON_UNESCAPED_UNICODE); $place_order = ioAPIv2('/v2/placeorder/',$payload,$clientsecret); $place_order = json_decode($products_in_cart,true); //Check if transaction is succesfull and send order confirmation to customer if ($place_order['error'] == '' && $place_order['id'] != ''){ //SEND CONFIRMATION TO CUSTOMER send_order_details_email( $account['email'], $products_in_cart, $account['first_name'], $account['last_name'], $account['address_street'], $account['address_city'], $account['address_state'], $account['address_zip'], $account['address_country'], $place_order['subtotal'], $place_order['discounttotal'], $place_order['shippingtotal'], $place_order['taxtotal'], $place_order['payment_amount'], $place_order['transaction_id'] ); } //Pay on delivery = 2 if (pay_on_delivery_enabled && $place_order['payment_method'] == 2){ //header('Location: ' . url('index.php?page=placeorder')); //exit; } /* //Disable giftcard if (isset($_SESSION['discount'])){ if (preg_match("/[#][0-9]/", $_SESSION['discount']) == 1){ useGiftCart($pdo, $_SESSION['discount']); } } // Authenticate the user if ($account_id != null) { // Log the user in with the details provided session_regenerate_id(); $_SESSION['account_loggedin'] = TRUE; $_SESSION['account_id'] = $account_id; $_SESSION['account_role'] = $account ? $account['role'] : 'Member'; } // Send order details to the specified email address send_order_details_email( isset($account['email']) && !empty($account['email']) ? $account['email'] : $_POST['email'], $products_in_cart, $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $subtotal, $discounttotal, $shippingtotal, $taxtotal, $payment_amount, $order_id ); header('Location: ' . url('index.php?page=placeorder')); exit; */ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Mollie ++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (mollie_enabled && $_POST['method'] == 'mollie') { // Process Normal Checkout // Generate unique transaction ID $transaction_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5)); // Insert transaction into database $stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, created, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, account_id, payment_method, shipping_method, shipping_amount, discount_code, address_phone, tax_amount) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'); $stmt->execute([ $transaction_id, $payment_amount, default_payment_status, date('Y-m-d H:i:s'), isset($account['email']) && !empty($account['email']) ? $account['email'] : $_POST['email'], $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $account_id, 'Debit/Credit', $selected_shipping_method_name, $shippingtotal, isset($_SESSION['discount']) ? $_SESSION['discount'] : '', $_POST['address_phone'], $taxtotal ]); // Get order ID $order_id = $pdo->lastInsertId(); // Iterate products and deduct quantities foreach ($products_in_cart as $product) { // For every product in the shopping cart insert a new transaction into our database $stmt = $pdo->prepare('INSERT INTO transactions_items (txn_id, item_id, item_price, item_quantity, item_options) VALUES (?,?,?,?,?)'); $stmt->execute([ $transaction_id, $product['id'], $product['final_price'], $product['quantity'], $product['options'] ]); // Update product quantity in the products table $stmt = $pdo->prepare('UPDATE products SET quantity = quantity - ? WHERE quantity > 0 AND id = ?'); $stmt->execute([ $product['quantity'], $product['id'] ]); // Deduct option quantities if ($product['options']) { $options = explode(',', $product['options']); foreach ($options as $opt) { $option_name = explode('-', $opt)[0]; $option_value = explode('-', $opt)[1]; $stmt = $pdo->prepare('UPDATE products_options SET quantity = quantity - ? WHERE quantity > 0 AND title = ? AND (name = ? OR name = "")'); $stmt->execute([ $product['quantity'], $option_name, $option_value ]); } } } // Authenticate the user if ($account_id != null) { // Log the user in with the details provided session_regenerate_id(); $_SESSION['account_loggedin'] = TRUE; $_SESSION['account_id'] = $account_id; $_SESSION['account_role'] = $account ? $account['role'] : 'Member'; } try { /* * Initialize the Mollie API library with your API key. * * See: https://www.mollie.com/dashboard/developers/api-keys */ require "initialize.php"; /* * Generate a unique order id for this example. It is important to include this unique attribute * in the redirectUrl (below) so a proper return page can be shown to the customer. */ $orderId = $transaction_id; $value = number_format(($subtotal-$discounttotal)+$shippingtotal,2,'.',''); /* * Determine the url parts to these example files. */ $protocol = isset($_SERVER['HTTPS']) && strcasecmp('off', $_SERVER['HTTPS']) !== 0 ? "https" : "http"; $hostname = $_SERVER['HTTP_HOST']; $path = dirname($_SERVER['REQUEST_URI'] ?? $_SERVER['PHP_SELF']); /* * Payment parameters: * amount Amount in EUROs. * description Description of the payment. * redirectUrl Redirect location. The customer will be redirected there after the payment. * webhookUrl Webhook location, used to report when the payment changes state. * metadata Custom metadata that is stored with the payment. */ if (rewrite_url){ $redirectURL = $protocol.'://'.$hostname.$path.'placeorder/'.$orderId; }else{ $redirectURL = $protocol.'://'.$hostname.$path.'index.php?page=placeorder&order_id='.$orderId; } $payment = $mollie->payments->create([ "amount" => [ "currency" => "EUR", "value" => "{$value}", // You must send the correct number of decimals, thus we enforce the use of strings ], "description" => "Order #{$orderId}", "redirectUrl" => "$redirectURL", "webhookUrl" => "{$protocol}://{$hostname}{$path}webhook.php", "metadata" => [ "order_id" => $orderId, ], ]); /* * Send the customer off to complete the payment. * This request should always be a GET, thus we enforce 303 http response code */ // Send order details to the specified email address send_order_details_email( isset($account['email']) && !empty($account['email']) ? $account['email'] : $_POST['email'], $products_in_cart, $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $subtotal, $discounttotal, $shippingtotal, $taxtotal, $payment_amount, $order_id ); // Send customer to checkout header("Location: " . $payment->getCheckoutUrl(), true, 303); } catch (\Mollie\Api\Exceptions\ApiException $e) { echo "API call failed: " . htmlspecialchars($e->getMessage()); } exit; } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // PayPal Payment + +++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (paypal_enabled && $_POST['method'] == 'paypal') { // Process Normal Checkout first then do PayPal related // Generate unique transaction ID $transaction_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5)); // Insert transaction into database $stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, created, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, account_id, payment_method, shipping_method, shipping_amount, discount_code, address_phone, tax_amount) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'); $stmt->execute([ $transaction_id, $payment_amount, default_payment_status, date('Y-m-d H:i:s'), isset($account['email']) && !empty($account['email']) ? $account['email'] : $_POST['email'], $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $account_id, 'paypal', $selected_shipping_method_name, $shippingtotal, isset($_SESSION['discount']) ? $_SESSION['discount'] : '', $_POST['address_phone'], $taxtotal ]); // Get order ID $order_id = $pdo->lastInsertId(); // Iterate products and deduct quantities foreach ($products_in_cart as $product) { // For every product in the shopping cart insert a new transaction into our database $stmt = $pdo->prepare('INSERT INTO transactions_items (txn_id, item_id, item_price, item_quantity, item_options) VALUES (?,?,?,?,?)'); $stmt->execute([ $transaction_id, $product['id'], $product['final_price'], $product['quantity'], $product['options'] ]); // Update product quantity in the products table $stmt = $pdo->prepare('UPDATE products SET quantity = quantity - ? WHERE quantity > 0 AND id = ?'); $stmt->execute([ $product['quantity'], $product['id'] ]); // Deduct option quantities if ($product['options']) { $options = explode(',', $product['options']); foreach ($options as $opt) { $option_name = explode('-', $opt)[0]; $option_value = explode('-', $opt)[1]; $stmt = $pdo->prepare('UPDATE products_options SET quantity = quantity - ? WHERE quantity > 0 AND title = ? AND (name = ? OR name = "")'); $stmt->execute([ $product['quantity'], $option_name, $option_value ]); } } } if ($account_id != null) { // Log the user in with the details provided session_regenerate_id(); $_SESSION['account_loggedin'] = TRUE; $_SESSION['account_id'] = $account_id; $_SESSION['account_role'] = $account ? $account['role'] : 'Member'; } //Process Payment require_once __DIR__."/lib/paypal/paypal.php"; $base = PAYPAL_URL; $id = PAYPAL_CLIENT_ID; $secret = PAYPAL_CLIENT_SECRET; //init input $order = $transaction_id; $price = $payment_amount; $currency = "EUR"; //make payment $paypal = new paypalCurl(); $paypal->init($id,$secret,$base); $result = $paypal->makePaymentURL($order,$price,$currency); if ($result->status === true) { header("location:". $result->url); die; } else { //raise error echo $result->msg; die; } } } } //------------------------------- // END PLACE ORDER //------------------------------- $terms_link = url('index.php?page=termsandconditions'); template_header('Checkout'); $view = '

'.$h1_checkout.'

'.implode('
', $errors).'

'; if (!isset($_SESSION['account_loggedin'])){ $view .= '

'.$account_available.' '.$account_log_in.'

'; } $view .= '

'.$payment_method.'

'; if (mollie_enabled){ $view .= ' '; } if (paypal_enabled){ $view .= ' '; } if (pay_on_delivery_enabled){ $view .= ' '; } $view .= '
'; if (!isset($_SESSION['account_loggedin'])){ $view .= '

'.$account_create_email.'

'.$account_create.((!account_required) ? $account_create_optional : '').'

'; } $view .= '

'.$h2_Shipping_details.'

'.$h2_shoppingcart.'

'; foreach($products_in_cart['cart_details']['products'] as $product){ $view .= ' '; } $view .= '
'.$product['meta']['name'].' '.$product['quantity'].' x '.$product['meta']['name'].' '.currency_code.''.number_format($product['options_price'] * $product['quantity'],2).'
'; if (isset($_SESSION['discount'], $products_in_cart['totals']['discounttotal'])){ $view .= $products_in_cart['totals']['discount_message']; } $view .= '
'; if ($shipping_methods_available){ $view .= '

'.$h3_shipping_method.'

'; foreach($shipping_methods as $k => $method){ if (!in_array($method['id'], $shipping_methods_available)){ $view .= '
'; } $view .= '
'; } } $view .= '
'.$total_subtotal.' '.currency_code.''.number_format($subtotal,2).'
'.$total_shipping.' '.currency_code.''.number_format($shippingtotal,2).'
'; if ($discounttotal > 0){ $view .= '
'.$total_discount.' -'.currency_code.''.number_format(round($discounttotal, 1),2).'
'; } if ($taxtotal > 0){ $view .= '
VAT ('.$tax_rate.') '.currency_code.''.number_format($taxtotal,2).'
'; } $view .= '
'.$total_total.' '.$total_total_note.''.currency_code.''.number_format($total,2).'
'.$order_consent_1.'
'.$order_consent_2.' '.$order_consent_3.'
'; //OUTPUT echo $view; template_footer(); ?>