Skip to content

Commit

Permalink
Merge branch 'develop' into release/v1.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
tomk1v committed Dec 18, 2024
2 parents 7317df9 + acfebda commit 1df13e7
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 53 deletions.
74 changes: 74 additions & 0 deletions Model/Cache/Currency.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php
/**
* @category Internship
* @package Internship\BinancePay
* @author Andrii Tomkiv <tomkivandrii18@gmail.com>
* @copyright 2024 Tomkiv
*/

declare(strict_types=1);

namespace Internship\BinancePay\Model\Cache;

class Currency
{
private const CACHE_KEY = 'binance_supported_currencies';
private const CACHE_LIFETIME = 86400;

/**
* @param \Magento\Framework\App\CacheInterface $cache
* @param \Internship\BinancePay\Service\BinancePay $binancePay
* @param \Magento\Framework\Serialize\Serializer\Json $jsonSerializer
*/
public function __construct(
private readonly \Magento\Framework\App\CacheInterface $cache,
private readonly \Internship\BinancePay\Service\BinancePay $binancePay,
private readonly \Magento\Framework\Serialize\Serializer\Json $jsonSerializer,
) {
}

/**
* Fetches currencies from cache or updates the cache if empty or outdated.
*
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getCurrencies(): array
{
try {
$cachedData = $this->cache->load(self::CACHE_KEY);

if ($cachedData) {
return $this->jsonSerializer->unserialize($cachedData);
}

return $this->fetchAndCacheCurrencies();
} catch (\Exception $exception) {
throw new \Magento\Framework\Exception\LocalizedException(__());
}
}

/**
* Fetches currencies from Binance API.
*
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function fetchAndCacheCurrencies(): array
{
try {
$currencies = $this->binancePay->getSupportedCurrencies();

$this->cache->save(
$this->jsonSerializer->serialize($currencies),
self::CACHE_KEY,
[],
self::CACHE_LIFETIME
);

return $currencies;
} catch (\Exception $exception) {
throw new \Magento\Framework\Exception\LocalizedException(__($exception->getMessage()));
}
}
}
46 changes: 30 additions & 16 deletions Model/Payment/Mapping.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,49 @@ class Mapping
/**
* @param \DateTime $dateTime
* @param \Magento\Framework\UrlInterface $url
* @param \Internship\BinancePay\Model\Cache\Currency $currency
*/
public function __construct(
private readonly \DateTime $dateTime,
private readonly \Magento\Framework\UrlInterface $url
private readonly \Magento\Framework\UrlInterface $url,
private readonly \Internship\BinancePay\Model\Cache\Currency $currency
) {
}

/**
* Map body for order creation.
*
* @param object $quote
* @param \Magento\Quote\Model\Quote $quote
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function mapOrderBody($quote)
{
return [
'env' => [
'terminalType' => 'WEB'
],
'orderTags' => [
'ifProfitSharing' => false
],
'merchantTradeNo' => $this->generateUniqueMerchantTradeNo(),
'orderAmount' => $quote->getGrandTotal(),
'currency' => 'USDT',
'description' => $this->getQuoteItemsDescription($quote->getItems()),
'goodsDetails' => $this->generateGoods($quote->getItems()),
'returnUrl' => $this->getReturnUrl() . '?quoteId=' . $quote->getId()
];
try {
$currencies = $this->currency->getCurrencies();

if (!in_array($quote->getQuoteCurrencyCode(), $currencies)) {
throw new \Magento\Framework\Exception\LocalizedException(__('Currency is not supported.'));
}

return [
'env' => [
'terminalType' => 'WEB'
],
'orderTags' => [
'ifProfitSharing' => false

],
'merchantTradeNo' => $this->generateUniqueMerchantTradeNo(),
'fiatAmount' => $quote->getGrandTotal(),
'fiatCurrency' => $quote->getQuoteCurrencyCode(),
'description' => $this->getQuoteItemsDescription($quote->getItems()),
'goodsDetails' => $this->generateGoods($quote->getItems()),
'returnUrl' => $this->getReturnUrl() . '?quoteId=' . $quote->getId()
];
} catch (\Exception $exception) {
throw new \Magento\Framework\Exception\LocalizedException(__($exception->getMessage()));
}
}

/**
Expand Down
36 changes: 36 additions & 0 deletions Service/BinancePay.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
class BinancePay
{
protected const BASE_URL = 'https://bpay.binanceapi.com';
protected const BASE_URL_CURRENCY = 'https://www.binance.com';
protected const BUILD_ORDER_ENDPOINT = '/binancepay/openapi/v3/order';
protected const GET_CERTIFICATE_ENDPOINT = '/binancepay/openapi/certificates';
protected const GET_CURRENCIES_ENDPOINT = '/bapi/asset/v1/public/asset-service/product/currency';
protected const BUILD_REFUND_ENDPOINT = '/binancepay/openapi/order/refund';

/**
Expand Down Expand Up @@ -55,6 +57,40 @@ public function buildRefund(string $body): array
return $this->sendRequest(self::BUILD_REFUND_ENDPOINT, $body);
}

/**
* Fetches the list of supported currencies.
*
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getSupportedCurrencies(): array
{
try {
$curl = $this->curlFactory->create();
$curl->setOption(CURLOPT_ENCODING, '');
$curl->get(self::BASE_URL_CURRENCY . self::GET_CURRENCIES_ENDPOINT);

$response = $curl->getBody();
$data = $this->jsonSerializer->unserialize($response);
if (isset($data['data']) && is_array($data['data'])) {
$currencies = [];
foreach ($data['data'] as $currency) {
if (isset($currency['pair'])) {
$pair = explode('_', $currency['pair']);
if (isset($pair[0])) {
$currencies[] = $pair[0];
}
}
}
return $currencies;
}
} catch (\Exception $exception) {
throw new \Magento\Framework\Exception\LocalizedException(__($exception->getMessage()));
}

return [];
}

/**
* Sends a request to the specified endpoint with the provided body data.
*
Expand Down
3 changes: 2 additions & 1 deletion view/frontend/web/js/binance-price.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ define(['jquery'], function ($) {
$('.crypto-amount').each(function () {
const defaultPrice = parseFloat($(this).data('amount'));
const cryptoPrice = (defaultPrice / avgPriceInUsdt).toFixed(6);
const symbol = config.symbol.replace('usdt', '').toUpperCase();

$(this).fadeOut(200, function () {
$(this).text(`Crypto Price: ${cryptoPrice} USD`).fadeIn(200);
$(this).text(`Crypto Price: ${cryptoPrice} ${symbol}`).fadeIn(200);
});
});
};
Expand Down
24 changes: 0 additions & 24 deletions view/frontend/web/js/model/binancepay-validator.js

This file was deleted.

12 changes: 0 additions & 12 deletions view/frontend/web/js/view/payment/binancepay-validator.js

This file was deleted.

0 comments on commit 1df13e7

Please sign in to comment.