Skip to content

Commit

Permalink
Merge pull request #8 from blnce-io/v1.2.2
Browse files Browse the repository at this point in the history
V1.2.2
  • Loading branch information
pniel-cohen authored Jun 28, 2021
2 parents f0b478f + 8ed9c1c commit 36fd607
Show file tree
Hide file tree
Showing 8 changed files with 259 additions and 33 deletions.
10 changes: 7 additions & 3 deletions Block/Info.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,18 @@ protected function _prepareSpecificInformation($transport = null)

if ($this->appState->getAreaCode() === Area::AREA_ADMINHTML) {
if (($checkoutToken = $info->getAdditionalInformation(BalancepayMethod::BALANCEPAY_CHECKOUT_TOKEN))) {
$data[(string)__('Balance Checkout Token')] = $checkoutToken;
$data[(string)__('Checkout Token')] = $checkoutToken;
}
if (($transationId = $info->getAdditionalInformation(BalancepayMethod::BALANCEPAY_CHECKOUT_TRANSACTION_ID))) {
$data[(string)__('Balance Transaction ID')] = $transationId;
$data[(string)__('Transaction ID')] = $transationId;
}
if (($chargeId = $info->getAdditionalInformation(BalancepayMethod::BALANCEPAY_CHARGE_ID))) {
$data[(string)__('Balance Charge ID')] = $chargeId;
$data[(string)__('Is Charged')] = __('Yes');
$data[(string)__('Charge ID')] = $chargeId;
} else {
$data[(string)__('Is Charged')] = __('No');
}
$data[(string)__('Is Financed')] = (int) $info->getAdditionalInformation(BalancepayMethod::BALANCEPAY_IS_FINANCED) ? __('Yes') : __('No');
}

return $transport->setData(array_merge($data, $transport->getData()));
Expand Down
24 changes: 8 additions & 16 deletions Controller/Webhook/Checkout/Charged.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;

/**
Expand Down Expand Up @@ -52,9 +53,9 @@ class Charged extends Action implements CsrfAwareActionInterface
private $json;

/**
* @var OrderCollectionFactory
* @var OrderFactory
*/
private $orderCollectionFactory;
private $orderFactory;

