Skip to content

Commit

Permalink
better callback handling
Browse files Browse the repository at this point in the history
  • Loading branch information
leviothan committed Jan 9, 2018
1 parent b506c98 commit 6d8d662
Show file tree
Hide file tree
Showing 10 changed files with 433 additions and 1,238 deletions.
3 changes: 3 additions & 0 deletions classes/PaybearData.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class PaybearData extends ObjectModel

public $invoice;

public $amount;

public $date_add;

public $date_upd;
Expand All @@ -32,6 +34,7 @@ class PaybearData extends ObjectModel
'confirmations' => array('type' => self::TYPE_INT, 'required' => false, 'validate' => false, 'allow_null' => true),
'address' => array('type' => self::TYPE_STRING, 'validate' => 'isString'),
'invoice' => array('type' => self::TYPE_STRING, 'validate' => 'isString'),
'amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'),
)
Expand Down
52 changes: 42 additions & 10 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 @@ -9,11 +9,13 @@ public function initContent()
$orderReference = $_GET['order'];
/** @var Order $order */
$order = Order::getByReference($orderReference)->getFirst();
$cart = new Cart($order->id_cart);
$currency = new Currency($cart->id_currency);
$customer = $order->getCustomer();
$sdk = new PayBearSDK($this->context);

// $currency = new Currency($order->id_currency);
// $customer = $order->getCustomer();

$data = file_get_contents('php://input');

if ($data) {
$params = json_decode($data);
$minConfirmations = Configuration::get('PAYBEAR_' . strtoupper($params->blockchain) . '_CONFIRMATIONS');
Expand All @@ -22,21 +24,51 @@ public function initContent()
$paybearData->confirmations = $params->confirmations;
$paybearData->update();

PrestaShopLogger::addLog(sprintf('PayBear: incoming callback. Confirmations - %d', $params->confirmations), 1, null, 'Order', $order->id, true);

if ($params->confirmations >= $minConfirmations) {
$toPay = $paybearData->amount;
$amountPaid = $params->inTransaction->amount / pow(10, $params->inTransaction->exp);
$fiatPaid = $amountPaid * $sdk->getRate($params->blockchain);
$maxDifference = min($toPay * 0.005, 0.001);
$paybear = Module::getInstanceByName('paybear');

//compare $amountPaid with order total
//compare $invoice with one saved in the database to ensure callback is legitimate
//mark the order as paid
$paybear->validateOrder($cart->id, Configuration::get('PS_OS_PAYMENT'), $amountPaid, $this->module->displayName, NULL, array(), (int)$currency->id, false, $customer->secure_key);
PrestaShopLogger::addLog(sprintf('PayBear: to pay %s', $toPay), 1, null, 'Order', $order->id, true);
PrestaShopLogger::addLog(sprintf('PayBear: paid %s', $amountPaid), 1, null, 'Order', $order->id, true);
PrestaShopLogger::addLog(sprintf('PayBear: maxDifference %s', $maxDifference), 1, null, 'Order', $order->id, true);

$orderStatus = Configuration::get('PS_OS_ERROR');

if ($toPay > 0 && ($toPay - $fiatPaid) < $maxDifference) {
$orderTimestamp = strtotime($order->date_add);
$paymentTimestamp = time();
$deadline = $orderTimestamp + Configuration::get('PAYBEAR_EXCHANGE_LOCKTIME') * 60;

if ($paymentTimestamp > $deadline) {
PrestaShopLogger::addLog('PayBear: late payment', 1, null, 'Order', $order->id, true);

$fiatPaid = $amountPaid * $sdk->getRate($params->blockchain);
if ($order->total_paid < $fiatPaid) {
PrestaShopLogger::addLog('PayBear: rate changed', 1, null, 'Order', $order->id, true);
} else {
$orderStatus = Configuration::get('PS_OS_PAYMENT');
$order->addOrderPayment($amountPaid, $paybear->displayName, $params->inTransaction->hash);
PrestaShopLogger::addLog(sprintf('PayBear: payment complete', $amountPaid), 1, null, 'Order', $order->id, true);
}
}
} else {
PrestaShopLogger::addLog(sprintf('PayBear: wrong amount %s', $amountPaid), 2, null, 'Order', $order->id, true);
}

$orderHistory = new OrderHistory();
$orderHistory->id_order = (int) $order->id;
$orderHistory->changeIdOrderState((int) $orderStatus, $order, true);
$orderHistory->addWithemail(true);

echo $invoice; //stop further callbacks
die();
}
}
die();
// echo Tools::jsonEncode($data);
// die();
}
}
35 changes: 0 additions & 35 deletions controllers/front/payment.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,40 +23,5 @@ public function initContent()
]);

