Commit 5aa56a42 by Bartosz Kubicki

Init repo

parents
File added
<?php
namespace Meetanshi\Paymulti\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
/**
* Class Data
* @package Meetanshi\Paymulti\Helper
*/
class Data extends AbstractHelper
{
/**
*
*/
const MEETANSHI_MODULE_ENABLE = 'paymulti/general/active';
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var OrderInterface
*/
protected $order;
/**
* @var
*/
protected $extraPrice;
/**
* @var
*/
protected $itemPrice;
/**
* Data constructor.
* @param Context $context
* @param StoreManagerInterface $storeManager
* @param OrderInterface $order
*/
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
OrderInterface $order
) {
$this->storeManager = $storeManager;
$this->order = $order;
parent::__construct($context);
}
/**
* @return array
*/
public static function getSupportedCurrency()
{
return ['AUD', 'CAD', 'CZK', 'DKK', 'EUR', 'HKD', 'HUF', 'ILS', 'JPY', 'MXN',
'NOK', 'NZD', 'PLN', 'GBP', 'SGD', 'SEK', 'CHF', 'USD', 'TWD', 'THB', 'INR'];
}
/**
* @return bool
*/
public static function shouldConvert()
{
return !self::isActive();
}
/**
* @return mixed
*/
public function isActive()
{
return $this->scopeConfig->getValue(self::MEETANSHI_MODULE_ENABLE, ScopeInterface::SCOPE_STORE);
}
/**
* @param $quote
* @return mixed
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getConvertedGrandTotal($quote)
{
$toCurrency = $this->getCurrentCurrency();
$currentCurrency = $this->storeManager->getStore()->getCurrentCurrencyCode();
if ($toCurrency == $currentCurrency) {
return $quote->getGrandTotal();
} else {
return $this->getConvertedBaseAmount($quote->getBaseGrandTotal());
}
}
/**
* @return mixed
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getCurrentCurrency()
{
return $this->storeManager->getStore()->getCurrentCurrency()->getCode();
}
/**
* @param $value
* @return mixed
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getConvertedBaseAmount($value)
{
$baseCurrency = $this->storeManager->getStore()->getBaseCurrencyCode();
$currentCurrency = $this->getCurrentCurrency();
$amount = $this->convertCurrency($value, $baseCurrency, $currentCurrency);
return $amount;
}
/**
* @param $amountValue
* @param null $currencyCodeFrom
* @param null $currencyCodeTo
* @return mixed
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function convertCurrency($amountValue, $currencyCodeFrom = null, $currencyCodeTo = null)
{
return $this->storeManager->getStore()->getBaseCurrency()->convert($amountValue, $currencyCodeTo);
}
/**
* @return array
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getCurrencyArray()
{
return [$this->storeManager->getStore()->getBaseCurrencyCode()];
}
/**
* @param $orderID
* @return mixed
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getPaymentOrderCurrency($orderID)
{
$order = $this->order->load($orderID);
if ($order) {
$payment = $order->getPayment();
return $payment->getAdditionalInformation('payment_currency');
}
return $this->getCurrentCurrency();
}
/**
* @param $identifier
* @return mixed
*/
public function getConfig($identifier)
{
return $this->scopeConfig->getValue(
$identifier,
ScopeInterface::SCOPE_STORE
);
}
/**
* @param $key
* @param $value
*/
public function addExtraPrice($key, $value)
{
$this->extraPrice[$key] = $value;
}
/**
* @param $i
* @param $key
* @param $value
*/
public function addItemPrice($i, $key, $value)
{
$this->itemPrice[$i][$key] = $value;
}
/**
* @param array $request
* @return array
*/
public function convertRequest(array &$request)
{
$itemAmount = 0;
$extraprice = 0;
foreach ($this->itemPrice as $item) {
$itemAmount = $itemAmount + ((int)$item['qty'] * (float)$item['amount']);
}
foreach ($this->extraPrice as $key => $value) {
$extraprice = (float)$extraprice + (float)$value;
}
$baseprice = $extraprice + $itemAmount;
$request['AMT'] = number_format($baseprice,2);
$request['ITEMAMT'] = $itemAmount;
return $request;
}
}
<?php
namespace Meetanshi\Paymulti\Model\Api;
use Magento\Payment\Model\Method\Logger;
use Magento\Paypal\Model\Api\Nvp as PaypalNvp;
/**
* Class Nvp
* @package Meetanshi\Paymulti\Model\Api
*/
class Nvp extends PaypalNvp
{
/**
* @var \Meetanshi\Paymulti\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Framework\App\Request\Http
*/
protected $request;
/**
* Nvp constructor.
* @param \Magento\Customer\Helper\Address $customerAddress
* @param \Psr\Log\LoggerInterface $logger
* @param Logger $customLogger
* @param \Magento\Framework\Locale\ResolverInterface $localeResolver
* @param \Magento\Directory\Model\RegionFactory $regionFactory
* @param \Magento\Directory\Model\CountryFactory $countryFactory
* @param \Magento\Paypal\Model\Api\ProcessableExceptionFactory $processableExceptionFactory
* @param \Magento\Framework\Exception\LocalizedExceptionFactory $frameworkExceptionFactory
* @param \Magento\Framework\HTTP\Adapter\CurlFactory $curlFactory
* @param \Meetanshi\Paymulti\Helper\Data $helper
* @param \Magento\Framework\App\Request\Http $request
* @param array $data
*/
public function __construct(
\Magento\Customer\Helper\Address $customerAddress,
\Psr\Log\LoggerInterface $logger,
Logger $customLogger,
\Magento\Framework\Locale\ResolverInterface $localeResolver,
\Magento\Directory\Model\RegionFactory $regionFactory,
\Magento\Directory\Model\CountryFactory $countryFactory,
\Magento\Paypal\Model\Api\ProcessableExceptionFactory $processableExceptionFactory,
\Magento\Framework\Exception\LocalizedExceptionFactory $frameworkExceptionFactory,
\Magento\Framework\HTTP\Adapter\CurlFactory $curlFactory,
\Meetanshi\Paymulti\Helper\Data $helper,
\Magento\Framework\App\Request\Http $request,
array $data = []
)
{
$this->helper = $helper;
$this->request = $request;
parent::__construct($customerAddress, $logger, $customLogger, $localeResolver, $regionFactory, $countryFactory, $processableExceptionFactory, $frameworkExceptionFactory, $curlFactory, $data);
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function callSetExpressCheckout()
{
$this->_prepareExpressCheckoutCallRequest($this->_setExpressCheckoutRequest);
$request = $this->_exportToRequest($this->_setExpressCheckoutRequest);
$this->_exportLineItems($request);
// import/suppress shipping address, if any
$options = $this->getShippingOptions();
if ($this->getAddress()) {
$request = $this->_importAddresses($request);
$request['ADDROVERRIDE'] = 0;
} elseif ($options && count($options) <= 10) {
// doesn't support more than 10 shipping options
$request['CALLBACK'] = $this->getShippingOptionsCallbackUrl();
$request['CALLBACKTIMEOUT'] = 6;
// max value
$request['MAXAMT'] = $request['AMT'] + 999.00;
// it is impossible to calculate max amount
$this->_exportShippingOptions($request);
}
$response = $this->call(self::SET_EXPRESS_CHECKOUT, $request);
$this->_importFromResponse($this->_setExpressCheckoutResponse, $response);
}
/**
* @param array $request
* @param int $i
* @return array|bool|true|void|null
*/
protected function _exportLineItems(array &$request, $i = 0)
{
if (!$this->_cart) {
return;
}
$this->_cart->setTransferDiscountAsItem();
return $this->_exportPayPalLineItems($request, $i);
}
/**
* @param array $request
* @param int $i
* @return array|bool|void|null
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function _exportPayPalLineItems(array &$request, $i = 0)
{
if (!$this->_cart) {
return;
}
if ($this->_lineItemTotalExportMap) {
foreach ($this->_cart->getAmounts() as $key => $total) {
if (isset($this->_lineItemTotalExportMap[$key])) {
if ($this->helper->isActive()) {
$total = $this->helper->getConvertedBaseAmount($total);
}
$privateKey = $this->_lineItemTotalExportMap[$key];
$request[$privateKey] = $this->formatPrice($total);
if ($key != 'subtotal') {
$this->helper->addExtraPrice($key, $total);
}
}
}
}
$items = $this->_cart->getAllItems();
if (empty($items) || !$this->getIsLineItemsEnabled()) {
return;
}
$result = null;
foreach ($items as $item) {
foreach ($this->_lineItemExportItemsFormat as $publicKey => $privateFormat) {
$result = true;
$value = $item->getDataUsingMethod($publicKey);
if ($publicKey == 'amount' && $this->helper->isActive()) {
$value = $this->helper->getConvertedBaseAmount($value);
}
if ($publicKey == 'qty') {
$this->helper->addItemPrice($i, 'qty', $value);
}
if ($publicKey == 'amount') {
$this->helper->addItemPrice($i, 'amount', number_format($value, 2));
}
$request[sprintf($privateFormat, $i)] = $this->formatAmount($value, $publicKey);
}
$i++;
}
$result = $this->helper->convertRequest($request);
return $result;
}
/**
* @param $value
* @param $publicKey
* @return string
*/
private function formatAmount($value, $publicKey)
{
if (!empty($this->_lineItemExportItemsFilters[$publicKey])) {
$callback = $this->_lineItemExportItemsFilters[$publicKey];
$value = method_exists($this, $callback) ? $this->{$callback}($value) : $callback($value);
}
if (is_float($value)) {
$value = $this->formatPrice($value);
}
return $value;
}
/**
* @param array $request
* @param int $i
* @return bool
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function _exportShippingOptions(array &$request, $i = 0)
{
$options = $this->getShippingOptions();
if (empty($options)) {
return false;
}
foreach ($options as $option) {
foreach ($this->_shippingOptionsExportItemsFormat as $publicKey => $privateFormat) {
$value = $option->getDataUsingMethod($publicKey);
if (is_float($value)) {
if ($this->helper->isActive()) {
$value = $this->helper->getConvertedBaseAmount($value);
}
$value = $this->formatPrice($value);
}
if (is_bool($value)) {
$value = $this->_filterBool($value);
}
$request[sprintf($privateFormat, $i)] = $value;
}
$i++;
}
return true;
}
/**
* @param string $methodName
* @param array $request
* @return array|false|string|string[]
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Paypal\Model\Api\ProcessableException
*/
public function call($methodName, array $request)
{
$request = $this->_addMethodToRequest($methodName, $request);
$eachCallRequest = $this->_prepareEachCallRequest($methodName);
if ($this->getUseCertAuthentication()) {
$key = array_search('SIGNATURE', $eachCallRequest);
if ($key) {
unset($eachCallRequest[$key]);
}
}
$request = $this->_exportToRequest($eachCallRequest, $request);
$debugData = ['url' => $this->getApiEndpoint(), $methodName => $request];
if (isset($request['METHOD']) && ($request['METHOD'] == self::DO_CAPTURE ||
$request['METHOD'] == self::REFUND_TRANSACTION)) {
$orderId = $this->request->getParam('order_id');
if ($orderId) {
$paymentCurrency = $this->helper->getPaymentOrderCurrency($orderId);
$request['AMT'] = number_format($this->helper->convertCurrency($request['AMT'], null, $paymentCurrency), 2);
$request['CURRENCYCODE'] = $paymentCurrency;
}
}
try {
$http = $this->_curlFactory->create();
$config = ['timeout' => 60, 'verifypeer' => $this->_config->getValue('verifyPeer')];
if ($this->getUseProxy()) {
$config['proxy'] = $this->getProxyHost() . ':' . $this->getProxyPort();
}
if ($this->getUseCertAuthentication()) {
$config['ssl_cert'] = $this->getApiCertificate();
}
$http->setConfig($config);
$http->write(
\Zend_Http_Client::POST,
$this->getApiEndpoint(),
'1.1',
$this->_headers,
$this->_buildQuery($request)
);
$response = $http->read();
} catch (\Exception $e) {
$debugData['http_error'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
$this->_debug($debugData);
throw $e;
}
$response = preg_split('/^\r?$/m', $response, 2);
$response = trim($response[1]);
$response = $this->_deformatNVP($response);
$debugData['response'] = $response;
$this->_debug($debugData);
$response = $this->_postProcessResponse($response);
// handle transport error
if ($http->getErrno()) {
$this->_logger->critical(
new \Exception(
sprintf('PayPal NVP CURL connection error #%s: %s', $http->getErrno(), $http->getError())
)
);
$http->close();
throw new \Magento\Framework\Exception\LocalizedException(
__('Payment Gateway is unreachable at the moment. Please use another payment option.')
);
}
// cUrl resource must be closed after checking it for errors
$http->close();
if (!$this->_validateResponse($methodName, $response)) {
$this->_logger->critical(new \Exception(__('PayPal response hasn\'t required fields.')));
throw new \Magento\Framework\Exception\LocalizedException(
__('Something went wrong while processing your order.')
);
}
$this->_callErrors = [];
if ($this->_isCallSuccessful($response)) {
if ($this->_rawResponseNeeded) {
$this->setRawSuccessResponseData($response);
}
return $response;
}
$this->_handleCallErrors($response);
return $response;
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Paypal\Model\Api\ProcessableException
*/
public function callDoExpressCheckoutPayment()
{
$this->_prepareExpressCheckoutCallRequest($this->_doExpressCheckoutPaymentRequest);
$request = $this->_exportToRequest($this->_doExpressCheckoutPaymentRequest);
$this->_exportLineItems($request);
if ($this->getAddress()) {
$request = $this->_importAddresses($request);
$request['ADDROVERRIDE'] = 0;
}
$response = $this->call(self::DO_EXPRESS_CHECKOUT_PAYMENT, $request);
$this->_importFromResponse($this->_paymentInformationResponse, $response);
$this->_importFromResponse($this->_doExpressCheckoutPaymentResponse, $response);
$this->_importFromResponse($this->_createBillingAgreementResponse, $response);
}
}
<?php
namespace Meetanshi\Paymulti\Model;
use Magento\Paypal\Model\Express\Checkout as ExpressCheckout;
use Meetanshi\Paymulti\Helper\Data;
use Magento\Paypal\Model\Express as PaypalExpress;
/**
* Class Express
* @package Meetanshi\Paymulti\Model
*/
class Express extends PaypalExpress
{
/**
* @var Data
*/
protected $helper;
/**
* Express constructor.
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
* @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory
* @param \Magento\Payment\Helper\Data $paymentData
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Payment\Model\Method\Logger $logger
* @param \Magento\Paypal\Model\ProFactory $proFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Magento\Paypal\Model\CartFactory $cartFactory
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Framework\Exception\LocalizedExceptionFactory $exception
* @param \Magento\Sales\Api\TransactionRepositoryInterface $transactionRepository
* @param \Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface $transactionBuilder
* @param Data $helper
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
\Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Payment\Model\Method\Logger $logger,
\Magento\Paypal\Model\ProFactory $proFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Paypal\Model\CartFactory $cartFactory,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Framework\Exception\LocalizedExceptionFactory $exception,
\Magento\Sales\Api\TransactionRepositoryInterface $transactionRepository,
\Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface $transactionBuilder,
Data $helper,
array $data = []
)
{
$this->helper = $helper;
parent::__construct($context, $registry, $extensionFactory, $customAttributeFactory, $paymentData, $scopeConfig, $logger, $proFactory, $storeManager, $urlBuilder, $cartFactory, $checkoutSession, $exception, $transactionRepository, $transactionBuilder, null, null, $data);
}
/**
* @param \Magento\Sales\Model\Order\Payment $payment
* @param float $amount
* @return $this|PaypalExpress
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function _placeOrder(\Magento\Sales\Model\Order\Payment $payment, $amount)
{
$order = $payment->getOrder();
// prepare api call
$token = $payment->getAdditionalInformation(ExpressCheckout::PAYMENT_INFO_TRANSPORT_TOKEN);
$cart = $this->_cartFactory->create(['salesModel' => $order]);
if ($this->helper->isActive()) {
$amount = number_format($this->helper->getConvertedGrandTotal($order), 2);
$currencyCode = $this->helper->getCurrentCurrency();
} else {
$amount = $amount;
$currencyCode = $order->getBaseCurrencyCode();
}
$payment->setAdditionalInformation('payment_currency', $currencyCode);
$api = $this->getApi()->setToken(
$token
)->setPayerId(
$payment->getAdditionalInformation(ExpressCheckout::PAYMENT_INFO_TRANSPORT_PAYER_ID)
)->setAmount(
$amount
)->setPaymentAction(
$this->_pro->getConfig()->getValue('paymentAction')
)->setNotifyUrl(
$this->_urlBuilder->getUrl('paypal/ipn/')
)->setInvNum(
$order->getIncrementId()
)->setCurrencyCode(
$currencyCode
)->setPaypalCart(
$cart
)->setIsLineItemsEnabled(
$this->_pro->getConfig()->getValue('lineItemsEnabled')
);
if ($order->getIsVirtual()) {
$api->setAddress($order->getBillingAddress())->setSuppressShipping(true);
} else {
$api->setAddress($order->getShippingAddress());
$api->setBillingAddress($order->getBillingAddress());
}
// call api and get details from it
$api->callDoExpressCheckoutPayment();
$this->_importToPayment($api, $payment);
return $this;
}
}
<?php
namespace Meetanshi\Paymulti\Model\Express;
use Magento\Customer\Model\AccountManagement;
use Magento\Paypal\Model\Cart as PaypalCart;
use Magento\Paypal\Model\Config as PaypalConfig;
use Magento\Quote\Model\Quote\Address;
use Magento\Sales\Model\Order\Email\Sender\OrderSender;
use Magento\Paypal\Model\Express\Checkout as ExpressCheckout;
/**
* Class Checkout
* @package Meetanshi\Paymulti\Model\Express
*/
class Checkout extends ExpressCheckout
{
/**
* @var \Meetanshi\Paymulti\Helper\Data
*/
protected $helper;
/**
* Checkout constructor.
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Customer\Model\Url $customerUrl
* @param \Magento\Tax\Helper\Data $taxData
* @param \Magento\Checkout\Helper\Data $checkoutData
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\App\Cache\Type\Config $configCacheType
* @param \Magento\Framework\Locale\ResolverInterface $localeResolver
* @param \Magento\Paypal\Model\Info $paypalInfo
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\UrlInterface $coreUrl
* @param \Magento\Paypal\Model\CartFactory $cartFactory
* @param \Magento\Checkout\Model\Type\OnepageFactory $onepageFactory
* @param \Magento\Quote\Api\CartManagementInterface $quoteManagement
* @param \Magento\Paypal\Model\Billing\AgreementFactory $agreementFactory
* @param \Magento\Paypal\Model\Api\Type\Factory $apiTypeFactory
* @param \Magento\Framework\DataObject\Copy $objectCopyService
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Magento\Framework\Message\ManagerInterface $messageManager
* @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
* @param AccountManagement $accountManagement
* @param OrderSender $orderSender
* @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
* @param \Magento\Quote\Model\Quote\TotalsCollector $totalsCollector
* @param \Meetanshi\Paymulti\Helper\Data $helper
* @param array $params
* @throws \Exception
*/
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Customer\Model\Url $customerUrl,
\Magento\Tax\Helper\Data $taxData,
\Magento\Checkout\Helper\Data $checkoutData,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\App\Cache\Type\Config $configCacheType,
\Magento\Framework\Locale\ResolverInterface $localeResolver,
\Magento\Paypal\Model\Info $paypalInfo,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\UrlInterface $coreUrl,
\Magento\Paypal\Model\CartFactory $cartFactory,
\Magento\Checkout\Model\Type\OnepageFactory $onepageFactory,
\Magento\Quote\Api\CartManagementInterface $quoteManagement,
\Magento\Paypal\Model\Billing\AgreementFactory $agreementFactory,
\Magento\Paypal\Model\Api\Type\Factory $apiTypeFactory,
\Magento\Framework\DataObject\Copy $objectCopyService,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Framework\Encryption\EncryptorInterface $encryptor,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
AccountManagement $accountManagement,
OrderSender $orderSender,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
\Magento\Quote\Model\Quote\TotalsCollector $totalsCollector,
\Meetanshi\Paymulti\Helper\Data $helper,
$params = []
)
{
$this->helper = $helper;
parent::__construct($logger, $customerUrl, $taxData, $checkoutData, $customerSession, $configCacheType, $localeResolver, $paypalInfo, $storeManager, $coreUrl, $cartFactory, $onepageFactory, $quoteManagement, $agreementFactory, $apiTypeFactory, $objectCopyService, $checkoutSession, $encryptor, $messageManager, $customerRepository, $accountManagement, $orderSender, $quoteRepository, $totalsCollector, $params);
}
/**
* @param string $returnUrl
* @param string $cancelUrl
* @param null $button
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function start($returnUrl, $cancelUrl, $button = null)
{
$this->_quote->collectTotals();
if (!$this->_quote->getGrandTotal()) {
throw new \Magento\Framework\Exception\LocalizedException(
__(
'PayPal can\'t process orders with a zero balance due. '
. 'To finish your purchase, please go through the standard checkout process.'
)
);
}
$this->_quote->reserveOrderId();
$this->quoteRepository->save($this->_quote);
// prepare API
$solutionType = $this->_config->getMerchantCountry() == 'DE'
? \Magento\Paypal\Model\Config::EC_SOLUTION_TYPE_MARK
: $this->_config->getValue('solutionType');
if ($this->helper->isActive()) {
$totalAmount = $this->helper->getConvertedGrandTotal($this->_quote);
$currencyCode = $this->helper->getCurrentCurrency();
} else {
$totalAmount = round($this->_quote->getBaseGrandTotal(), 2);
$currencyCode = $this->_quote->getBaseCurrencyCode();
}
$this->_getApi()->setAmount($totalAmount)
->setCurrencyCode($currencyCode)
->setInvNum($this->_quote->getReservedOrderId())
->setReturnUrl($returnUrl)
->setCancelUrl($cancelUrl)
->setSolutionType($solutionType)
->setPaymentAction($this->_config->getValue('paymentAction'));
if ($this->_giropayUrls) {
list($successUrl, $cancelUrl, $pendingUrl) = $this->_giropayUrls;
$this->_getApi()->addData(
[
'giropay_cancel_url' => $cancelUrl,
'giropay_success_url' => $successUrl,
'giropay_bank_txn_pending_url' => $pendingUrl,
]
);
}
if ($this->_isBml) {
$this->_getApi()->setFundingSource('BML');
}
$this->_setBillingAgreementRequest();
if ($this->_config->getValue('requireBillingAddress') == PaypalConfig::REQUIRE_BILLING_ADDRESS_ALL) {
$this->_getApi()->setRequireBillingAddress(1);
}
// suppress or export shipping address
$address = null;
if ($this->_quote->getIsVirtual()) {
if ($this->_config->getValue('requireBillingAddress')
== PaypalConfig::REQUIRE_BILLING_ADDRESS_VIRTUAL
) {
$this->_getApi()->setRequireBillingAddress(1);
}
$this->_getApi()->setSuppressShipping(true);
} else {
$this->_getApi()->setBillingAddress($this->_quote->getBillingAddress());
$address = $this->_quote->getShippingAddress();
$isOverridden = 0;
if (true === $address->validate()) {
$isOverridden = 1;
$this->_getApi()->setAddress($address);
}
$this->_quote->getPayment()->setAdditionalInformation(
self::PAYMENT_INFO_TRANSPORT_SHIPPING_OVERRIDDEN,
$isOverridden
);
$this->_quote->getPayment()->save();
}
/** @var $cart \Magento\Payment\Model\Cart */
$cart = $this->_cartFactory->create(['salesModel' => $this->_quote]);
$this->_getApi()->setPaypalCart($cart);
if (!$this->_taxData->getConfig()->priceIncludesTax()) {
$this->setShippingOptions($cart, $address);
}
$this->_config->exportExpressCheckoutStyleSettings($this->_getApi());
/* Temporary solution. @TODO: do not pass quote into Nvp model */
$this->_getApi()->setQuote($this->_quote);
$this->_getApi()->callSetExpressCheckout();
$token = $this->_getApi()->getToken();
$this->_setRedirectUrl($button, $token);
$payment = $this->_quote->getPayment();
$payment->unsAdditionalInformation(self::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT);
// Set flag that we came from Express Checkout button
if (!empty($button)) {
$payment->setAdditionalInformation(self::PAYMENT_INFO_BUTTON, 1);
} elseif ($payment->hasAdditionalInformation(self::PAYMENT_INFO_BUTTON)) {
$payment->unsAdditionalInformation(self::PAYMENT_INFO_BUTTON);
}
$payment->save();
return $token;
}
/**
* @param PaypalCart $cart
* @param Address|null $address
*/
private function setShippingOptions(PaypalCart $cart, Address $address = null)
{
// for included tax always disable line items (related to paypal amount rounding problem)
$this->_getApi()->setIsLineItemsEnabled($this->_config->getValue(PaypalConfig::TRANSFER_CART_LINE_ITEMS));
// add shipping options if needed and line items are available
$cartItems = $cart->getAllItems();
if ($this->_config->getValue(PaypalConfig::TRANSFER_CART_LINE_ITEMS)
&& $this->_config->getValue(PaypalConfig::TRANSFER_SHIPPING_OPTIONS)
&& !empty($cartItems)
) {
if (!$this->_quote->getIsVirtual()) {
$options = $this->_prepareShippingOptions($address, true);
if ($options) {
$this->_getApi()->setShippingOptionsCallbackUrl(
$this->_coreUrl->getUrl(
'*/*/shippingOptionsCallback',
['quote_id' => $this->_quote->getId()]
)
)->setShippingOptions($options);
}
}
}
}
}
<?php
namespace Meetanshi\Paymulti\Model\Paypal;
use Magento\Paypal\Model\Config as PayPalConfig;
/**
* Class Config
* @package Meetanshi\Paymulti\Model\Paypal
*/
class Config extends PayPalConfig
{
/**
* @var \Meetanshi\Paymulti\Helper\Data
*/
protected $helper;
/**
* @var array
*/
protected $_supportedCurrencyCodes = [
'AUD',
'CAD',
'CZK',
'DKK',
'EUR',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PLN',
'GBP',
'RUB',
'SGD',
'SEK',
'CHF',
'TWD',
'THB',
'USD',
'INR',
];
/**
* Config constructor.
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Directory\Helper\Data $directoryHelper
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Payment\Model\Source\CctypeFactory $cctypeFactory
* @param \Magento\Paypal\Model\CertFactory $certFactory
* @param \Meetanshi\Paymulti\Helper\Data $helper
* @param array $params
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Directory\Helper\Data $directoryHelper,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Payment\Model\Source\CctypeFactory $cctypeFactory,
\Magento\Paypal\Model\CertFactory $certFactory,
\Meetanshi\Paymulti\Helper\Data $helper,
$params = []
) {
parent::__construct($scopeConfig, $directoryHelper, $storeManager, $cctypeFactory, $certFactory, $params);
$this->helper = $helper;
}
/**
* @param string $code
* @return bool
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function isCurrencyCodeSupported($code)
{
if ($this->helper->isActive()) {
$this->_supportedCurrencyCodes =
array_merge($this->_supportedCurrencyCodes, $this->helper->getCurrencyArray());
}
if (in_array($code, $this->_supportedCurrencyCodes)) {
return true;
}
if ($this->getMerchantCountry() == 'BR' && $code == 'BRL') {
return true;
}
if ($this->getMerchantCountry() == 'MY' && $code == 'MYR') {
return true;
}
if ($this->getMerchantCountry() == 'TR' && $code == 'TRY') {
return true;
}
return false;
}
}
<?php
namespace Meetanshi\Paymulti\Model\Source;
/**
* Class Currency
* @package Meetanshi\Paymulti\Model\Source
*/
class Currency extends \Magento\Config\Model\Config\Source\Locale\Currency
{
/**
* @var \Magento\Framework\Locale\ListsInterface
*/
protected $_localeLists;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_currencySymbol;
/**
* @var \Meetanshi\Paymulti\Helper\Data
*/
protected $_helper;
/**
* Currency constructor.
* @param \Magento\Framework\Locale\ListsInterface $localeLists
* @param \Magento\Store\Model\StoreManagerInterface $currencySymbol
* @param \Meetanshi\Paymulti\Helper\Data $helper
*/
public function __construct(
\Magento\Framework\Locale\ListsInterface $localeLists,
\Magento\Store\Model\StoreManagerInterface $currencySymbol,
\Meetanshi\Paymulti\Helper\Data $helper
) {
$this->_localeLists = $localeLists;
$this->_currencySymbol = $currencySymbol;
$this->_helper = $helper;
parent::__construct($localeLists);
}
/**
* @return array
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function toOptionArray()
{
$_supportedCurrencyCodes = $this->_helper->getSupportedCurrency();
$_availableCurrencyCodes = $this->_currencySymbol->getStore()->getAvailableCurrencyCodes(true);
;
if (!$this->_options) {
$this->_options = $this->_localeLists->getOptionCurrencies();
}
$options = [];
foreach ($this->_options as $option) {
if (in_array($option['value'], $_supportedCurrencyCodes) && in_array($option['value'], $_availableCurrencyCodes)) {
$options[] = $option;
}
}
return $options;
}
}
{
"name": "meetanshi/magento2-paypal-multi-currency",
"description": "Magento 2 paypal multi currency",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0|7.0.2|7.0.4|~7.0.6|~7.1.0|~7.2.0|~7.3.0"
},
"type": "magento2-module",
"version": "1.0.4",
"license": [
"OSL-3.0"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Meetanshi\\Paymulti\\": ""
}
},
"support": {
"email": "support@meetanshi.com"
},
"authors": [
{
"name": "Jignesh Parmar",
"email": "support@meetanshi.com",
"homepage": "https://meetanshi.com"
}
]
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="Meetanshi_Paymulti::config_paymulti" title="Paypal Multi Currency" />
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="paymulti" frontName="paymulti">
<module name="Meetanshi_Paymulti" />
</route>
</router>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="meetanshi" translate="label" class="meetanshi" sortOrder="99998">
<label></label>
</tab>
<section id="paymulti" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>PayPal Multi Currency</label>
<tab>meetanshi</tab>
<resource>Meetanshi_Paymulti::config_paymulti</resource>
<group id="general" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Configuration</label>
<field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>PayPal Multi Currency</label>
<source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model>
</field>
</group>
</section>
</system>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<paymulti>
<general>
<active>1</active>
</general>
</paymulti>
</default>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Paypal\Model\Express\Checkout" type="Meetanshi\Paymulti\Model\Express\Checkout"/>
<preference for="Magento\Paypal\Model\Api\Nvp" type="Meetanshi\Paymulti\Model\Api\Nvp"/>
<preference for="Magento\Paypal\Model\Express" type="Meetanshi\Paymulti\Model\Express"/>
<preference for="Magento\Paypal\Model\Config" type="Meetanshi\Paymulti\Model\Paypal\Config" />
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Meetanshi_Paymulti" setup_version="1.0.4" schema_version="1.0.4">
</module>
</config>
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Meetanshi_Paymulti',
__DIR__
);
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Meetanshi_Paymulti::css/meetanshi.css"/>
</head>
</page>
.meetanshi .title:before {
background-image: url(https://meetanshi.com/media/logo.png);
background-size: 150px 19px;
display: inline-block;
width: 150px;
height: 19px;
content: "";
background-repeat: no-repeat;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment