Skip to content

Commit

Permalink
code clean up and update form
Browse files Browse the repository at this point in the history
  • Loading branch information
leviothan committed Apr 2, 2018
1 parent e8aee4c commit 3dcc2eb
Show file tree
Hide file tree
Showing 12 changed files with 127 additions and 102 deletions.
3 changes: 3 additions & 0 deletions classes/PaybearData.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,16 @@ public static function getByOrderRefence($orderReference)

$raw = Db::getInstance()->getRow($sql);
if ($raw && isset($raw['id_paybear'])) {
/** @noinspection PhpUnhandledExceptionInspection */
return new self($raw['id_paybear']);
}

return null;
}

/**
* @param null|string $excludeHash
*
* @return PaybearTransaction[]
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
Expand Down
2 changes: 0 additions & 2 deletions classes/PaybearTransaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,4 @@ public static function getByTransactionHash($hash)

return $object;
}


}
69 changes: 43 additions & 26 deletions controllers/front/callback.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

include_once(_PS_MODULE_DIR_ . 'paybear/sdk/PayBearSDK.php');
include_once _PS_MODULE_DIR_ . 'paybear/sdk/PayBearSDK.php';

class PayBearCallbackModuleFrontController extends ModuleFrontController
{
Expand All @@ -18,13 +18,14 @@ public function initContent()
$currency = new Currency($order->id_currency);
$customer = $order->getCustomer();
$sdk = new PayBearSDK($this->context);
$currencies = $sdk->getCurrencies();
$data = file_get_contents('php://input');
$message = null;
$addMessage = true;
$paybear = Module::getInstanceByName('paybear');
$updateStatus = true;

if ($order->current_state == Configuration::get('PS_OS_PAYMENT')) {
if ((int) $order->current_state === (int) Configuration::get('PS_OS_PAYMENT')) {
die();
}

Expand All @@ -37,14 +38,26 @@ public function initContent()
$params = json_decode($data);
$paybearData = PaybearData::getByOrderRefence($orderReference);

if ($paybearData->invoice != $params->invoice) {
if (!$paybearData) {
die();
}

if ($paybearData->invoice !== $params->invoice) {
PrestaShopLogger::addLog(sprintf('PayBear: Wrong invoice - %s. expected - %s', $paybearData->invoice, $params->invoice), 1, null, 'Order', $order->id, true);
die();
}

/** @noinspection PhpUnhandledExceptionInspection */
$allPaybearPayments = $paybearData->getPayments($params->inTransaction->hash);
$maxConfirmations = $params->maxConfirmations;
$rate = $sdk->getRate($params->blockchain);
$blockchain = PayBearSDK::sanitizeToken($params->blockchain);
$blockchainCode = strtoupper($blockchain);

if (isset($currencies[$params->blockchain])) {
$blockchainCode = $currencies[$params->blockchain]['code'];
}

$rate = $sdk->getRate($blockchain);
if (!$maxConfirmations) {
$maxConfirmations = $paybearData->max_confirmations; // todo: tmp fix
}
Expand All @@ -60,16 +73,18 @@ public function initContent()
$alreadyPaid += $payment->amount;
}

$paidNow = $params->inTransaction->amount / pow(10, $params->inTransaction->exp);
$paidNow = $params->inTransaction->amount / (10 ** $params->inTransaction->exp);
$totalPaid = $paidNow + $alreadyPaid;

/** @noinspection PhpUnhandledExceptionInspection */
$paybearPayment = PaybearTransaction::getByTransactionHash($params->inTransaction->hash);
if (!$paybearPayment) {
/** @noinspection PhpUnhandledExceptionInspection */
$paybearPayment = new PaybearTransaction();
$paybearPayment->invoice = $params->invoice;
$paybearPayment->max_confirmations = $params->maxConfirmations;
$paybearPayment->order_reference = $orderReference;
$paybearPayment->blockchain = $params->blockchain;
$paybearPayment->blockchain = $blockchain;
$paybearPayment->amount = sprintf('%.8F', $paidNow);
$paybearPayment->currency = $currency->iso_code;
$paybearPayment->address = $paybearData->address;
Expand All @@ -79,7 +94,7 @@ public function initContent()
}