$this->setTemplate('module:paybear/views/templates/front/payment.tpl');


// $this->ajax = true;
// $sdk = new PayBearSDK($this->context);
//
// // $orderId = (int) $_GET['order'];
// $orderId = 123;
// $fiatTotal = 19.99; //get from order
//
// $tokens = ['ETH', 'BTC', 'LTC', 'BCH', 'BTG', 'DASH'];
//
//
// if (isset($_GET['token'])) {
// $token = $_GET['token'];
// $data = $sdk->getCurrency($token, $orderId, true);
// } else {
// $data = [];
// foreach ($tokens as $token) {
// $enabled = Configuration::get('paybear_enable_'.strtolower($token));
// $wallet = Configuration::get('paybear_' . strtolower($token) . '_wallet');
// $confirmations = Configuration::get('paybear_' . strtolower($token) . '_confirmations');
//
// if (!$enabled || !$wallet || !$confirmations) {
// continue;
// }
//
// $currency = $sdk->getCurrency($token, $orderId);
// if ($currency) {
// $data[] = $currency;
// }
// }
// }
//
// echo Tools::jsonEncode($data);
// die();
}
}
41 changes: 37 additions & 4 deletions paybear.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@

class PayBear extends PaymentModule
{
const DEBUG_MODE = true; // todo change

protected $_html = '';
protected $_postErrors = array();

Expand All @@ -42,6 +44,8 @@ class PayBear extends PaymentModule
public $address;
public $extra_mail_vars;



protected $cryptoCurrencies = array(
array('name' => 'eth', 'label' => 'ETH', 'defaults' => array('enabled' => 1, 'confirmations' => 3)),
array('name' => 'btc', 'label' => 'BTC', 'defaults' => array('enabled' => 1, 'confirmations' => 1)),
Expand All @@ -55,7 +59,7 @@ public function __construct()
{
$this->name = 'paybear';
$this->tab = 'payments_gateways';
$this->version = '0.1.0';
$this->version = '0.2.0';
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
$this->author = 'PayBear';
$this->controllers = array('validation', 'currencies', 'payment', 'callback', 'status');
Expand All @@ -67,6 +71,9 @@ public function __construct()
$this->bootstrap = true;
parent::__construct();

// $this->displayName = Configuration::get('PAYBEAR_TITLE');
// $this->description = Configuration::get('PAYBEAR_DESCRIPTION');

$this->displayName = $this->l('Crypto Payment Gateway for PrestaShop by PayBear.io');
$this->description = $this->l('Allows to accept crypto payments such as Bitcoin (BTC) and Ethereum (ETH)');
// $this->module_link = $this->context->link->getAdminLink('AdminModules', true).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
Expand Down Expand Up @@ -98,6 +105,11 @@ public function install()
}

// todo: set default config

Configuration::updateValue('PAYBEAR_TITLE', 'Crypto Payments');
Configuration::updateValue('PAYBEAR_DESCRIPTION', 'Bitcoin (BTC), Ethereum (ETH) and other crypto currencies');
Configuration::updateValue('PAYBEAR_EXCHANGE_LOCKTIME', '15');

foreach ($this->cryptoCurrencies as $cryptoCurrency) {
if (!Configuration::updateValue('PAYBEAR_ENABLE_'.strtoupper($cryptoCurrency['name']), $cryptoCurrency['defaults']['enabled'])) {
return false;
Expand Down Expand Up @@ -161,9 +173,9 @@ public function getEmbeddedPaymentOption()
$embeddedOption = new PaymentOption();
$embeddedOption
->setModuleName($this->name)
->setCallToActionText($this->trans('Pay by Crypto (Embedded)'))
->setCallToActionText(Configuration::get('PAYBEAR_TITLE'))
->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))
->setAdditionalInformation($this->context->smarty->fetch('module:paybear/views/templates/front/payment_infos.tpl'))
->setAdditionalInformation(Configuration::get('PAYBEAR_DESCRIPTION'))
// ->setLogo(Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/crypto.png'))
;

Expand Down Expand Up @@ -204,7 +216,24 @@ public function displayForm()
)
);

