diff --git a/.gitignore b/.gitignore index 45c2d7f..49893ec 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ productold.php +test.php diff --git a/cart.php b/cart.php index 8330425..a1a6f63 100644 --- a/cart.php +++ b/cart.php @@ -40,30 +40,33 @@ if ((isset($_POST['update']) || isset($_POST['checkout'])) && isset($_SESSION['c } // Check if accessoiries are added - -if (isset($_POST['accessoiries'])){ - $options = ''; - $quantity = 1; - $cart_product = &get_cart_product($_POST['add_product_id'], $options); - - if ($cart_product) { - // Product exists in cart, update the quanity - $cart_product['quantity'] += $quantity; - } else { - // Product is not in cart, add it - $_SESSION['cart'][] = [ - 'id' => $_POST['add_product_id'], - 'quantity' => $quantity, - 'options' => $options, - 'options_price' => $_POST['add_product_price'], - 'options_weight' => $_POST['add_product_weight'], - 'shipping_price' => 0.00 - ]; +if (isset($_POST['product'])) { + //VALIDATE THE INPUT FOR THE SHOPPING CART + $payload = json_encode($_POST['product'], JSON_UNESCAPED_UNICODE); + $product_to_cart = ioAPIv2('/v2/shopping_cart/',$payload,$clientsecret); + $product_to_cart = json_decode($product_to_cart,true); + // Check if the product exists (array is not empty) + if ($product_to_cart['quantity'] > 0) { + // Product exists in database, now we can create/update the session variable for the cart + if (!isset($_SESSION['cart'])) { + // Shopping cart session variable doesnt exist, create it + $_SESSION['cart'] = []; + } + $cart_product = &get_cart_product($product_to_cart['id'], $product_to_cart['options']); + if ($cart_product) { + // Product exists in cart, update the quanity + $cart_product['quantity'] += $quantity; + } else { + // Product is not in cart, add it + $_SESSION['cart'][] = $product_to_cart; + } } + // Prevent form resubmission... + header('Location: ' . url('index.php?page=cart')); + exit; } // Check if samples are added - if (isset($_POST['samples'])){ $options = $h2_cart_sample_product; $quantity = 1; @@ -184,10 +187,10 @@ $view .= ' if (!empty($products_in_cart) && !empty(category_id_checkout_suggestions)){ $view .= getAccessoiries($clientsecret,category_id_checkout_suggestions); } - // SAMPLES + /* SAMPLES if (!empty($products_in_cart) && !empty(category_id_checkout_samples)){ $view .= getSamples($clientsecret,category_id_checkout_samples); - } + }*/ $view .= '
'.$total_subtotal.' diff --git a/checkout.php b/checkout.php index a452af9..0a451a6 100644 --- a/checkout.php +++ b/checkout.php @@ -26,6 +26,7 @@ $discounttotal = 0.00; $taxtotal = 0.00; $tax_rate = ''; $weighttotal = 0; +$shipping_methods = []; $checkout_input = [ "selected_country" => isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'], @@ -34,11 +35,17 @@ $checkout_input = [ "discount_code" => isset($_SESSION['discount']) ? $_SESSION['discount'] : '' ]; -$selected_shipping_method_name = ''; -$shipping_methods_available = []; // Error array, output errors on the form $errors = []; +//CALL TO API FOR shipping +$api_url = '/v2/taxes/'; +$countries = ioAPIv2($api_url,'',$clientsecret); +//Decode Payload +if (!empty($countries)){$countries = json_decode($countries,true);}else{$countries = null;} +//CountryID mapping +$countryMap = array_column($countries, 'country', 'id'); + // --------------------------------------------- // End defaults -------------------------------- // --------------------------------------------- @@ -63,12 +70,15 @@ if (isset($_POST['discount_code']) && !empty($_POST['discount_code'])) { } else if (isset($_POST['discount_code']) && empty($_POST['discount_code']) && isset($_SESSION['discount'])) { unset($_SESSION['discount']); } - +if (isset($_POST['address_country'])){ + // Retrieve shipping methods + $shipping_methods = ioAPIv2('/v2/shipping/list=methods&country='.$checkout_input['selected_country'].'&price_total='.$subtotal.'&weight_total='.$weighttotal,'',$clientsecret); + $shipping_methods = json_decode($shipping_methods,true); +} //------------------------------- // 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); @@ -82,25 +92,24 @@ if ($products_in_cart) { $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); + // Retrieve shipping methods + $shipping_methods = ioAPIv2('/v2/shipping/list=methods&country='.$checkout_input['selected_country'].'&price_total='.$subtotal.'&weight_total='.$weighttotal,'',$clientsecret); + $shipping_methods = json_decode($shipping_methods,true); + // 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 //------------------------------- @@ -198,119 +207,122 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a $_SESSION['account_id'] = $account_id; $_SESSION['account_role'] = $account ? $account['role'] : 'Member'; } - } - // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Pay on delivery = 2 - // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Pay on delivery = 2 + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - if (pay_on_delivery_enabled && $place_order['payment_method'] == 2){ - header('Location: ' . url('index.php?page=placeorder')); - exit; - } - - // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - // Mollie = 0 ++++++++++++++++++++++++++++++++++++++++++++++++++ - // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - if (mollie_enabled && $_POST['method'] == 0) { - - 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 = $place_order['transaction_id']; - $value = number_format($place_order['payment_amount'],2,'.',''); + if (pay_on_delivery_enabled && $place_order['payment_method'] == 2){ + header('Location: ' . url('index.php?page=placeorder')); + exit; + } - /* - * 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. - */ + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + // Mollie = 0 ++++++++++++++++++++++++++++++++++++++++++++++++++ + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - if (rewrite_url){ - $redirectURL = $protocol.'://'.$hostname.$path.'placeorder/'.$orderId; - }else{ - $redirectURL = $protocol.'://'.$hostname.$path.'index.php?page=placeorder&order_id='.$orderId; + if (mollie_enabled && $_POST['method'] == 0) { + + 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 = $place_order['transaction_id']; + $value = number_format($place_order['payment_amount'],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 customer to checkout + header("Location: " . $payment->getCheckoutUrl(), true, 303); + + } catch (\Mollie\Api\Exceptions\ApiException $e) { + echo "API call failed: " . htmlspecialchars($e->getMessage()); } - - $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 customer to checkout - header("Location: " . $payment->getCheckoutUrl(), true, 303); - - } catch (\Mollie\Api\Exceptions\ApiException $e) { - echo "API call failed: " . htmlspecialchars($e->getMessage()); + exit; } - exit; - } - // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - // PayPal Payment = 1 +++++++++++++++++++++++++++++++++++++++++ - // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + // PayPal Payment = 1 +++++++++++++++++++++++++++++++++++++++++ + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - if (paypal_enabled && $_POST['method'] == 'paypal') { - - //Process Payment - require_once __DIR__."/lib/paypal/paypal.php"; + if (paypal_enabled && $_POST['method'] == 'paypal') { + + //Process Payment + require_once __DIR__."/lib/paypal/paypal.php"; - $base = PAYPAL_URL; - $id = PAYPAL_CLIENT_ID; - $secret = PAYPAL_CLIENT_SECRET; - - //init input - $order = $place_order['transaction_id']; - $price = number_format($place_order['payment_amount'],2,'.',''); - $currency = "EUR"; + $base = PAYPAL_URL; + $id = PAYPAL_CLIENT_ID; + $secret = PAYPAL_CLIENT_SECRET; - //make payment - $paypal = new paypalCurl(); - $paypal->init($id,$secret,$base); - $result = $paypal->makePaymentURL($order,$price,$currency); + //init input + $order = $place_order['transaction_id']; + $price = number_format($place_order['payment_amount'],2,'.',''); + $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; + if ($result->status === true) { + header("location:". $result->url); + die; + } + else { //raise error + echo $result->msg; + die; + } } - else { //raise error - echo $result->msg; - die; + } else { + foreach ($place_order['error'] as $error){ + $errors[] = $error; } } - } } @@ -412,8 +424,8 @@ $view .= ' @@ -444,21 +456,19 @@ $view .= '
'; - if ($shipping_methods_available){ + if (isset($shipping_methods) && count($shipping_methods) > 0){ $view .= '

'.$h3_shipping_method.'

'; - foreach($shipping_methods as $k => $method){ - - if (!in_array($method['id'], $shipping_methods_available)){ - $view .= '
- - + foreach($shipping_methods as $method){ + $view .= '
+ +
'; - } - $view .= '
'; } - } + $view .= '
'; + + } $view .= '
diff --git a/custom/email/order-invoice-template.php b/custom/email/order-invoice-template.php index 6930a79..7f3c952 100644 --- a/custom/email/order-invoice-template.php +++ b/custom/email/order-invoice-template.php @@ -4,21 +4,20 @@ -
-
-
- ,
- +
+
+ ,
+
-

Invoice:

-

Date:

+

Invoice:

+

Date:

@@ -39,45 +38,43 @@ + foreach($invoice_cust['products'] as $product): ?> - - - - - + + + + + - - + - + - + - + - +
-

Het totaalbedrag van deze factuur is betaald

diff --git a/custom/settings/config.php b/custom/settings/config.php index 9d83d45..b71a4a8 100644 --- a/custom/settings/config.php +++ b/custom/settings/config.php @@ -149,7 +149,9 @@ define('db_user','morvalwatches');//morvalwatches_prod define('db_pass','4~gv71bM6'); // Database name define('db_name','shoppingcart_advanced'); //morvalwatches -// API BASE URL +/* API */ +define('clientID','paul@veliti.nl'); //morvalwatches +define('clientsecret','test1234'); //morvalwatches define('api_url','https://dev.veliti.nl/api.php'); //morvalwatches define('img_url',substr(api_url, 0, -8)); diff --git a/functions.php b/functions.php index 1216410..a513784 100644 --- a/functions.php +++ b/functions.php @@ -339,9 +339,9 @@ function getAccessoiries($clientsecret, $categoryID){ '.$additional_product['productname'].'
- - - + + +
@@ -431,7 +431,7 @@ function createGiftCart($pdo, $orderID){ $giftcard_ID = giftcard_id; //Check if Giftcard is ordered - $stmt = $pdo->prepare('SELECT t.payer_email as email, ti.id as id, ti.txn_id as txn, ti.item_price as item_price, ti.item_quantity as item_quantity FROM transactions t INNER JOIN transactions_items ti ON t.txn_id = ti.txn_id INNER JOIN products_categories p ON ti.item_id = p.product_id WHERE p.category_id = ? AND ti.txn_id = ?'); + $stmt = $pdo->prepare('SELECT t.payer_email as email, ti.id as id, ti.txn_id as txn, ti.item_price as item_price, ti.item_quantity as item_quantity FROM transactions t INNER JOIN transactions_items ti ON t.id = ti.txn_id INNER JOIN products_categories p ON ti.item_id = p.product_id WHERE p.category_id = ? AND t.txn_id = ?'); $stmt->execute([$giftcard_ID,$orderID]); $giftcards = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -508,46 +508,16 @@ function removeGiftCart($pdo, $orderID){ } } -function generateInvoice($pdo, $orderID){ +function generateInvoice($invoice,$orderID){ - // Retrieve order items - $stmt = $pdo->prepare('SELECT ti.*, p.productcode, p.name FROM transactions t JOIN transactions_items ti ON ti.txn_id = t.txn_id LEFT JOIN products p ON p.id = ti.item_id WHERE t.txn_id = ?'); - $stmt->execute([ $orderID ]); - $order_items = $stmt->fetchAll(PDO::FETCH_ASSOC); - - // Retrieve order details - $stmt = $pdo->prepare('SELECT a.email, a.id AS a_id, a.first_name AS a_first_name, a.last_name AS a_last_name, a.address_street AS a_address_street, a.address_city AS a_address_city, a.address_state AS a_address_state, a.address_zip AS a_address_zip, a.address_country AS a_address_country, t.* FROM transactions t LEFT JOIN transactions_items ti ON ti.txn_id = t.txn_id LEFT JOIN accounts a ON a.id = t.account_id WHERE t.txn_id = ?'); - $stmt->execute([ $orderID]); - $order = $stmt->fetch(PDO::FETCH_ASSOC); - - // Get tax - $stmt = $pdo->prepare('SELECT * FROM taxes WHERE country = ?'); - $stmt->execute([$order['a_address_country']]); - $tax = $stmt->fetch(PDO::FETCH_ASSOC); - $tax_rate = $tax ? $tax['rate'] : 0.00; - //$stmt->debugDumpParams(); //Variables - $customer_email = htmlspecialchars($order['payer_email'] ?? '', ENT_QUOTES); - $address_name = htmlspecialchars($order['first_name'] ?? '', ENT_QUOTES).' '.htmlspecialchars($order['last_name'] ?? '', ENT_QUOTES); - $address_street = htmlspecialchars($order['address_street'] ?? '', ENT_QUOTES); - $address_city = htmlspecialchars($order['address_city'] ?? '', ENT_QUOTES); - $address_state = htmlspecialchars($order['address_state'] ?? '', ENT_QUOTES); - $address_zip = htmlspecialchars($order['address_zip'] ?? '', ENT_QUOTES); - $address_country = htmlspecialchars($order['address_country'] ?? '', ENT_QUOTES); - - $order_id = $order['id']; - $products = $order_items; - $shippingtotal = $order['shipping_amount']; - $total = $order['payment_amount']; - $taxtotal = $order['tax_amount']; - $order_created = $order['created']; - + $customer_email = htmlspecialchars($invoice['customer']['email'] ?? '', ENT_QUOTES); //Generate invoice ob_start(); include dirname(__FILE__).'/custom/email/order-invoice-template.php'; $order_invoice_template = ob_get_clean(); - return array($order_invoice_template,$customer_email,$order_id); + return array($order_invoice_template,$customer_email,$orderId); } function freeShipment($price, $type){ diff --git a/index.php b/index.php index 11ec304..61ebbe9 100644 --- a/index.php +++ b/index.php @@ -12,22 +12,22 @@ define('base_url', rtrim($base_url, '/') . '/'); // Initialize a new session session_start(); -// Include the configuration file, this contains settings you can change. +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +// Includes +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ include './custom/settings/config.php'; -// Include functions and connect to the database using PDO MySQL include 'functions.php'; -// Include translation file include './custom/translations/translations_'.strtoupper(language_code).'.php'; +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ //LOGIN TO API -$data = json_encode(array("username" => "paul@veliti.nl", "password" => "test1234"), JSON_UNESCAPED_UNICODE); +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +$data = json_encode(array("clientID" => clientID, "clientsecret" => clientsecret), JSON_UNESCAPED_UNICODE); $responses = ioAPIv2('/v2/authorization', $data,''); //Decode Payload if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = '400';} $clientsecret = $responses['token']; -// Connect to MySQL database -$pdo = pdo_connect_mysql(); // Output error variable $error = ''; //error reporting diff --git a/product.php b/product.php index aa37367..431aebb 100644 --- a/product.php +++ b/product.php @@ -2,19 +2,6 @@ // Prevent direct access to file defined(security_key) or exit; -//+++++++++++++++++++++++++++++++++++++++++++++ -// TODO -//+++++++++++++++++++++++++++++++++++++++++++++ -/* - -3. product notifier when out of stock - -*/ -//+++++++++++++++++++++++++++++++++++++++++++++ -// END TODO -//+++++++++++++++++++++++++++++++++++++++++++++ - - // Check to make sure the id parameter is specified in the URL if (isset($_GET['id'])) { @@ -45,12 +32,10 @@ if (isset($_GET['id'])) { // If the user clicked the add to cart button if (isset($_POST['product'])) { - //VALIDATE THE INPUT FOR THE SHOPPING CART $payload = json_encode($_POST['product'], JSON_UNESCAPED_UNICODE); $product_to_cart = ioAPIv2('/v2/shopping_cart/',$payload,$clientsecret); $product_to_cart = json_decode($product_to_cart,true); - // Check if the product exists (array is not empty) if ($product_to_cart['quantity'] > 0) { // Product exists in database, now we can create/update the session variable for the cart @@ -69,8 +54,7 @@ if (isset($_GET['id'])) { } // Prevent form resubmission... header('Location: ' . url('index.php?page=cart')); - exit; - + exit; } diff --git a/webhook.php b/webhook.php index 828ddda..145c07e 100644 --- a/webhook.php +++ b/webhook.php @@ -2,18 +2,26 @@ //Define security for webhook -> factuur define('interface', true); -// Include the configuration file, this contains settings you can change. +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +// Includes +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ include '/custom/settings/config.php'; -// Include functions and connect to the database using PDO MySQL include 'functions.php'; -// Connect to MySQL database -$pdo = pdo_connect_mysql(); -/* - * How to verify Mollie API Payments in a webhook. - * - * See: https://docs.mollie.com/guides/webhooks - */ +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +//LOGIN TO API +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +$data = json_encode(array("clientID" => clientID, "clientsecret" => clientsecret), JSON_UNESCAPED_UNICODE); +$responses = ioAPIv2('/v2/authorization', $data,''); +//Decode Payload +if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = '400';} +$clientsecret = $responses['token']; + +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +// BASEURL is required for invoice template +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +$base_url = 'https://'.$_SERVER['SERVER_NAME'].'/'; +define('base_url', $base_url); try { /* @@ -23,94 +31,121 @@ try { */ require "initialize.php"; - /* - * Retrieve the payment's current state.tr_ZFpQZZMZ76 - */ + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Retrieve the payment's current state.tr_ZFpQZZMZ76 + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + $payment = $mollie->payments->get($_POST["id"]); $orderId = $payment->metadata->order_id; - /* - * Update the order in the database. - */ - // database_write($orderId, $payment->status); - - // Update order_status to Paid - $stmt = $pdo->prepare('UPDATE transactions SET payment_status = ? WHERE txn_id = ?'); + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + // Update the order in the database. + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ - if ($payment->isPaid() && ! $payment->hasRefunds() && ! $payment->hasChargebacks()) { - /* - * The payment is paid and isn't refunded or charged back. - * At this point you'd probably want to start the process of delivering the product to the customer. - */ - $stmt->execute(["Paid", $orderId]); - - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Order is Paid. Create Giftcards when applicable - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - createGiftCart($pdo, $orderId); - - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Send the invoice when status is Paid - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - $base_url = 'https://'.$_SERVER['SERVER_NAME'].'/'; - define('base_url', $base_url); - - list($data,$customer_email,$order_id) = generateInvoice($pdo,$orderId); - $dompdf->loadHtml($data); - - // (Optional) Setup the paper size and orientation - $dompdf->setPaper('A4', 'portrait'); - - // Render the HTML as PDF - $dompdf->render(); - $subject = 'MorvalWatches - Invoice: '.$order_id; - $attachment = $dompdf->output(); + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + //The payment is paid and isn't refunded or charged back. + //At this point you'd probably want to start the process of delivering the product to the customer. + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + //UPDATE THE PAYMENT STATUS + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 1, "giftcard_categoryID" => giftcard_id), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + $transaction = json_decode($transaction,true); - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Send to PHPMailer - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - send_mail_by_PHPMailer($customer_email, $subject, $data, $attachment, $subject); + if ($transaction !== null && !empty($transaction)) { + + if(count($transaction) > 0) { + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Generate INVOICE RECORD + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $payload = json_encode(array("txn_id" => $transaction['transaction_id']), JSON_UNESCAPED_UNICODE); + $invoice = ioAPIv2('/v2/invoice/',$payload,$clientsecret); + $invoice = json_decode($invoice,true); + + if ($invoice !== null && !empty($invoice)) { + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Generate INVOICE TO CUSTOMER + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $invoice_cust = ioAPIv2('/v2/invoice/list=invoice&id='.$invoice['invoice_id'],'',$clientsecret); + $invoice_cust = json_decode($invoice_cust,true); + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Send the invoice when status is Paid + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + list($data,$customer_email,$order_id) = generateInvoice($invoice_cust,$orderId); + + //CREATE PDF + $dompdf->loadHtml($data); + // (Optional) Setup the paper size and orientation + $dompdf->setPaper('A4', 'portrait'); + + // Render the HTML as PDF + $dompdf->render(); + $subject = ($invoice_morval_subject ?? 'MorvalWatches - Invoice: ').$order_id; + $attachment = $dompdf->output(); + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Send to PHPMailer + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + send_mail_by_PHPMailer($customer_email, $subject, $data, $attachment, $subject); - if(invoice_bookkeeping){ - send_mail_by_PHPMailer(email_bookkeeping, $subject, $data, $attachment, $subject); + if(invoice_bookkeeping){ + send_mail_by_PHPMailer(email_bookkeeping, $subject, $data, $attachment, $subject); + } + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + } + } } - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - // + } elseif ($payment->isOpen()) { /* - * The payment is open. + * The payment is open. status = Pending = 101 */ - $stmt->execute(["Pending", $orderId]); + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 101), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + } elseif ($payment->isPending()) { /* - * The payment is pending. + * The payment is pending.status = Pending = 101 */ - $stmt->execute(["Pending", $orderId]); + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 101), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + } elseif ($payment->isFailed()) { /* - * The payment has failed. + * The payment has failed.status = Failed = 102 */ - $stmt->execute(["Failed", $orderId]); + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 102), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + } elseif ($payment->isExpired()) { /* - * The payment is expired. + * The payment is expired.status = Expired= 103 */ - $stmt->execute(["Pending", $orderId]); + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 103), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + } elseif ($payment->isCanceled()) { /* - * The payment has been canceled. + * The payment has been status = Cancelled= 103 */ - $stmt->execute(["Cancelled", $orderId]); + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 999), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + } elseif ($payment->hasRefunds()) { /* * The payment has been (partially) refunded. * The status of the payment is still "paid" + * status = Paid = 1 */ - $stmt->execute(["Refunded", $orderId]); - + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 1), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + //Order is refunded - disable giftcards useGiftCart($pdo, $orderId); diff --git a/webhook_paypal.php b/webhook_paypal.php index e9ea571..58d8752 100644 --- a/webhook_paypal.php +++ b/webhook_paypal.php @@ -3,8 +3,16 @@ include '/custom/settings/config.php'; // Include functions and connect to the database using PDO MySQL include 'functions.php'; -// Connect to MySQL database -$pdo = pdo_connect_mysql(); + +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +//LOGIN TO API +//+++++++++++++++++++++++++++++++++++++++++++++++++++++ +$data = json_encode(array("clientID" => clientID, "clientsecret" => clientsecret), JSON_UNESCAPED_UNICODE); +$responses = ioAPIv2('/v2/authorization', $data,''); +//Decode Payload +if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = '400';} +$clientsecret = $responses['token']; + // paypal require_once __DIR__."/lib/paypal/paypal.php"; @@ -36,47 +44,60 @@ if($token !=''){ //IF TXN_ID is not empty if ($orderId !='' && $result->ref == 'COMPLETED'){ - //CHECK IF ORDER EXISTS - $stmt = $pdo->prepare('SELECT * FROM transactions WHERE txn_id = ?'); - $stmt->execute([$orderId]); - if ($stmt->fetch(PDO::FETCH_ASSOC)){ - //TXN EXISTS - UPDATE TO PAID - $stmt = $pdo->prepare('UPDATE transactions SET payment_status = ? WHERE txn_id = ?'); - $stmt->execute(["Paid", $orderId]); - - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Order is Paid. Create Giftcards when applicable - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - createGiftCart($pdo, $orderId); - - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Send the invoice when status is Paid - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - list($data,$customer_email,$order_id) = generateInvoice($pdo,$orderId); - $dompdf->loadHtml($data); + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + //UPDATE THE PAYMENT STATUS + //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + $payload = json_encode(array("txn_id" => $orderId, "payment_status" => 1,"giftcard_categoryID" => giftcard_id), JSON_UNESCAPED_UNICODE); + $transaction = ioAPIv2('/v2/transactions/',$payload,$clientsecret); + $transaction = json_decode($transaction,true); - // (Optional) Setup the paper size and orientation - $dompdf->setPaper('A4', 'portrait'); + if ($transaction !== null && !empty($transaction)) { + + if(count($transaction) > 0) { + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Generate INVOICE RECORD + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $payload = json_encode(array("txn_id" => $transaction['transaction_id']), JSON_UNESCAPED_UNICODE); + $invoice = ioAPIv2('/v2/invoice/',$payload,$clientsecret); + $invoice = json_decode($invoice,true); + + if ($invoice !== null && !empty($invoice)) { + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Generate INVOICE TO CUSTOMER + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $invoice_cust = ioAPIv2('/v2/invoice/list=invoice&id='.$invoice['invoice_id'],'',$clientsecret); + $invoice_cust = json_decode($invoice_cust,true); + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Send the invoice when status is Paid + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + list($data,$customer_email,$order_id) = generateInvoice($invoice_cust,$orderId); + + //CREATE PDF + $dompdf->loadHtml($data); + // (Optional) Setup the paper size and orientation + $dompdf->setPaper('A4', 'portrait'); + + // Render the HTML as PDF + $dompdf->render(); + $subject = ($invoice_morval_subject ?? 'MorvalWatches - Invoice: ').$order_id; + $attachment = $dompdf->output(); + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //Send to PHPMailer + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + send_mail_by_PHPMailer($customer_email, $subject, $data, $attachment, $subject); - // Render the HTML as PDF - $dompdf->render(); - $subject = 'MorvalWatches - Invoice: '.$order_id; - $attachment = $dompdf->output(); - - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - //Send to PHPMailer - //++++++++++++++++++++++++++++++++++++++++++++++++++++++ - send_mail_by_PHPMailer($customer_email, $subject, $data, $attachment, $subject); - - if(invoice_bookkeeping){ - send_mail_by_PHPMailer(email_bookkeeping, $subject, $data, $attachment, $subject); + if(invoice_bookkeeping){ + send_mail_by_PHPMailer(email_bookkeeping, $subject, $data, $attachment, $subject); + } + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + //++++++++++++++++++++++++++++++++++++++++++++++++++++++ + } } - //REDIRECT TO PLACEORDER SCREEN - header('Location: ' . url('index.php?page=placeorder')); - exit; - } + } } else { //GET TXN FROM RETURN LINK $orderId = $_GET['txn'] ?? '';