if (isset($allPaybearPayments[$paybearPayment->transaction_hash])) {
$transactionIndex = array_search($paybearPayment->transaction_hash, array_keys($allPaybearPayments));
$transactionIndex = array_search($paybearPayment->transaction_hash, array_keys($allPaybearPayments), true);
if ($transactionIndex > 0) { //avoid race conditions
usleep($transactionIndex * 500);
}
Expand All @@ -88,25 +103,28 @@ public function initContent()
$paybearPayment->confirmations = $params->confirmations;

if (!$paybearPayment->id_paybear_transaction) {
/** @noinspection PhpUnhandledExceptionInspection */
$paybearPayment->save();
} else {
/** @noinspection PhpUnhandledExceptionInspection */
$paybearPayment->update();
}

if (($toPay - $totalPaid) > $maxDifference) {
if ($order->current_state != (int) Configuration::get('PAYBEAR_OS_MISPAID')) {
if ((int) $order->current_state !== (int) Configuration::get('PAYBEAR_OS_MISPAID')) {
$order->setCurrentState((int) Configuration::get('PAYBEAR_OS_MISPAID'));
}
$updateStatus = false;
$underpaid = $toPay - $totalPaid;
$underpaidFiat = $underpaid * $rate;
// $underpaidFiat = round(($toPay-$totalPaid) * $rate, 2);
$message = sprintf("Looks like you underpaid %.8F %s (%.2F %s)\n\nDon't worry, here is what to do next:\n\nContact the merchant directly and...\n-Request details on how you can pay the difference..\n-Request a refund and create a new order.\n\nTips for Paying with Crypto:\n\nTip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value.\n\nTip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees.\n\nTip 3) Be sure to successfully send your payment before the countdown timer expires.\nThis timer is setup to lock in a fixed rate for your payment. Once it expires, the rate changes.", $underpaid, strtoupper($params->blockchain), $underpaidFiat, $currency->iso_code, strtoupper($params->blockchain), $currency->iso_code);
$message = sprintf("Looks like you underpaid %.8F %s (%.2F %s)\n\nDon't worry, here is what to do next:\n\nContact the merchant directly and...\n-Request details on how you can pay the difference..\n-Request a refund and create a new order.\n\nTips for Paying with Crypto:\n\nTip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value.\n\nTip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees.\n\nTip 3) Be sure to successfully send your payment before the countdown timer expires.\nThis timer is setup to lock in a fixed rate for your payment. Once it expires, the rate changes.", $underpaid, strtoupper($blockchainCode), $underpaidFiat, $currency->iso_code, strtoupper($blockchainCode), $currency->iso_code);
}

if ($params->confirmations >= $maxConfirmations && $maxConfirmations > 0) {
$orderStatus = Configuration::get('PAYBEAR_OS_MISPAID');

/** @noinspection NotOptimalIfConditionsInspection */
if ($toPay > 0 && ($toPay - $totalPaid) < $maxDifference) {
$orderTimestamp = strtotime($order->date_add);
$paymentTimestamp = strtotime($paybearPayment->date_add);
Expand All @@ -121,7 +139,7 @@ public function initContent()
$underpaid = $toPay - $totalPaid;
$underpaidFiat = $underpaid * $rate;
PrestaShopLogger::addLog('PayBear: rate changed', 1, null, 'Order', $order->id, true);
$message = sprintf("Looks like you underpaid %.8F %s (%.2F %s)\nThis was due to the payment being sent after the Countdown Timer Expired.\n\nDon't worry, here is what to do next:\n\nContact the merchant directly and...\n-Request details on how you can pay the difference..\n-Request a refund and create a new order.\n\nTips for Paying with Crypto:\n\nTip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value.\n\nTip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees.\n\nTip 3) Be sure to successfully send your payment before the countdown timer expires.\nThis timer is setup to lock in a fixed rate for your payment. Once it expires, the rate changes.", $underpaid, strtoupper($params->blockchain), $underpaidFiat, $currency->iso_code, strtoupper($params->blockchain), $currency->iso_code);
$message = sprintf("Looks like you underpaid %.8F %s (%.2F %s)\nThis was due to the payment being sent after the Countdown Timer Expired.\n\nDon't worry, here is what to do next:\n\nContact the merchant directly and...\n-Request details on how you can pay the difference..\n-Request a refund and create a new order.\n\nTips for Paying with Crypto:\n\nTip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value.\n\nTip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees.\n\nTip 3) Be sure to successfully send your payment before the countdown timer expires.\nThis timer is setup to lock in a fixed rate for your payment. Once it expires, the rate changes.", $underpaid, strtoupper($blockchainCode), $underpaidFiat, $currency->iso_code, strtoupper($blockchainCode), $currency->iso_code);
$addMessage = true;
// $message = sprintf('Late Payment / Rate changed (%s %s paid, %s %s expected)', $fiatPaid, $currency->iso_code, $order->total_paid, $currency->iso_code);
} else {
Expand All @@ -136,20 +154,21 @@ public function initContent()
$minOverpaymentFiat = Configuration::get('PAYBEAR_MIN_OVERPAYMENT');

if ($overpaidFiat > $minOverpaymentFiat) {
$message = sprintf("Whoops, you overpaid: %.8F %s\n\nDon’t worry, here is what to do next:\nTo get your overpayment refunded, please contact the merchant directly and share your Order ID %s and %s Address to send your refund to.\n\nTips for Paying with Crypto:\n\nTip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value.\n\nTip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees.\n\nTip 3) Be sure to successfully send your payment before the countdown timer expires.\nThis timer is setup to lock in a fixed rate for your payment. Once it expires, the rate changes.", $overpaid, strtoupper($params->blockchain), $orderReference, strtoupper($params->blockchain), strtoupper($params->blockchain), strtoupper($currency->iso_code));
$message = sprintf("Whoops, you overpaid: %.8F %s\n\nDon’t worry, here is what to do next:\nTo get your overpayment refunded, please contact the merchant directly and share your Order ID %s and %s Address to send your refund to.\n\nTips for Paying with Crypto:\n\nTip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value.\n\nTip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees.\n\nTip 3) Be sure to successfully send your payment before the countdown timer expires.\nThis timer is setup to lock in a fixed rate for your payment. Once it expires, the rate changes.", $overpaid, strtoupper($blockchainCode), $orderReference, strtoupper($blockchainCode), strtoupper($blockchainCode), strtoupper($currency->iso_code));
$addMessage = true;
}
}

if ($updateStatus && $order->current_state != $orderStatus) {
if ($updateStatus && (int) $order->current_state !== (int) $orderStatus) {
$order->setCurrentState($orderStatus);
}
$response = $params->invoice;
} elseif (!in_array($order->current_state, [
Configuration::get('PAYBEAR_OS_WAITING_CONFIRMATIONS'),
Configuration::get('PAYBEAR_OS_MISPAID'),
])) {
} elseif (!in_array((int) $order->current_state, [
(int) Configuration::get('PAYBEAR_OS_WAITING_CONFIRMATIONS'),
(int) Configuration::get('PAYBEAR_OS_MISPAID'),
], true)) {
$paybearData->payment_add = date('Y-m-d H:i:s');
/** @noinspection PhpUnhandledExceptionInspection */
$paybearData->update();

$order->setCurrentState((int) Configuration::get('PAYBEAR_OS_WAITING_CONFIRMATIONS'));
Expand All @@ -161,6 +180,7 @@ public function initContent()
if ($message && $addMessage) {
$idCustomerThread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
if (!$idCustomerThread) {
/** @noinspection PhpUnhandledExceptionInspection */
$customerThread = new CustomerThread();
$customerThread->id_contact = 0;
$customerThread->id_customer = (int)$order->id_customer;
Expand All @@ -170,24 +190,27 @@ public function initContent()
$customerThread->email = $customer->email;
$customerThread->status = 'open';
$customerThread->token = Tools::passwdGen(12);
/** @noinspection PhpUnhandledExceptionInspection */
$customerThread->add();
} else {
$customerThread = new CustomerThread((int)$idCustomerThread);
/** @noinspection PhpUnhandledExceptionInspection */
$customerThread = new CustomerThread((int) $idCustomerThread);
}

/** @noinspection PhpUnhandledExceptionInspection */
$customerMessage = new CustomerMessage();
$customerMessage->id_customer_thread = $customerThread->id;
// $customerMessage->id_employee = (int)$this->context->employee->id;
$customerMessage->message = $message;
$customerMessage->private = 0;

/** @noinspection PhpUnhandledExceptionInspection */
$customerMessage->add();

$message = $customerMessage->message;
if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
if ((int) Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) !== Mail::TYPE_TEXT) {
$message = Tools::nl2br($customerMessage->message);
}

// $orderLanguage = new Language((int) $order->id_lang);
$varsTpl = array(
'{lastname}' => $customer->lastname,
'{firstname}' => $customer->firstname,
Expand All @@ -200,12 +223,6 @@ public function initContent()
(int)$order->id_lang,
'order_merchant_comment',
'New message regarding your order',
// $this->trans(
// 'New message regarding your order',
// array(),
// 'Emails.Subject',
// $orderLanguage->locale
// ),
$varsTpl, $customer->email,
$customer->firstname.' '.$customer->lastname,
null,
Expand Down
5 changes: 3 additions & 2 deletions controllers/front/currencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ public function initContent()
$data = [];
$currencies = $sdk->getCurrencies();
$getAddress = false;
if (count($currencies) == 1) {
if (count($currencies) === 1) {
$getAddress = true;
}

$paybearData = PaybearData::getByOrderRefence($orderId);
$currentCurrencyToken = null;
if ($paybearData) {
/** @noinspection PhpUnhandledExceptionInspection */
$allPaybearPayments = $paybearData->getPayments();
if (!empty($allPaybearPayments)) {
$firstPayment = current($allPaybearPayments);
Expand All @@ -46,7 +47,7 @@ public function initContent()
$coinsPaid = 0;
if ($paybearData && !empty($allPaybearPayments)) {
foreach ($allPaybearPayments as $payment) {
if ($payment->blockchain == strtolower($currency->code)) {
if ($payment->blockchain === strtolower($currency->code)) {
$coinsPaid += $payment->amount;
}
}
Expand Down
29 changes: 10 additions & 19 deletions controllers/front/pay.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,28 @@ public function initContent()
$statusWaitingForConfirmations = Configuration::get('PAYBEAR_OS_WAITING_CONFIRMATIONS');
$statusMispaid = Configuration::get('PAYBEAR_OS_MISPAID');

// var_dump($order->current_state);
// var_dump(Configuration::get('PS_OS_PAYMENT'));
// die();

if ($order->current_state == Configuration::get('PS_OS_PAYMENT')) {
if ((int) $order->current_state === (int) Configuration::get('PS_OS_PAYMENT')) {
$paymentStatus = 'paid';
}

if ($order->current_state == Configuration::get('PAYBEAR_OS_WAITING_CONFIRMATIONS')) {
if ((int) $order->current_state === (int) Configuration::get('PAYBEAR_OS_WAITING_CONFIRMATIONS')) {
$paymentStatus = 'waiting for confirmations';
}

if ($order->current_state == Configuration::get('PAYBEAR_OS_MISPAID')) {
if ((int) $order->current_state === (int) Configuration::get('PAYBEAR_OS_MISPAID')) {
$paymentStatus = 'partial payment';
}

if ($paybearData) {
/** @noinspection PhpUnhandledExceptionInspection */
$allPaybearPayments = $paybearData->getPayments();
$selectedCurrency = $sdk->getCurrency($paybearData->token, $orderReference);
$blockExplorer = sprintf($selectedCurrency->blockExplorer, $paybearData->address);
if ($selectedCurrency) {
$blockExplorer = sprintf($selectedCurrency->blockExplorer, $paybearData->address);
}
}

$maxUnderpaymentFiat = Configuration::get('PAYBEAR_MAX_UNDERPAYMENT');
// $maxUnderpaymentFiat = Configuration::get('PAYBEAR_MAX_UNDERPAYMENT');
$toPayFiat = $order->total_paid;
$alreadyPaid = 0;
$alreadyPaidFiat = 0;
Expand All @@ -56,18 +55,9 @@ public function initContent()
if ($alreadyPaid > 0) {
$rate = round($order->total_paid / $paybearData->amount, 8);
$alreadyPaidFiat = $alreadyPaid * $rate;
$toPayFiat = $toPayFiat - $alreadyPaidFiat;
$toPayFiat -= $alreadyPaidFiat;
}

// if (!in_array($order->current_state, [
// (int) Configuration::get('PAYBEAR_OS_WAITING'),
// (int) Configuration::get('PAYBEAR_OS_MISPAID'),
// ])) {
// $logMessage = sprintf('Paybear: payment failed. order: %s, order status: %s', $order->id, $order->current_state);
// PrestaShopLogger::addLog($logMessage, 1, null, 'Order', $order->id, true);
// Tools::redirect('index.php?controller=order');
// }

if ((float) _PS_VERSION_ < 1.7) {
$redirectTo = 'index.php?controller=order-detail&&id_order='.$order->id.'&key='.$customer->secure_key;
} else {
Expand Down Expand Up @@ -103,6 +93,7 @@ public function initContent()
$template = 'module:paybear/views/templates/front/payment.tpl';
}

/** @noinspection PhpUnhandledExceptionInspection */
$this->setTemplate($template);
}
}
Loading

0 comments on commit 3dcc2eb

Please sign in to comment.