$fields_form[0]['form']['input'] = array();
$fields_form[0]['form']['input'] = array(
array(
'type' => 'text',
'label' => 'Title',
'name' => 'paybear_title',
),
array(
'type' => 'textarea',
'label' => 'Description',
'name' => 'paybear_description'
),
array(
'type' => 'text',
'label' => 'Exchange Rate Lock Time',
'name' => 'paybear_exchange_locktime',
'desc' => 'Lock Fiat to Crypto exchange rate for this long (in minutes, 15 is the recommended minimum)'
)
);

foreach ($this->cryptoCurrencies as $currency) {
$fields_form[0]['form']['input'][] = array(
Expand Down Expand Up @@ -268,6 +297,9 @@ public function displayForm()
);

// Load current value
$helper->fields_value['paybear_title'] = Configuration::get('PAYBEAR_TITLE');
$helper->fields_value['paybear_description'] = Configuration::get('PAYBEAR_DESCRIPTION');
$helper->fields_value['paybear_exchange_locktime'] = Configuration::get('PAYBEAR_EXCHANGE_LOCKTIME');
foreach ($this->cryptoCurrencies as $currency) {
$helper->fields_value['paybear_enable_' . $currency['name']] = Configuration::get('PAYBEAR_ENABLE_' . strtoupper($currency['name']));
$helper->fields_value['paybear_' . $currency['name'] . '_confirmations'] = Configuration::get('PAYBEAR_' . strtoupper($currency['name']) . '_CONFIRMATIONS');
Expand All @@ -287,6 +319,7 @@ private function installSQL()
`token` VARCHAR(256) NULL DEFAULT NULL,
`address` VARCHAR(256),
`invoice` VARCHAR(256),
`amount` DECIMAL(20, 7),
`confirmations` INT(2) NULL DEFAULT NULL,
`date_add` DATETIME NULL DEFAULT NULL,
`date_upd` DATETIME NULL DEFAULT NULL
Expand Down
13 changes: 11 additions & 2 deletions sdk/PayBearSDK.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ public function __construct($context)
public function getAddress($orderId, $token = 'ETH')
{
$data = PaybearData::getByOrderRefence($orderId);
/** @var Order $order */
$order = Order::getByReference($orderId)->getFirst();

$rate = $this->getRate($token);

if ($data && strtolower($data->token) == strtolower($token)) {
return $data->address;
} elseif (!$data) {
Expand All @@ -28,10 +33,14 @@ public function getAddress($orderId, $token = 'ETH')
$response = json_decode($response);

if (isset($response->data->address)) {
$fiatAmount = $order->total_paid;
$coinsAmount = round($fiatAmount / $rate, 7);

$data->confirmations = null;
$data->token = strtolower($token);
$data->address = $response->data->address;
$data->invoice = $response->data->invoice;
$data->amount = $coinsAmount;

if ($data->id_paybear) {
$data->update();
Expand Down Expand Up @@ -60,7 +69,7 @@ public function getCurrency($token, $orderId, $getAddress = false)
/** @var Order $order */
$order = Order::getByReference($orderReference)->getFirst();
$fiatValue = (float)$order->total_paid;
$coinsValue = round($fiatValue / $rate, 5);
$coinsValue = round($fiatValue / $rate, 7);

switch ($token) {
case 'ETH':
Expand Down Expand Up @@ -89,7 +98,7 @@ public function getCurrency($token, $orderId, $getAddress = false)
'blockExplorer' => 'https://blockchain.info/address/%s',
'minimum' => 0.0005,
'min_with_fee' => 0.001,
'walletLink' => "bitcoin:%s?amount=%s"
// 'walletLink' => "bitcoin:%s?amount=%s"
];
break;
case 'DASH':
Expand Down
Loading

0 comments on commit 6d8d662

Please sign in to comment.