CMXX - Webhooks and giftcards

This commit is contained in:
“VeLiTi”
2025-02-19 12:11:44 +01:00
parent d85923c299
commit 0e9d133ff9
10 changed files with 358 additions and 335 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
productold.php productold.php
test.php

View File

@@ -40,30 +40,33 @@ if ((isset($_POST['update']) || isset($_POST['checkout'])) && isset($_SESSION['c
} }
// Check if accessoiries are added // Check if accessoiries are added
if (isset($_POST['product'])) {
if (isset($_POST['accessoiries'])){ //VALIDATE THE INPUT FOR THE SHOPPING CART
$options = ''; $payload = json_encode($_POST['product'], JSON_UNESCAPED_UNICODE);
$quantity = 1; $product_to_cart = ioAPIv2('/v2/shopping_cart/',$payload,$clientsecret);
$cart_product = &get_cart_product($_POST['add_product_id'], $options); $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) { if ($cart_product) {
// Product exists in cart, update the quanity // Product exists in cart, update the quanity
$cart_product['quantity'] += $quantity; $cart_product['quantity'] += $quantity;
} else { } else {
// Product is not in cart, add it // Product is not in cart, add it
$_SESSION['cart'][] = [ $_SESSION['cart'][] = $product_to_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
];
} }
} }
// Prevent form resubmission...
header('Location: ' . url('index.php?page=cart'));
exit;
}
// Check if samples are added // Check if samples are added
if (isset($_POST['samples'])){ if (isset($_POST['samples'])){
$options = $h2_cart_sample_product; $options = $h2_cart_sample_product;
$quantity = 1; $quantity = 1;
@@ -184,10 +187,10 @@ $view .= '</tbody>
if (!empty($products_in_cart) && !empty(category_id_checkout_suggestions)){ if (!empty($products_in_cart) && !empty(category_id_checkout_suggestions)){
$view .= getAccessoiries($clientsecret,category_id_checkout_suggestions); $view .= getAccessoiries($clientsecret,category_id_checkout_suggestions);
} }
// SAMPLES /* SAMPLES
if (!empty($products_in_cart) && !empty(category_id_checkout_samples)){ if (!empty($products_in_cart) && !empty(category_id_checkout_samples)){
$view .= getSamples($clientsecret,category_id_checkout_samples); $view .= getSamples($clientsecret,category_id_checkout_samples);
} }*/
$view .= ' $view .= '
<div class="total"> <div class="total">
<span class="text">'.$total_subtotal.'</span> <span class="text">'.$total_subtotal.'</span>

View File

@@ -26,6 +26,7 @@ $discounttotal = 0.00;
$taxtotal = 0.00; $taxtotal = 0.00;
$tax_rate = ''; $tax_rate = '';
$weighttotal = 0; $weighttotal = 0;
$shipping_methods = [];
$checkout_input = [ $checkout_input = [
"selected_country" => isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'], "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'] : '' "discount_code" => isset($_SESSION['discount']) ? $_SESSION['discount'] : ''
]; ];
$selected_shipping_method_name = '';
$shipping_methods_available = [];
// Error array, output errors on the form // Error array, output errors on the form
$errors = []; $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 -------------------------------- // 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'])) { } else if (isset($_POST['discount_code']) && empty($_POST['discount_code']) && isset($_SESSION['discount'])) {
unset($_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 there are products in cart handle the checkout
//------------------------------- //-------------------------------
if ($products_in_cart) { if ($products_in_cart) {
//Calculate shopping_cart //Calculate shopping_cart
$payload = json_encode(array("cart" => $products_in_cart, "checkout_input" => $checkout_input), JSON_UNESCAPED_UNICODE); $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 = ioAPIv2('/v2/checkout/',$payload,$clientsecret);
@@ -83,24 +93,23 @@ if ($products_in_cart) {
$weighttotal = $products_in_cart['totals']['weighttotal']; $weighttotal = $products_in_cart['totals']['weighttotal'];
$total = $products_in_cart['totals']['total']; $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 // Retrieve shipping methods
$stmt = $pdo->query('SELECT * FROM shipping'); $shipping_methods = ioAPIv2('/v2/shipping/list=methods&country='.$checkout_input['selected_country'].'&price_total='.$subtotal.'&weight_total='.$weighttotal,'',$clientsecret);
$shipping_methods = $stmt->fetchAll(PDO::FETCH_ASSOC); $shipping_methods = json_decode($shipping_methods,true);
// Redirect the user if the shopping cart is empty // Redirect the user if the shopping cart is empty
if (empty($products_in_cart)) { if (empty($products_in_cart)) {
header('Location: ' . url('index.php?page=cart')); header('Location: ' . url('index.php?page=cart'));
exit; exit;
} }
//------------------------------- //-------------------------------
// END Checkout handler // END Checkout handler
//------------------------------- //-------------------------------
} }
//------------------------------- //-------------------------------
//Place order //Place order
//------------------------------- //-------------------------------
@@ -198,7 +207,6 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a
$_SESSION['account_id'] = $account_id; $_SESSION['account_id'] = $account_id;
$_SESSION['account_role'] = $account ? $account['role'] : 'Member'; $_SESSION['account_role'] = $account ? $account['role'] : 'Member';
} }
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Pay on delivery = 2 //Pay on delivery = 2
@@ -310,7 +318,11 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a
die; die;
} }
} }
} else {
foreach ($place_order['error'] as $error){
$errors[] = $error;
}
}
} }
} }
@@ -412,8 +424,8 @@ $view .= '
<label for="address_country">'.$shipping_country.'</label> <label for="address_country">'.$shipping_country.'</label>
<select name="address_country" class="ajax-update form-field" required>'; <select name="address_country" class="ajax-update form-field" required>';
foreach(get_countries() as $country){ foreach($countries as $country){
$view .= ' <option value="'.$country.'" '.($country==$account['address_country'] ? ' selected' : '').'>'.$country.'</option>'; $view .= ' <option value="'.$country['id'].'" '.($country['id']==$account['address_country'] ? ' selected' : '').'>'.(${$countryMap[$country['id']]} ?? $countryMap[$country['id']]).'</option>';
} }
$view .= ' </select> $view .= ' </select>
@@ -444,20 +456,18 @@ $view .= ' </span>
</div> </div>
<div class="shipping-methods-container">'; <div class="shipping-methods-container">';
if ($shipping_methods_available){ if (isset($shipping_methods) && count($shipping_methods) > 0){
$view .= ' <div class="shipping-methods"> $view .= ' <div class="shipping-methods">
<h3>'.$h3_shipping_method.'</h3>'; <h3>'.$h3_shipping_method.'</h3>';
foreach($shipping_methods as $k => $method){ foreach($shipping_methods as $method){
if (!in_array($method['id'], $shipping_methods_available)){
$view .= ' <div class="shipping-method"> $view .= ' <div class="shipping-method">
<input type="radio" class="ajax-update" id="sm'.$k.'" name="shipping_method" value="'.$method['id'].'" required'.($selected_shipping_method==$method['id'] ? ' checked':'').'> <input type="radio" class="ajax-update" id="sm'.$method['id'].'" name="shipping_method" value="'.$method['id'].'" required'.($checkout_input['selected_shipment_method']==$method['id'] ? ' checked':'').'>
<label for="sm'.$k.'">'.$method['name'].' ('.currency_code.''.number_format($method['price'], 2).''.$method['type']=='Single Product'?' per item':''.')</label> <label for="sm'.$method['id'].'">'.$method['name'].' ('.currency_code.''.number_format($method['price'], 2).')</label>
</div>'; </div>';
} }
$view .= '</div>'; $view .= '</div>';
}
} }
$view .= ' </div> $view .= ' </div>
<div class="summary"> <div class="summary">