/**
* @method __construct
Expand All @@ -71,14 +72,14 @@ public function __construct(
BalancepayConfig $balancepayConfig,
RequestFactory $requestFactory,
Json $json,
OrderCollectionFactory $orderCollectionFactory
OrderFactory $orderFactory
) {
parent::__construct($context);
$this->jsonResultFactory = $jsonResultFactory;
$this->balancepayConfig = $balancepayConfig;
$this->requestFactory = $requestFactory;
$this->json = $json;
$this->orderCollectionFactory = $orderCollectionFactory;
$this->orderFactory = $orderFactory;
}
/**
* @return ResultInterface
Expand Down Expand Up @@ -111,21 +112,12 @@ public function execute()
//Prepare & validate params:
$params = (array) $this->json->unserialize($content);
$this->validateParams($params);
$checkoutToken = (string) $params['checkoutToken'];
$externalReferenceId = (string) $params['externalReferenceId'];
$chargeId = (string) $params['chargeId'];
$amount = (float) $params['amount'];

//Load the order:
$ordersCollection = $this->orderCollectionFactory->create();
$ordersCollection->getSelect()->join(
['sop' => $ordersCollection->getTable('sales_order_payment')],
"main_table.entity_id = sop.parent_id AND sop.method = '" . BalancepayMethod::METHOD_CODE . "'",
[]
);
$ordersCollection->addAttributeToFilter('sop.additional_information', ['like' => '%' . $checkoutToken . '%']);
$ordersCollection->setPageSize(1);

$order = $ordersCollection->getFirstItem();
$order = $this->orderFactory->create()->loadByIncrementId($externalReferenceId);

if (!$order || !$order->getId()) {
throw new \Exception("No matching order!");
Expand Down Expand Up @@ -184,7 +176,7 @@ public function execute()
*/
private function validateParams($params)
{
$requiredKeys = ['checkoutToken', 'chargeId', 'amount'];
$requiredKeys = ['externalReferenceId', 'chargeId', 'amount'];
$bodyKeys = array_keys($params);

$diff = array_diff($requiredKeys, $bodyKeys);
Expand Down
186 changes: 186 additions & 0 deletions Controller/Webhook/Transaction/Confirmed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php
/**
* Balance Payments For Magento 2
* https://www.getbalance.com/
*
* @category Balance
* @package Balancepay_Balancepay
* @author Developer: Pniel Cohen
* @author Company: Girit-Interactive (https://www.girit-tech.com/)
*/

namespace Balancepay\Balancepay\Controller\Webhook\Transaction;

use Balancepay\Balancepay\Model\BalancepayMethod;
use Balancepay\Balancepay\Model\Config as BalancepayConfig;
use Balancepay\Balancepay\Model\Request\Factory as RequestFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;

/**
* Balancepay transaction/confirmed webhook.
*/
class Confirmed extends Action implements CsrfAwareActionInterface
{
/**
* @var JsonFactory
*/
private $jsonResultFactory;

/**
* @var BalancepayConfig
*/
private $balancepayConfig;

/**
* @var RequestFactory
*/
private $requestFactory;

/**
* @var Json
*/
private $json;

/**
* @var OrderFactory
*/
private $orderFactory;

/**
* @method __construct
* @param Context $context
* @param JsonFactory $jsonResultFactory
* @param BalancepayConfig $balancepayConfig
* @param RequestFactory $requestFactory
* @param Json $json
* @param OrderFactory $orderFactory
*/
public function __construct(
Context $context,
JsonFactory $jsonResultFactory,
BalancepayConfig $balancepayConfig,
RequestFactory $requestFactory,
Json $json,
OrderFactory $orderFactory
) {
parent::__construct($context);
$this->jsonResultFactory = $jsonResultFactory;
$this->balancepayConfig = $balancepayConfig;
$this->requestFactory = $requestFactory;
$this->json = $json;
$this->orderFactory = $orderFactory;
}
/**
* @return ResultInterface
* @throws \InvalidArgumentException
* @throws \Exception
*/
public function execute()
{
if (!$this->balancepayConfig->isActive()) {
return $this->resultFactory->create(ResultFactory::TYPE_FORWARD)->forward('noroute');
}

$resBody = [];

try {
$content = $this->getRequest()->getContent();
$headers = $this->getRequest()->getHeaders()->toArray();

$this->balancepayConfig->log('Webhook\Checkout\Confirmed::execute() ', 'debug', [
'content' => $content,
'headers' => $headers,
]);

//Validate Signature:
$signature = hash_hmac("sha256", $content, $this->balancepayConfig->getWebhookSecret());
if ($signature !== $headers['X-Blnce-Signature']) {
throw new \Exception("Signature is doesn't match!");
}

//Prepare & validate params:
$params = (array) $this->json->unserialize($content);
$this->validateParams($params);
$externalReferenceId = (string) $params['externalReferenceId'];
$isFinanced = $params['isFinanced'] ? 1 : 0;
$selectedPaymentMethod = (float) $params['selectedPaymentMethod'];

//Load the order:
$order = $this->orderFactory->create()->loadByIncrementId($externalReferenceId);

if (!$order || !$order->getId()) {
throw new \Exception("No matching order!");
}

$orderPayment = $order->getPayment();

$orderPayment
->setAdditionalInformation(BalancepayMethod::BALANCEPAY_IS_FINANCED, $isFinanced)
->setAdditionalInformation(BalancepayMethod::BALANCEPAY_SELECTED_PAYMENT_METHOD, $selectedPaymentMethod);

$orderPayment->save();
$order->save();

$resBody = [
"error" => 0,
"message" => "Success",
"order" => $order->getIncrementId()
];
} catch (\Exception $e) {
$this->balancepayConfig->log('Webhook\Transaction\Confirmed::execute() [Exception: ' . $e->getMessage() . "]\n" . $e->getTraceAsString(), 'error');
$resBody = [
"error" => 1,
"message" => $e->getMessage(),
];
if ($this->balancepayConfig->isDebugEnabled()) {
$resBody["trace"] = $e->getTraceAsString();
}
}

return $this->jsonResultFactory->create()
->setHttpResponseCode(\Magento\Framework\Webapi\Response::HTTP_OK)
->setData($resBody);
}

/**
* @return $this
* @throws Exception
*/
private function validateParams($params)
{
$requiredKeys = ['externalReferenceId', 'isFinanced', 'selectedPaymentMethod'];
$bodyKeys = array_keys($params);

$diff = array_diff($requiredKeys, $bodyKeys);
if (!empty($diff)) {
throw new Exception(
__(
'Balancepay webhook required fields are missing: %1.',
implode(', ', $diff)
)
);
}

return $this;
}

public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException
{
return null;
}

public function validateForCsrf(RequestInterface $request): ?bool
{
return true;
}
}
37 changes: 31 additions & 6 deletions Model/AbstractRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,15 @@ protected function getResponseHandler()
}

