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
test.php

View File

@@ -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 .= '</tbody>
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 .= '
<div class="total">
<span class="text">'.$total_subtotal.'</span>

View File

@@ -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 .= '
<label for="address_country">'.$shipping_country.'</label>
<select name="address_country" class="ajax-update form-field" required>';
foreach(get_countries() as $country){
$view .= ' <option value="'.$country.'" '.($country==$account['address_country'] ? ' selected' : '').'>'.$country.'</option>';
foreach($countries as $country){
$view .= ' <option value="'.$country['id'].'" '.($country['id']==$account['address_country'] ? ' selected' : '').'>'.(${$countryMap[$country['id']]} ?? $countryMap[$country['id']]).'</option>';
}
$view .= ' </select>
@@ -444,21 +456,19 @@ $view .= ' </span>
</div>
<div class="shipping-methods-container">';
if ($shipping_methods_available){
if (isset($shipping_methods) && count($shipping_methods) > 0){
$view .= ' <div class="shipping-methods">
<h3>'.$h3_shipping_method.'</h3>';
foreach($shipping_methods as $k => $method){
if (!in_array($method['id'], $shipping_methods_available)){
$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':'').'>
<label for="sm'.$k.'">'.$method['name'].' ('.currency_code.''.number_format($method['price'], 2).''.$method['type']=='Single Product'?' per item':''.')</label>
foreach($shipping_methods as $method){
$view .= ' <div class="shipping-method">
<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'.$method['id'].'">'.$method['name'].' ('.currency_code.''.number_format($method['price'], 2).')</label>
</div>';
}
$view .= '</div>';
}
}
$view .= '</div>';
}
$view .= ' </div>
<div class="summary">
<div class="subtotal">

View File

@@ -4,21 +4,20 @@
<?=template_order_email_header()?>
<?php include './custom/translations/translations_'.strtoupper(language_code).'.php';?>
</tr>
<tr><td><br></td></tr>
<tr>
<td>
<?=$address_name?><br>
<?=$address_street?><br>
<?=$address_zip?>, <?=$address_city?><br>
<?=$address_country?>
<?=$invoice_cust['customer']['name']?><br>
<?=$invoice_cust['customer']['street']?><br>
<?=$invoice_cust['customer']['zip']?>, <?=$invoice_cust['customer']['city']?><br>
<?=$invoice_cust['customer']['country']?>
</td>
</tr>
<tr><td><br></td></tr>
<tr>
<td><h2>Invoice: <?=$order_id?></h2></td>
<td><p>Date: <?php echo date("Y-m-d", strtotime($order_created))?></p></td>
<td><h2>Invoice: <?=$invoice_cust['invoice']['id']?></h2></td>
<td><p>Date: <?php echo date("Y-m-d", strtotime($invoice_cust['invoice']['created']))?></p></td>
</tr>
</table>
@@ -39,45 +38,43 @@
</thead>
<tbody>
<?php
$subtotal = 0;
foreach($products as $product): ?>
foreach($invoice_cust['products'] as $product): ?>
<tr>
<td><?=$product['name']?></td>
<td><?=$product['item_options']?></td>
<td><?=$product['item_quantity']?></td>
<td><?=currency_code?> <?=number_format($product['item_price'],2)?></td>
<td style="text-align:right;"><?=currency_code?> <?=number_format($product['item_price'] * $product['item_quantity'],2)?></td>
<td><?=${$product['product_name']} ?? $product['product_name'] ?></td>
<td><?=implode(", ", $product['options'])?></td>
<td><?=$product['quantity']?></td>
<td><?=currency_code?> <?=number_format($product['price'],2)?></td>
<td style="text-align:right;"><?=currency_code?> <?=number_format($product['line_total'],2)?></td>
</tr>
<?php $subtotal += $product['item_price']*$product['item_quantity'];?>
<?php endforeach; ?>
<tr>
<td colspan="5" class="item-list-end"></td>
</tr>
<tr>
<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>
<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>
<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>
<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>
<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>
</tbody>
</table>
</div>
</div>
<?php if($order['payer_email'] == 'Paid'){
<?php if($invoice_cust['invoice']['payment_status'] === 1){
echo '
<div class="content-wrapper">
<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');
// 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));

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'].'">
</a>
<form id="product-form" action="" method="post">
<input type="hidden" name="add_product_id" value="'.$additional_product['rowID'].'">
<input type="hidden" name="add_product_price" value="'.$additional_product['price'].'">
<input type="hidden" name="add_product_weight" value="'.($additional_product['weight'] ?? 0).'">
<input id="product" type="hidden" name="product[product]" value="'.$additional_product['rowID'].'">
<input id="product" type="hidden" name="product[version]" value="'.($additional_product['version_id'] ?? '').'">
<input id="product" type="hidden" name="product[quantity]" value="1">
<input type="submit" name="accessoiries" value="+">
</form>
<a href="'.$additional_product_url.'" id="'.$additional_product['rowID'].'A" class="product">
@@ -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){

View File

@@ -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

View File

@@ -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;
}

View File

@@ -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);

View File

@@ -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'] ?? '';