View File

@@ -4,21 +4,20 @@
<?=template_order_email_header()?> <?=template_order_email_header()?>
<?php include './custom/translations/translations_'.strtoupper(language_code).'.php';?> <?php include './custom/translations/translations_'.strtoupper(language_code).'.php';?>
</tr> </tr>
<tr><td><br></td></tr> <tr><td><br></td></tr>
<tr> <tr>
<td> <td>
<?=$address_name?><br> <?=$invoice_cust['customer']['name']?><br>
<?=$address_street?><br> <?=$invoice_cust['customer']['street']?><br>
<?=$address_zip?>, <?=$address_city?><br> <?=$invoice_cust['customer']['zip']?>, <?=$invoice_cust['customer']['city']?><br>
<?=$address_country?> <?=$invoice_cust['customer']['country']?>
</td> </td>
</tr> </tr>
<tr><td><br></td></tr> <tr><td><br></td></tr>
<tr> <tr>
<td><h2>Invoice: <?=$order_id?></h2></td> <td><h2>Invoice: <?=$invoice_cust['invoice']['id']?></h2></td>
<td><p>Date: <?php echo date("Y-m-d", strtotime($order_created))?></p></td> <td><p>Date: <?php echo date("Y-m-d", strtotime($invoice_cust['invoice']['created']))?></p></td>
</tr> </tr>
</table> </table>
@@ -39,45 +38,43 @@
</thead> </thead>
<tbody> <tbody>
<?php <?php
$subtotal = 0; foreach($invoice_cust['products'] as $product): ?>
foreach($products as $product): ?>
<tr> <tr>
<td><?=$product['name']?></td> <td><?=${$product['product_name']} ?? $product['product_name'] ?></td>
<td><?=$product['item_options']?></td> <td><?=implode(", ", $product['options'])?></td>
<td><?=$product['item_quantity']?></td> <td><?=$product['quantity']?></td>
<td><?=currency_code?> <?=number_format($product['item_price'],2)?></td> <td><?=currency_code?> <?=number_format($product['price'],2)?></td>
<td style="text-align:right;"><?=currency_code?> <?=number_format($product['item_price'] * $product['item_quantity'],2)?></td> <td style="text-align:right;"><?=currency_code?> <?=number_format($product['line_total'],2)?></td>
</tr> </tr>
<?php $subtotal += $product['item_price']*$product['item_quantity'];?>
<?php endforeach; ?> <?php endforeach; ?>
<tr> <tr>
<td colspan="5" class="item-list-end"></td> <td colspan="5" class="item-list-end"></td>
</tr> </tr>
<tr> <tr>
<td colspan="4" class="subtotal"><?=$total_subtotal?></td> <td colspan="4" class="subtotal"><?=$total_subtotal?></td>
<td class="num"><?=currency_code?> <?=number_format($subtotal,2)?></td> <td class="num"><?=currency_code?> <?=number_format($invoice_cust['pricing']['subtotal'],2)?></td>
</tr> </tr>
<tr> <tr>
<td colspan="4" class="subtotal"><?=$total_discount?></td> <td colspan="4" class="subtotal"><?=$total_discount?></td>
<td class="num"><?=currency_code?> <?=number_format($total-($subtotal+$shippingtotal),2)?></td> <td class="num"><?=currency_code?> <?=number_format($invoice_cust['pricing']['discount_total'],2)?></td>
</tr> </tr>
<tr> <tr>
<td colspan="4" class="shipping"><?=$total_shipping?></td> <td colspan="4" class="shipping"><?=$total_shipping?></td>
<td class="num"><?=currency_code?><?=number_format($shippingtotal,2)?></td> <td class="num"><?=currency_code?><?=number_format($invoice_cust['pricing']['shipping_total'],2)?></td>
</tr> </tr>
<tr> <tr>
<td colspan="4" class="tax"><?=$total_vat?></td> <td colspan="4" class="tax"><?=$total_vat?></td>
<td class="num" style="border-bottom: 1px solid #0e0f10;"><?=currency_code?><?=number_format($taxtotal,2)?></td> <td class="num" style="border-bottom: 1px solid #0e0f10;"><?=currency_code?><?=number_format($invoice_cust['pricing']['tax_total'],2)?></td>
</tr> </tr>
<tr> <tr>
<td colspan="4" class="total"><?=$total_total?></td> <td colspan="4" class="total"><?=$total_total?></td>
<td class="num"><?=currency_code?> <?=number_format($total,2)?></td> <td class="num"><?=currency_code?> <?=number_format($invoice_cust['pricing']['payment_amount'],2)?></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
<?php if($order['payer_email'] == 'Paid'){ <?php if($invoice_cust['invoice']['payment_status'] === 1){
echo ' echo '
<div class="content-wrapper"> <div class="content-wrapper">
<p>Het totaalbedrag van deze factuur is betaald</p> <p>Het totaalbedrag van deze factuur is betaald</p>

View File

@@ -149,7 +149,9 @@ define('db_user','morvalwatches');//morvalwatches_prod
define('db_pass','4~gv71bM6'); define('db_pass','4~gv71bM6');
// Database name // Database name
define('db_name','shoppingcart_advanced'); //morvalwatches 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('api_url','https://dev.veliti.nl/api.php'); //morvalwatches
define('img_url',substr(api_url, 0, -8)); define('img_url',substr(api_url, 0, -8));

View File

@@ -339,9 +339,9 @@ function getAccessoiries($clientsecret, $categoryID){
<img src="'.img_url.$additional_product['full_path'].'" id="'.$additional_product['rowID'].'" width="50" height="50" alt="'.$additional_product['productname'].'"> <img src="'.img_url.$additional_product['full_path'].'" id="'.$additional_product['rowID'].'" width="50" height="50" alt="'.$additional_product['productname'].'">
</a> </a>
<form id="product-form" action="" method="post"> <form id="product-form" action="" method="post">
<input type="hidden" name="add_product_id" value="'.$additional_product['rowID'].'"> <input id="product" type="hidden" name="product[product]" value="'.$additional_product['rowID'].'">
<input type="hidden" name="add_product_price" value="'.$additional_product['price'].'"> <input id="product" type="hidden" name="product[version]" value="'.($additional_product['version_id'] ?? '').'">
<input type="hidden" name="add_product_weight" value="'.($additional_product['weight'] ?? 0).'"> <input id="product" type="hidden" name="product[quantity]" value="1">
<input type="submit" name="accessoiries" value="+"> <input type="submit" name="accessoiries" value="+">
</form> </form>
<a href="'.$additional_product_url.'" id="'.$additional_product['rowID'].'A" class="product"> <a href="'.$additional_product_url.'" id="'.$additional_product['rowID'].'A" class="product">
@@ -431,7 +431,7 @@ function createGiftCart($pdo, $orderID){
$giftcard_ID = giftcard_id; $giftcard_ID = giftcard_id;
//Check if Giftcard is ordered //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]); $stmt->execute([$giftcard_ID,$orderID]);
$giftcards = $stmt->fetchAll(PDO::FETCH_ASSOC); $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 //Variables
$customer_email = htmlspecialchars($order['payer_email'] ?? '', ENT_QUOTES); $customer_email = htmlspecialchars($invoice['customer']['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'];
//Generate invoice //Generate invoice
ob_start(); ob_start();
include dirname(__FILE__).'/custom/email/order-invoice-template.php'; include dirname(__FILE__).'/custom/email/order-invoice-template.php';
$order_invoice_template = ob_get_clean(); $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){ function freeShipment($price, $type){

View File

@@ -12,22 +12,22 @@ define('base_url', rtrim($base_url, '/') . '/');
// Initialize a new session // Initialize a new session
session_start(); session_start();
// Include the configuration file, this contains settings you can change. //+++++++++++++++++++++++++++++++++++++++++++++++++++++
// Includes
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
include './custom/settings/config.php'; include './custom/settings/config.php';
// Include functions and connect to the database using PDO MySQL
include 'functions.php'; include 'functions.php';
// Include translation file
include './custom/translations/translations_'.strtoupper(language_code).'.php'; include './custom/translations/translations_'.strtoupper(language_code).'.php';
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
//LOGIN TO API //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,''); $responses = ioAPIv2('/v2/authorization', $data,'');
//Decode Payload //Decode Payload
if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = '400';} if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = '400';}
$clientsecret = $responses['token']; $clientsecret = $responses['token'];
// Connect to MySQL database
$pdo = pdo_connect_mysql();
// Output error variable // Output error variable
$error = ''; $error = '';
//error reporting //error reporting

View File

@@ -2,19 +2,6 @@
// Prevent direct access to file // Prevent direct access to file
defined(security_key) or exit; 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 // Check to make sure the id parameter is specified in the URL
if (isset($_GET['id'])) { if (isset($_GET['id'])) {
@@ -45,12 +32,10 @@ if (isset($_GET['id'])) {
// If the user clicked the add to cart button // If the user clicked the add to cart button
if (isset($_POST['product'])) { if (isset($_POST['product'])) {
//VALIDATE THE INPUT FOR THE SHOPPING CART //VALIDATE THE INPUT FOR THE SHOPPING CART
$payload = json_encode($_POST['product'], JSON_UNESCAPED_UNICODE); $payload = json_encode($_POST['product'], JSON_UNESCAPED_UNICODE);
$product_to_cart = ioAPIv2('/v2/shopping_cart/',$payload,$clientsecret); $product_to_cart = ioAPIv2('/v2/shopping_cart/',$payload,$clientsecret);
$product_to_cart = json_decode($product_to_cart,true); $product_to_cart = json_decode($product_to_cart,true);
// Check if the product exists (array is not empty) // Check if the product exists (array is not empty)
if ($product_to_cart['quantity'] > 0) { if ($product_to_cart['quantity'] > 0) {
// Product exists in database, now we can create/update the session variable for the cart // Product exists in database, now we can create/update the session variable for the cart
@@ -70,7 +55,6 @@ if (isset($_GET['id'])) {
// Prevent form resubmission... // Prevent form resubmission...
header('Location: ' . url('index.php?page=cart')); header('Location: ' . url('index.php?page=cart'));
exit; exit;
} }

View File

@@ -2,18 +2,26 @@
//Define security for webhook -> factuur //Define security for webhook -> factuur
define('interface', true); define('interface', true);
// Include the configuration file, this contains settings you can change. //+++++++++++++++++++++++++++++++++++++++++++++++++++++
// Includes
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
include '/custom/settings/config.php'; include '/custom/settings/config.php';
// Include functions and connect to the database using PDO MySQL
include 'functions.php'; include 'functions.php';
// Connect to MySQL database
$pdo = pdo_connect_mysql();
/* //+++++++++++++++++++++++++++++++++++++++++++++++++++++
* How to verify Mollie API Payments in a webhook. //LOGIN TO API
* //+++++++++++++++++++++++++++++++++++++++++++++++++++++
* See: https://docs.mollie.com/guides/webhooks $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 { try {
/* /*
@@ -23,49 +31,61 @@ try {
*/ */
require "initialize.php"; 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"]); $payment = $mollie->payments->get($_POST["id"]);
$orderId = $payment->metadata->order_id; $orderId = $payment->metadata->order_id;
/* //+++++++++++++++++++++++++++++++++++++++++++++++++++++
* Update the order in the database. // 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 = ?');
if ($payment->isPaid() && ! $payment->hasRefunds() && ! $payment->hasChargebacks()) { if ($payment->isPaid() && ! $payment->hasRefunds() && ! $payment->hasChargebacks()) {
/* //+++++++++++++++++++++++++++++++++++++++++++++++++++++
* The payment is paid and isn't refunded or charged back. //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. //At this point you'd probably want to start the process of delivering the product to the customer.
*/ //+++++++++++++++++++++++++++++++++++++++++++++++++++++
$stmt->execute(["Paid", $orderId]);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
//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);
if ($transaction !== null && !empty($transaction)) {
if(count($transaction) > 0) {
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Order is Paid. Create Giftcards when applicable //Generate INVOICE RECORD
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
createGiftCart($pdo, $orderId); $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 //Send the invoice when status is Paid
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
list($data,$customer_email,$order_id) = generateInvoice($invoice_cust,$orderId);
$base_url = 'https://'.$_SERVER['SERVER_NAME'].'/'; //CREATE PDF
define('base_url', $base_url);
list($data,$customer_email,$order_id) = generateInvoice($pdo,$orderId);
$dompdf->loadHtml($data); $dompdf->loadHtml($data);
// (Optional) Setup the paper size and orientation // (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'portrait'); $dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF // Render the HTML as PDF
$dompdf->render(); $dompdf->render();
$subject = 'MorvalWatches - Invoice: '.$order_id; $subject = ($invoice_morval_subject ?? 'MorvalWatches - Invoice: ').$order_id;
$attachment = $dompdf->output(); $attachment = $dompdf->output();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -78,38 +98,53 @@ try {
} }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
// }
}
}
} elseif ($payment->isOpen()) { } 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()) { } 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()) { } 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()) { } 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()) { } 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()) { } elseif ($payment->hasRefunds()) {
/* /*
* The payment has been (partially) refunded. * The payment has been (partially) refunded.
* The status of the payment is still "paid" * 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 //Order is refunded - disable giftcards
useGiftCart($pdo, $orderId); useGiftCart($pdo, $orderId);

View File

@@ -3,8 +3,16 @@
include '/custom/settings/config.php'; include '/custom/settings/config.php';
// Include functions and connect to the database using PDO MySQL // Include functions and connect to the database using PDO MySQL
include 'functions.php'; 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 // paypal
require_once __DIR__."/lib/paypal/paypal.php"; require_once __DIR__."/lib/paypal/paypal.php";
@@ -36,33 +44,45 @@ if($token !=''){
//IF TXN_ID is not empty //IF TXN_ID is not empty
if ($orderId !='' && $result->ref == 'COMPLETED'){ 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 //UPDATE THE PAYMENT STATUS
$stmt = $pdo->prepare('UPDATE transactions SET payment_status = ? WHERE txn_id = ?'); //+++++++++++++++++++++++++++++++++++++++++++++++++++++
$stmt->execute(["Paid", $orderId]); $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);
if ($transaction !== null && !empty($transaction)) {
if(count($transaction) > 0) {
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Order is Paid. Create Giftcards when applicable //Generate INVOICE RECORD
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
createGiftCart($pdo, $orderId); $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 //Send the invoice when status is Paid
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
list($data,$customer_email,$order_id) = generateInvoice($invoice_cust,$orderId);
list($data,$customer_email,$order_id) = generateInvoice($pdo,$orderId); //CREATE PDF
$dompdf->loadHtml($data); $dompdf->loadHtml($data);
// (Optional) Setup the paper size and orientation // (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'portrait'); $dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF // Render the HTML as PDF
$dompdf->render(); $dompdf->render();
$subject = 'MorvalWatches - Invoice: '.$order_id; $subject = ($invoice_morval_subject ?? 'MorvalWatches - Invoice: ').$order_id;
$attachment = $dompdf->output(); $attachment = $dompdf->output();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -73,9 +93,10 @@ if($token !=''){
if(invoice_bookkeeping){ if(invoice_bookkeeping){
send_mail_by_PHPMailer(email_bookkeeping, $subject, $data, $attachment, $subject); send_mail_by_PHPMailer(email_bookkeeping, $subject, $data, $attachment, $subject);
} }
//REDIRECT TO PLACEORDER SCREEN //++++++++++++++++++++++++++++++++++++++++++++++++++++++
header('Location: ' . url('index.php?page=placeorder')); //++++++++++++++++++++++++++++++++++++++++++++++++++++++
exit; }
}
} }
} else { } else {
//GET TXN FROM RETURN LINK //GET TXN FROM RETURN LINK