/**
* @param Quote $quote
* @param Quote $quote
* @param int|float $totalShippingAmount
*
* @return array
*/
protected function getLineItemsParams(Quote $quote)
protected function getLinesParams(Quote $quote, $totalShippingAmount = 0)
{
$params = [];
$totalItemsQty = 0;

foreach ($quote->getAllVisibleItems() as $quoteItem) {
$price = $this->amountFormat($quoteItem->getBasePrice());
Expand Down Expand Up @@ -215,16 +217,39 @@ protected function getLineItemsParams(Quote $quote)
'itemType' => $quoteItem->getIsVirtual() ? 'VIRTUAL' : 'PHYSICAL',
'price' => $price,
'tax' => $quoteItem->getBaseTaxAmount(),
'vendorId' => $balanceVendorId,
];

if ($balanceVendorId) {
$lineItem['vendorId'] = $balanceVendorId;
$totalItemsQty += $lineItem['quantity'];
$params[] = $lineItem;
}

$itemShippingPrice = $totalItemsQty ? ($totalShippingAmount / $totalItemsQty) : 0;

$lines = [];

foreach ($params as $param) {
$balanceVendorId = $param['vendorId'] ?: 0;
unset($param['vendorId']);
if (!isset($lines[$balanceVendorId])) {
$lines[$balanceVendorId] = [
"shippingPrice" => $itemShippingPrice * $lineItem['quantity'],
"lineItems" => [$param],
];
if ($balanceVendorId) {
$lines[$balanceVendorId]['vendorId'] = $balanceVendorId;
}
} else {
$lines[$balanceVendorId]['shippingPrice'] += $itemShippingPrice * $lineItem['quantity'];
$lines[$balanceVendorId]['lineItems'][] = $param;
}
}

$params[] = $lineItem;
foreach ($lines as &$line) {
$line['shippingPrice'] = $this->amountFormat($line['shippingPrice']);
}

return $params;
return array_values($lines);
}

/**
Expand Down
17 changes: 17 additions & 0 deletions Model/BalancepayMethod.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class BalancepayMethod extends AbstractMethod
const BALANCEPAY_CHECKOUT_TRANSACTION_ID = 'balancepay_checkout_transaction_id';
const BALANCEPAY_CHARGE_ID = 'balancepay_charge_id';
const BALANCEPAY_IS_AUTH_CHECKOUT = 'balancepay_is_auth_checkout';
const BALANCEPAY_IS_FINANCED = 'balancepay_is_financed';
const BALANCEPAY_SELECTED_PAYMENT_METHOD= 'balancepay_selected_payment_method';

/**
* Gateway code
Expand Down Expand Up @@ -216,6 +218,21 @@ public function __construct(
$this->request = $request;
}

/**
* Check whether payment method can be used
*
* @param \Magento\Quote\Api\Data\CartInterface|null $quote
* @return bool
* @deprecated 100.2.0
*/
public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null)
{
if ($quote && $quote->isMultipleShippingAddresses()) {
return false;
}
return parent::isAvailable($quote);
}

/**
* Assign data.
*
Expand Down
6 changes: 1 addition & 5 deletions Model/Request/Transactions.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,7 @@ protected function getParams()
"planType" => "invoice",
"chargeDate" => date('Y-m-d', strtotime($this->_balancepayConfig->getGmtDate())),
],
'lines' => [[
'shippingPrice' => $this->amountFormat($quoteTotals->getBaseShippingAmount()),
'tax' => $this->amountFormat($quoteTotals->getBaseTaxAmount()),
'lineItems' => $this->getLineItemsParams($quote),
]],
'lines' => $this->getLinesParams($quote, $quoteTotals->getBaseShippingAmount()),
'shippingLines' => $this->getShippingLinesParams($quote),
'totalDiscount' => abs($this->amountFormat($quoteTotals->getBaseDiscountAmount())),
'billingAddress' => $this->getBillingAddressParams($quote),
Expand Down
Loading

0 comments on commit 36fd607

Please sign in to comment.