This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,182 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\Api;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\HTTP\Adapter\Curl;
use Magento\Framework\HTTP\Adapter\CurlFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Paypal\Model\CartFactory;
use Magento\Paypal\Model\Config;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteRepository;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\MockObject\MockObject as MockObject;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class NvpTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Nvp
*/
private $nvpApi;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Curl|MockObject
*/
private $httpClient;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/** @var CurlFactory|MockObject $httpFactory */
$httpFactory = $this->getMockBuilder(CurlFactory::class)
->disableOriginalConstructor()
->getMock();
$this->httpClient = $this->getMockBuilder(Curl::class)
->disableOriginalConstructor()
->getMock();
$httpFactory->method('create')
->willReturn($this->httpClient);
$this->nvpApi = $this->objectManager->create(Nvp::class, [
'curlFactory' => $httpFactory
]);
/** @var ProductMetadataInterface|MockObject $productMetadata */
$productMetadata = $this->getMockBuilder(ProductMetadataInterface::class)
->getMock();
$productMetadata->method('getEdition')
->willReturn('');
/** @var Config $config */
$config = $this->objectManager->get(Config::class);
$config->setMethodCode(Config::METHOD_EXPRESS);
$refObject = new \ReflectionObject($config);
$refProperty = $refObject->getProperty('productMetadata');
$refProperty->setAccessible(true);
$refProperty->setValue($config, $productMetadata);
$this->nvpApi->setConfigObject($config);
}
/**
* Checks a case when items with FPT (Fixed Product Tax) are present in the request.
*
* @magentoConfigFixture current_store tax/weee/enable 1
* @magentoConfigFixture current_store tax/weee/include_in_subtotal 0
* @magentoDataFixture Magento/Paypal/_files/quote_with_fpt.php
*/
public function testRequestTotalsAndLineItemsWithFPT()
{
$quote = $this->getQuote('100000016');
/** @var CartFactory $cartFactory */
$cartFactory = $this->objectManager->get(CartFactory::class);
$cart = $cartFactory->create(['salesModel' => $quote]);
$request = 'PAYMENTACTION=Authorization&AMT=112.70'
. '&SHIPPINGAMT=0.00&ITEMAMT=112.70&TAXAMT=0.00'
. '&L_NAME0=Simple+Product+FPT&L_QTY0=1&L_AMT0=100.00'
. '&L_NAME1=FPT&L_QTY1=1&L_AMT1=12.70'
. '&METHOD=SetExpressCheckout&VERSION=72.0&BUTTONSOURCE=Magento_2_';
$this->httpClient->method('write')
->with(
'POST',
'https://api-3t.paypal.com/nvp',
'1.1',
[],
$this->equalTo($request)
);
$this->httpClient->method('read')
->willReturn(
"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nRESULT=0&RESPMSG=Approved"
);
$this->nvpApi->setAmount($quote->getBaseGrandTotal());
$this->nvpApi->setPaypalCart($cart);
$this->nvpApi->setQuote($quote);
$this->nvpApi->setIsLineItemsEnabled(true);
$this->nvpApi->callSetExpressCheckout();
}
/**
* Test that the refund request to Paypal sends the correct data
*
* @magentoDataFixture Magento/Paypal/_files/order_express_with_tax.php
*/
public function testCallRefundTransaction()
{
/** @var \Magento\Sales\Model\Order $order */
$order = $this->objectManager->create(\Magento\Sales\Model\Order::class);
$order->loadByIncrementId('100000001');
/** @var \Magento\Sales\Model\Order\Payment $payment */
$payment = $order->getPayment();
$this->nvpApi->setPayment(
$payment
)->setTransactionId(
'fooTransactionId'
)->setAmount(
$payment->formatAmount($order->getBaseGrandTotal())
)->setCurrencyCode(
$order->getBaseCurrencyCode()
)->setRefundType(
Config::REFUND_TYPE_PARTIAL
);
$httpQuery = 'TRANSACTIONID=fooTransactionId&REFUNDTYPE=Partial'
.'&CURRENCYCODE=USD&AMT=145.98&METHOD=RefundTransaction'
.'&VERSION=72.0&BUTTONSOURCE=Magento_2_';
$this->httpClient->expects($this->once())->method('write')
->with(
'POST',
'https://api-3t.paypal.com/nvp',
'1.1',
[],
$httpQuery
);
$this->httpClient->method('read')->willReturn('');
$this->nvpApi->callRefundTransaction();
}
/**
* Gets quote by reserved order id.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuote($reservedOrderId)
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->create(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var QuoteRepository $quoteRepository */
$quoteRepository = $this->objectManager->get(QuoteRepository::class);
$items = $quoteRepository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\Api;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\HTTP\Adapter\Curl;
use Magento\Framework\HTTP\Adapter\CurlFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Paypal\Model\CartFactory;
use Magento\Paypal\Model\Config;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteRepository;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\MockObject_MockObject as MockObject;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PayflowNvpTest extends \PHPUnit\Framework\TestCase
{
/**
* @var PayflowNvp
*/
private $nvpApi;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Curl|MockObject
*/
private $httpClient;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/** @var CurlFactory|MockObject $httpFactory */
$httpFactory = $this->getMockBuilder(CurlFactory::class)
->disableOriginalConstructor()
->getMock();
$this->httpClient = $this->getMockBuilder(Curl::class)
->disableOriginalConstructor()
->getMock();
$httpFactory->method('create')
->willReturn($this->httpClient);
$this->nvpApi = $this->objectManager->create(PayflowNvp::class, [
'curlFactory' => $httpFactory
]);
/** @var ProductMetadataInterface|MockObject $productMetadata */
$productMetadata = $this->getMockBuilder(ProductMetadataInterface::class)
->getMock();
$productMetadata->method('getEdition')
->willReturn('');
/** @var Config $config */
$config = $this->objectManager->get(Config::class);
$config->setMethodCode(Config::METHOD_WPP_PE_EXPRESS);
$refObject = new \ReflectionObject($config);
$refProperty = $refObject->getProperty('productMetadata');
$refProperty->setAccessible(true);
$refProperty->setValue($config, $productMetadata);
$this->nvpApi->setConfigObject($config);
}
/**
* Checks a case when items and discount are present in the request.
*
* @magentoDataFixture Magento/Paypal/_files/quote_payflowpro.php
* @magentoDbIsolation disabled
*/
public function testRequestLineItems()
{
$quote = $this->getQuote('100000015');
/** @var CartFactory $cartFactory */
$cartFactory = $this->objectManager->get(CartFactory::class);
$cart = $cartFactory->create(['salesModel' => $quote]);
$request = 'TENDER=P&AMT=52.14&FREIGHTAMT=0.00&TAXAMT=0.00&'
. 'L_NAME0=Simple 1&L_QTY0=1&L_COST0=7.69&'
. 'L_NAME1=Simple 2&L_QTY1=2&L_COST1=9.69&'
. 'L_NAME2=Simple 3&L_QTY2=3&L_COST2=11.69&'
. 'L_NAME3=Discount&L_QTY3=1&L_COST3=-10.00&'
. 'TRXTYPE=A&ACTION=S&BUTTONSOURCE=Magento_2_';
$this->httpClient->method('write')
->with(
'POST',
'https://payflowpro.paypal.com/transaction',
'1.1',
['PAYPAL-NVP: Y'],
self::equalTo($request)
);
$this->httpClient->method('read')
->willReturn("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nRESULT=0&RESPMSG=Approved");
$this->nvpApi->setAmount($quote->getBaseGrandTotal());
$this->nvpApi->setPaypalCart($cart);
$this->nvpApi->setQuote($quote);
$this->nvpApi->setIsLineItemsEnabled(true);
$this->nvpApi->callSetExpressCheckout();
}
/**
* Gets quote by reserved order id.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuote($reservedOrderId)
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->create(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var QuoteRepository $quoteRepository */
$quoteRepository = $this->objectManager->get(QuoteRepository::class);
$items = $quoteRepository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,783 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\Express;
use Magento\Checkout\Model\Type\Onepage;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Paypal\Model\Api\Nvp;
use Magento\Paypal\Model\Api\Type\Factory;
use Magento\Paypal\Model\Config;
use Magento\Paypal\Model\Info;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Address;
use Magento\Quote\Model\ResourceModel\Quote\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CheckoutTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Info|MockObject
*/
private $paypalInfo;
/**
* @var Config|MockObject
*/
private $paypalConfig;
/**
* @var Factory|MockObject
*/
private $apiTypeFactory;
/**
* @var Nvp|MockObject
*/
private $api;
/**
* @var Checkout
*/
private $checkoutModel;
/**
* Set up
*
* @return void
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->paypalInfo = $this->getMockBuilder(Info::class)
->disableOriginalConstructor()
->getMock();
$this->paypalConfig = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock();
$this->api = $this->getMockBuilder(Nvp::class)
->disableOriginalConstructor()
->setMethods(['call', 'getExportedShippingAddress', 'getExportedBillingAddress', 'getShippingRateCode'])
->getMock();
$this->api->expects($this->any())
->method('call')
->willReturn([]);
$this->apiTypeFactory = $this->getMockBuilder(Factory::class)
->disableOriginalConstructor()
->getMock();
$this->apiTypeFactory->expects($this->any())
->method('create')
->willReturn($this->api);
}
/**
* Verify that api has set customer email.
*
* @magentoDataFixture Magento/Paypal/_files/quote_express.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testCheckoutStartWithBillingAddress()
{
$quote = $this->getFixtureQuote();
$paypalConfig = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock();
$apiTypeFactory = $this->getMockBuilder(Factory::class)
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$paypalInfo = $this->getMockBuilder(Info::class)
->disableOriginalConstructor()
->getMock();
$checkoutModel = $this->objectManager->create(
Checkout::class,
[
'params' => ['quote' => $quote, 'config' => $paypalConfig],
'apiTypeFactory' => $apiTypeFactory,
'paypalInfo' => $paypalInfo
]
);
$api = $this->getMockBuilder(Nvp::class)
->disableOriginalConstructor()
->setMethods(['callSetExpressCheckout'])
->getMock();
$api->expects($this->any())
->method('callSetExpressCheckout')
->willReturn(null);
$apiTypeFactory->expects($this->any())
->method('create')
->willReturn($api);
$checkoutModel->start(
'return',
'cancel',
false
);
$this->assertEquals('test@com.com', $api->getBillingAddress()->getEmail());
}
/**
* Verify that an order placed with an existing customer can re-use the customer addresses.
*
* @magentoDataFixture Magento/Paypal/_files/quote_express_with_customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testPrepareCustomerQuote()
{
/** @var Quote $quote */
$quote = $this->getFixtureQuote();
$quote->setCheckoutMethod(Onepage::METHOD_CUSTOMER); // to dive into _prepareCustomerQuote() on switch
$quote->getShippingAddress()->setSameAsBilling(0);
$quote->setReservedOrderId(null);
$customer = $this->objectManager->create(\Magento\Customer\Model\Customer::class)->load(1);
$customer->setDefaultBilling(false)
->setDefaultShipping(false)
->save();
/** @var \Magento\Customer\Model\Session $customerSession */
$customerSession = $this->objectManager->get(\Magento\Customer\Model\Session::class);
$customerSession->loginById(1);
$checkout = $this->getCheckout($quote);
$checkout->place('token');
/** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerService */
$customerService = $this->objectManager->get(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$customer = $customerService->getById($quote->getCustomerId());
$this->assertEquals(1, $quote->getCustomerId());
$this->assertCount(2, $customer->getAddresses());
$this->assertEquals(1, $quote->getBillingAddress()->getCustomerAddressId());
$this->assertEquals(2, $quote->getShippingAddress()->getCustomerAddressId());
$order = $checkout->getOrder();
$this->assertEquals(1, $order->getBillingAddress()->getCustomerAddressId());
$this->assertEquals(2, $order->getShippingAddress()->getCustomerAddressId());
}
/**
* Verify that after placing the order, addresses are associated with the order and the quote is a guest quote.
*
* @magentoDataFixture Magento/Paypal/_files/quote_express.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @param string $accountEmail
* @param string $expected
* @dataProvider placeGuestQuoteDataProvider
*/
public function testPlaceGuestQuote($accountEmail, $expected)
{
/** @var Quote $quote */
$quote = $this->getFixtureQuote();
$quote->setCheckoutMethod(Onepage::METHOD_GUEST); // to dive into _prepareGuestQuote() on switch
$quote->getShippingAddress()->setSameAsBilling(0);
$quote->setReservedOrderId(null);
/* Simulate data returned from PayPal containing email as well
as email entered at checkout step */
$quote->getBillingAddress()->setEmail('paypal_account@email.com');
$quote->getBillingAddress()->setOrigData('email', $accountEmail);
$checkout = $this->getCheckout($quote);
$checkout->place('token');
$this->assertNull($quote->getCustomerId());
$this->assertTrue($quote->getCustomerIsGuest());
$this->assertEquals(
\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID,
$quote->getCustomerGroupId()
);
$this->assertEquals($expected, $quote->getCustomerEmail());
$this->assertNotEmpty($quote->getBillingAddress());
$this->assertNotEmpty($quote->getShippingAddress());
$this->assertEquals($quote->getBillingAddress()->getFirstname(), $quote->getCustomerFirstname());
$this->assertEquals($quote->getBillingAddress()->getLastname(), $quote->getCustomerLastname());
$order = $checkout->getOrder();
$this->assertNotEmpty($order->getBillingAddress());
$this->assertNotEmpty($order->getShippingAddress());
$this->assertEquals($quote->getBillingAddress()->getFirstname(), $order->getCustomerFirstname());
$this->assertEquals($quote->getBillingAddress()->getLastname(), $order->getCustomerLastname());
}
/**
* @return array
*/
public function placeGuestQuoteDataProvider(): array
{
return [
'case with account email absent' => [null, 'paypal_account@email.com'],
'case with account email present' => ['magento_account@email.com', 'magento_account@email.com'],
];
}
/**
* Place the order as guest when `Automatic Assignment to Customer Group` is enabled.
*
* @magentoDataFixture Magento/Paypal/_files/quote_express.php
* @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
*
* @return void
*/
public function testPlaceGuestQuoteAutomaticAssignmentEnabled(): void
{
$quote = $this->getFixtureQuote();
$quote->setCheckoutMethod(Onepage::METHOD_GUEST);
$quote->getShippingAddress()->setSameAsBilling(0);
$quote->setReservedOrderId(null);
$checkout = $this->getCheckout($quote);
$checkout->place('token');
$order = $checkout->getOrder();
$this->assertNotEmpty($order->getRealOrderId());
}
/**
* @param Quote $quote
* @return Checkout
*/
protected function getCheckout(Quote $quote)
{
return $this->objectManager->create(
Checkout::class,
[
'params' => [
'config' => $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock(),
'quote' => $quote,
]
]
);
}
/**
* Verify that an order placed with an existing customer can re-use the customer addresses.
*
* @magentoDataFixture Magento/Paypal/_files/quote_payment_express_with_customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testReturnFromPaypal()
{
$quote = $this->getFixtureQuote();
$this->checkoutModel = $this->objectManager->create(
Checkout::class,
[
'params' => ['quote' => $quote, 'config' => $this->paypalConfig],
'apiTypeFactory' => $this->apiTypeFactory,
'paypalInfo' => $this->paypalInfo
]
);
$prefix = 'exported';
$exportedBillingAddress = $this->getExportedAddressFixture($quote->getBillingAddress()->getData(), $prefix);
$this->api->expects($this->any())
->method('getExportedBillingAddress')
->willReturn($exportedBillingAddress);
$exportedShippingAddress = $this->getExportedAddressFixture($quote->getShippingAddress()->getData(), $prefix);
$this->api->expects($this->any())
->method('getExportedShippingAddress')
->willReturn($exportedShippingAddress);
$this->paypalInfo->expects($this->once())->method('importToPayment')->with($this->api, $quote->getPayment());
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 1);
$this->checkoutModel->returnFromPaypal('token');
$billingAddress = $quote->getBillingAddress();
$this->assertStringContainsString($prefix, $billingAddress->getFirstname());
$this->assertEquals('note', $billingAddress->getCustomerNote());
$shippingAddress = $quote->getShippingAddress();
$this->assertTrue((bool)$shippingAddress->getSameAsBilling());
$this->assertNull($shippingAddress->getPrefix());
$this->assertNull($shippingAddress->getMiddlename());
$this->assertNull($shippingAddress->getSuffix());
$this->assertTrue($shippingAddress->getShouldIgnoreValidation());
$this->assertStringContainsString('exported', $shippingAddress->getFirstname());
$paymentAdditionalInformation = $quote->getPayment()->getAdditionalInformation();
$this->assertArrayHasKey(Checkout::PAYMENT_INFO_TRANSPORT_SHIPPING_METHOD, $paymentAdditionalInformation);
$this->assertArrayHasKey(Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID, $paymentAdditionalInformation);
$this->assertArrayHasKey(Checkout::PAYMENT_INFO_TRANSPORT_TOKEN, $paymentAdditionalInformation);
$this->assertTrue($quote->getPayment()->hasMethod());
$this->assertTrue($quote->getTotalsCollectedFlag());
}
/**
* The case when handling address data from Paypal button.
* System's address fields are replacing from export Paypal data.
* Billing and Shipping address are the same
*
* @magentoDataFixture Magento/Paypal/_files/quote_payment_express_with_customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testReturnFromPaypalButton()
{
$quote = $this->getFixtureQuote();
$quote->getShippingAddress()->setShippingMethod('');
$this->prepareCheckoutModel($quote);
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 1);
$this->checkoutModel->returnFromPaypal('token');
$shippingAddress = $quote->getShippingAddress();
$billingAddress = $quote->getBillingAddress();
$exportedShippingData = $this->getExportedData()['shipping'];
$this->assertEquals([$exportedShippingData['street']], $shippingAddress->getStreet());
$this->assertEquals($exportedShippingData['firstname'], $shippingAddress->getFirstname());
$this->assertEquals($exportedShippingData['city'], $shippingAddress->getCity());
$this->assertEquals($exportedShippingData['telephone'], $shippingAddress->getTelephone());
$this->assertEquals($exportedShippingData['email'], $shippingAddress->getEmail());
$this->assertEquals('flatrate_flatrate', $shippingAddress->getShippingMethod());
$this->assertEquals([$exportedShippingData['street']], $billingAddress->getStreet());
$this->assertEquals($exportedShippingData['firstname'], $billingAddress->getFirstname());
$this->assertEquals($exportedShippingData['city'], $billingAddress->getCity());
$this->assertEquals($exportedShippingData['telephone'], $billingAddress->getTelephone());
$this->assertEquals($exportedShippingData['email'], $billingAddress->getEmail());
}
/**
* The case when handling address data from Paypal button.
* System's address fields are replacing from export Paypal data.
* Billing and Shipping address are different
*
* @magentoDataFixture Magento/Paypal/_files/quote_payment_express_with_customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testReturnFromPaypalButtonWithReturnBillingAddress()
{
$quote = $this->getFixtureQuote();
$this->paypalConfig->expects($this->exactly(2))
->method('getValue')
->with('requireBillingAddress')
->willReturn(1);
$this->prepareCheckoutModel($quote);
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 1);
$this->checkoutModel->returnFromPaypal('token');
$shippingAddress = $quote->getShippingAddress();
$billingAddress = $quote->getBillingAddress();
$exportedBillingData = $this->getExportedData()['billing'];
$exportedShippingData = $this->getExportedData()['shipping'];
$this->assertEquals([$exportedShippingData['street']], $shippingAddress->getStreet());
$this->assertEquals($exportedShippingData['firstname'], $shippingAddress->getFirstname());
$this->assertEquals($exportedShippingData['city'], $shippingAddress->getCity());
$this->assertEquals($exportedShippingData['telephone'], $shippingAddress->getTelephone());
$this->assertEquals($exportedShippingData['email'], $shippingAddress->getEmail());
$this->assertEquals([$exportedBillingData['street']], $billingAddress->getStreet());
$this->assertEquals($exportedBillingData['firstname'], $billingAddress->getFirstname());
$this->assertEquals($exportedBillingData['city'], $billingAddress->getCity());
$this->assertEquals($exportedBillingData['telephone'], $billingAddress->getTelephone());
$this->assertEquals($exportedBillingData['email'], $billingAddress->getEmail());
}
/**
* The case when handling address data from the checkout.
* System's address fields are not replacing from export PayPal data.
* Billing and Shipping address are the same
*
* @magentoDataFixture Magento/Paypal/_files/quote_payment_express_with_customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testReturnFromPaypalIfCheckout()
{
$prefix = 'exported';
$quote = $this->getFixtureQuote();
$this->prepareCheckoutModel($quote, $prefix);
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 0);
$originalShippingAddress = $quote->getShippingAddress();
$originalBillingAddress = $quote->getBillingAddress();
$this->checkoutModel->returnFromPaypal('token');
$shippingAddress = $quote->getShippingAddress();
$billingAddress = $quote->getBillingAddress();
$this->assertEquals($originalShippingAddress->getStreet(), $shippingAddress->getStreet());
$this->assertEquals($originalShippingAddress->getFirstname(), $shippingAddress->getFirstname());
$this->assertEquals($originalShippingAddress->getCity(), $shippingAddress->getCity());
$this->assertEquals($originalShippingAddress->getTelephone(), $shippingAddress->getTelephone());
$this->assertEquals($originalBillingAddress->getStreet(), $billingAddress->getStreet());
$this->assertEquals($originalBillingAddress->getFirstname(), $billingAddress->getFirstname());
$this->assertEquals($originalBillingAddress->getCity(), $billingAddress->getCity());
$this->assertEquals($originalBillingAddress->getTelephone(), $billingAddress->getTelephone());
}
/**
* The case when handling address data from the checkout.
* System's address fields are replacing billing address from export PayPal data.
* Billing and Shipping address are different
*
* @magentoDataFixture Magento/Paypal/_files/quote_payment_express_with_customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testReturnFromPaypalIfCheckoutWithReturnBillingAddress()
{
$prefix = 'exported';
$quote = $this->getFixtureQuote();
$this->paypalConfig->expects($this->exactly(2))
->method('getValue')
->with('requireBillingAddress')
->willReturn(1);
$this->prepareCheckoutModel($quote, $prefix);
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 0);
$originalShippingAddress = $quote->getShippingAddress();
$this->checkoutModel->returnFromPaypal('token');
$shippingAddress = $quote->getShippingAddress();
$billingAddress = $quote->getBillingAddress();
$exportedBillingData = $this->getExportedData()['billing'];
$this->assertEquals($originalShippingAddress->getStreet(), $shippingAddress->getStreet());
$this->assertEquals($originalShippingAddress->getFirstname(), $shippingAddress->getFirstname());
$this->assertEquals($originalShippingAddress->getCity(), $shippingAddress->getCity());
$this->assertEquals($originalShippingAddress->getTelephone(), $shippingAddress->getTelephone());
$this->assertEquals([$prefix . $exportedBillingData['street']], $billingAddress->getStreet());
$this->assertEquals($prefix . $exportedBillingData['firstname'], $billingAddress->getFirstname());
$this->assertEquals($prefix . $exportedBillingData['city'], $billingAddress->getCity());
$this->assertEquals($prefix . $exportedBillingData['telephone'], $billingAddress->getTelephone());
}
/**
* Test case when customer doesn't have either billing or shipping addresses.
* Customer add virtual product to quote and place order using PayPal Express method.
* After return from PayPal quote billing address have to be updated by PayPal Express address.
*
* @magentoDataFixture Magento/Paypal/_files/virtual_quote_with_empty_billing_address.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoDbIsolation enabled
*
* @return void
*/
public function testReturnFromPayPalForCustomerWithEmptyAddresses(): void
{
$quote = $this->getFixtureQuote();
$this->prepareCheckoutModel($quote);
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 0);
$this->checkoutModel->returnFromPaypal('token');
$billingAddress = $quote->getBillingAddress();
$this->performQuoteAddressAssertions($billingAddress, $this->getExportedData()['billing']);
}
/**
* Test case when customer doesn't have either billing or shipping addresses.
* Customer add virtual product to quote and place order using PayPal Express method.
* Default store country is in PayPal Express allowed specific country list.
*
* @magentoDataFixture Magento/Paypal/_files/virtual_quote_with_empty_billing_address.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store payment/paypal_express/allowspecific 1
* @magentoConfigFixture current_store payment/paypal_express/specificcountry US,GB
* @magentoConfigFixture current_store general/country/default US
*
* @magentoDbIsolation enabled
*
* @return void
*/
public function testPaymentValidationWithAllowedSpecificCountry(): void
{
$quote = $this->getFixtureQuote();
$this->prepareCheckoutModel($quote);
$quote->getPayment()->getMethodInstance()->validate();
}
/**
* Test case when customer doesn't have either billing or shipping addresses.
* Customer add virtual product to quote and place order using PayPal Express method.
* PayPal Express allowed specific country list doesn't contain default store country.
*
* @magentoDataFixture Magento/Paypal/_files/virtual_quote_with_empty_billing_address.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store payment/paypal_express/allowspecific 1
* @magentoConfigFixture current_store payment/paypal_express/specificcountry US,GB
* @magentoConfigFixture current_store general/country/default CA
*
* @magentoDbIsolation enabled
*
* @return void
*/
public function testPaymentValidationWithAllowedSpecificCountryNegative(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage(
'You can\'t use the payment type you selected to make payments to the billing country.'
);
$quote = $this->getFixtureQuote();
$this->prepareCheckoutModel($quote);
$quote->getPayment()->getMethodInstance()->validate();
}
/**
* Performs quote address assertions.
*
* @param Address $address
* @param array $expected
* @return void
*/
private function performQuoteAddressAssertions(Address $address, array $expected): void
{
foreach ($expected as $key => $item) {
$methodName = 'get' . ucfirst($key);
if ($key === 'street') {
$item = [$item];
}
$this->assertEquals($item, $address->$methodName(), 'The "' . $key . '" does not match.');
}
}
/**
* Initialize a checkout model mock.
*
* @param Quote $quote
*/
private function prepareCheckoutModel(Quote $quote, $prefix = '')
{
$this->checkoutModel = $this->objectManager->create(
Checkout::class,
[
'params' => ['quote' => $quote, 'config' => $this->paypalConfig],
'apiTypeFactory' => $this->apiTypeFactory,
'paypalInfo' => $this->paypalInfo
]
);
$exportedBillingAddress = $this->getExportedAddressFixture($this->getExportedData()['billing'], $prefix);
$this->api->method('getExportedBillingAddress')
->willReturn($exportedBillingAddress);
$exportedShippingAddress = $this->getExportedAddressFixture($this->getExportedData()['shipping'], $prefix);
$this->api->method('getExportedShippingAddress')
->willReturn($exportedShippingAddress);
$this->api->method('getShippingRateCode')
->willReturn('flatrate_flatrate Flat Rate - Fixed');
$this->paypalInfo->method('importToPayment')
->with($this->api, $quote->getPayment());
}
/**
* A Paypal response stub.
*
* @return array
*/
private function getExportedData(): array
{
return [
'shipping' => [
'email' => 'customer@example.com',
'firstname' => 'John',
'lastname' => 'Doe',
'country' => 'US',
'region' => 'Colorado',
'region_id' => '13',
'city' => 'Denver',
'street' => '66 Pearl St',
'postcode' => '80203',
'telephone' => '555-555-555',
],
'billing' => [
'email' => 'customer@example.com',
'firstname' => 'Jane',
'lastname' => 'Doe',
'country' => 'US',
'region' => 'Texas',
'region_id' => '13',
'city' => 'Austin',
'street' => '1100 Congress Ave',
'postcode' => '78701',
'telephone' => '555-555-555'
]
];
}
/**
* Verify that guest customer quota has set type of checkout.
*
* @magentoDataFixture Magento/Paypal/_files/quote_payment_express.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testGuestReturnFromPaypal()
{
$quote = $this->getFixtureQuote();
$paypalConfig = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock();
$apiTypeFactory = $this->getMockBuilder(Factory::class)
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$paypalInfo = $this->getMockBuilder(Info::class)
->disableOriginalConstructor()
->setMethods(['importToPayment'])
->getMock();
$checkoutModel = $this->objectManager->create(
Checkout::class,
[
'params' => ['quote' => $quote, 'config' => $paypalConfig],
'apiTypeFactory' => $apiTypeFactory,
'paypalInfo' => $paypalInfo
]
);
$api = $this->getMockBuilder(Nvp::class)
->disableOriginalConstructor()
->setMethods(['call', 'getExportedShippingAddress', 'getExportedBillingAddress'])
->getMock();
$apiTypeFactory->expects($this->any())
->method('create')
->willReturn($api);
$exportedBillingAddress = $this->getExportedAddressFixture($quote->getBillingAddress()->getData());
$api->expects($this->any())
->method('getExportedBillingAddress')
->willReturn($exportedBillingAddress);
$exportedShippingAddress = $this->getExportedAddressFixture($quote->getShippingAddress()->getData());
$api->expects($this->any())
->method('getExportedShippingAddress')
->willReturn($exportedShippingAddress);
$this->addCountryFactory($api);
$data = [
'COUNTRYCODE' => $quote->getShippingAddress()->getCountryId(),
'STATE' => 'unknown'
];
$api->method('call')
->willReturn($data);
$paypalInfo->expects($this->once())
->method('importToPayment')
->with($api, $quote->getPayment());
$quote->getPayment()->setAdditionalInformation(Checkout::PAYMENT_INFO_BUTTON, 1);
$checkoutModel->returnFromPaypal('token');
$this->assertEquals(Onepage::METHOD_GUEST, $quote->getCheckoutMethod());
}
/**
* Prepare fixture for exported address.
*
* @param array $addressData
* @param string $prefix
* @return \Magento\Framework\DataObject
*/
private function getExportedAddressFixture(array $addressData, string $prefix = ''): \Magento\Framework\DataObject
{
$addressDataKeys = [
'country',
'firstname',
'lastname',
'street',
'city',
'telephone',
'postcode',
'region',
'region_id',
'email',
];
$result = [];
foreach ($addressDataKeys as $key) {
if (isset($addressData[$key])) {
$result[$key] = $prefix . $addressData[$key];
}
}
$fixture = new \Magento\Framework\DataObject($result);
$fixture->setExportedKeys($addressDataKeys);
$fixture->setData('note', 'note');
return $fixture;
}
/**
* Gets quote.
*
* @return Quote
*/
private function getFixtureQuote(): Quote
{
/** @var Collection $quoteCollection */
$quoteCollection = $this->objectManager->create(Collection::class);
return $quoteCollection->getLastItem();
}
/**
* Adds countryFactory to a mock.
*
* @param MockObject $api
* @return void
* @throws \ReflectionException
*/
private function addCountryFactory(MockObject $api): void
{
$reflection = new \ReflectionClass($api);
$property = $reflection->getProperty('_countryFactory');
$property->setAccessible(true);
$property->setValue($api, $this->objectManager->get(CountryFactory::class));
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\Hostedpro;
use Magento\Paypal\Model\Hostedpro\Request;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Sales\Model\Order;
/**
* Class RequestTest
* @package Magento\Paypal\Model
*/
class RequestTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Paypal\Model\Hostedpro\Request
*/
private $model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(Request::class);
}
/**
* @covers \Magento\Paypal\Model\Hostedpro\Request::setOrder()
* @magentoDataFixture Magento/Paypal/_files/order_hostedpro.php
*/
public function testSetOrder()
{
$incrementId = '100000001';
/** @var \Magento\Sales\Model\Order $order */
$order = $this->objectManager->create(Order::class);
$order->loadByIncrementId($incrementId);
$this->model->setOrder($order);
$addressData = require(__DIR__ . '/../../_files/address_data.php');
static::assertEquals($incrementId, $this->model->getInvoice());
$this->assertAddress($addressData, 'billing');
$this->assertAddress($addressData);
}
/**
* Assert address details
*
* @param array $address
* @param string $type
*/
protected function assertAddress(array $address, $type = '')
{
$type = !empty($type) ? $type . '_' : '';
static::assertEquals($address['firstname'], $this->model->getData($type.'first_name'));
static::assertEquals($address['lastname'], $this->model->getData($type.'last_name'));
static::assertEquals($address['city'], $this->model->getData($type.'city'));
static::assertEquals($address['region'], $this->model->getData($type.'state'));
static::assertEquals($address['country_id'], $this->model->getData($type.'country'));
static::assertEquals($address['postcode'], $this->model->getData($type.'zip'));
static::assertEquals($address['street'], $this->model->getData($type.'address1'));
}
}
@@ -0,0 +1,127 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model;
use Magento\Framework\DataObject;
use Magento\Paypal\Model\Api\Nvp;
use Magento\Paypal\Model\Config;
use Magento\Paypal\Model\Hostedpro;
use Magento\Paypal\Model\Hostedpro\RequestFactory;
use Magento\Paypal\Model\ProFactory;
use Magento\Sales\Model\Order;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class HostedproTest
* @package Magento\Paypal\Model
*/
class HostedproTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Paypal\Model\Hostedpro
*/
private $model;
/**
* @var \Magento\Paypal\Model\Api\Nvp|\PHPUnit\Framework\MockObject\MockObject
*/
private $api;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->api = $this->getMockBuilder(Nvp::class)
->disableOriginalConstructor()
->setMethods(['call'])
->getMock();
$proFactory = $this->getProFactory();
$this->model = $this->objectManager
->create(Hostedpro::class, [
'proFactory' => $proFactory
]);
}
/**
* @covers \Magento\Paypal\Model\Hostedpro::initialize
* @magentoDataFixture Magento/Paypal/_files/order_hostedpro.php
*/
public function testInitialize()
{
/** @var \Magento\Sales\Model\Order $order */
$order = $this->objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
$payment = $order->getPayment();
$this->model->setInfoInstance($payment);
$this->api->expects(static::once())
->method('call')
->willReturn([
'EMAILLINK' => 'https://securepayments.sandbox.paypal.com/webapps/HostedSoleSolutionApp/webflow/'
]);
$state = $this->objectManager->create(DataObject::class);
$this->model->initialize(Config::PAYMENT_ACTION_AUTH, $state);
static::assertEquals(Order::STATE_PENDING_PAYMENT, $state->getState());
static::assertEquals(Order::STATE_PENDING_PAYMENT, $state->getStatus());
static::assertFalse($state->getIsNotified());
}
/**
* Get mock for config
* @return \PHPUnit\Framework\MockObject\MockObject
*/
protected function getConfig()
{
$config = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->setMethods(['getValue'])
->getMock();
$config->expects(static::any())
->method('getValue')
->with('payment_action')
->willReturn(Config::PAYMENT_ACTION_AUTH);
return $config;
}
/**
* Create mock for Pro factory
* @return \PHPUnit\Framework\MockObject\MockObject
*/
protected function getProFactory()
{
$pro = $this->getMockBuilder(Pro::class)
->disableOriginalConstructor()
->setMethods(['getApi', 'setMethod', 'getConfig', '__wakeup'])
->getMock();
$config = $this->getConfig();
$pro->expects(static::any())
->method('getConfig')
->willReturn($config);
$pro->expects(static::any())
->method('getApi')
->willReturn($this->api);
$proFactory = $this->getMockBuilder(ProFactory::class)
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$proFactory->expects(static::once())
->method('create')
->willReturn($pro);
return $proFactory;
}
}
@@ -0,0 +1,284 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Creditmemo;
use Magento\Sales\Model\Order\Invoice;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea frontend
*/
class IpnTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager;
protected function setUp(): void
{
$this->_objectManager = Bootstrap::getObjectManager();
}
/**
* @param string $currencyCode
* @dataProvider currencyProvider
* @magentoDataFixture Magento/Paypal/_files/order_express.php
* @magentoConfigFixture current_store payment/paypal_direct/active 1
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store paypal/general/merchant_country US
*/
public function testProcessIpnRequestExpressCurrency($currencyCode)
{
$this->_processIpnRequestCurrency($currencyCode);
}
/**
* Refund full order amount by Paypal Express IPN message service.
*
* @magentoDataFixture Magento/Paypal/_files/order_express_with_invoice_and_shipping.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store paypal/general/merchant_country US
*/
public function testProcessIpnRequestFullRefund()
{
$ipnData = require __DIR__ . '/../_files/ipn_refund.php';
$ipnFactory = $this->_objectManager->create(IpnFactory::class);
$ipnModel = $ipnFactory->create(
[
'data' => $ipnData,
'curlFactory' => $this->_createMockedHttpAdapter()
]
);
$ipnModel->processIpnRequest();
$order = $this->_objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
$creditmemoItems = $order->getCreditmemosCollection()->getItems();
$creditmemo = current($creditmemoItems);
$this->assertEquals(Order::STATE_CLOSED, $order->getState()) ;
$this->assertCount(1, $creditmemoItems);
$this->assertEquals(Creditmemo::STATE_REFUNDED, $creditmemo->getState());
$this->assertEquals(10, $order->getSubtotalRefunded());
$this->assertEquals(10, $order->getBaseSubtotalRefunded());
$this->assertEquals(20, $order->getShippingRefunded());
$this->assertEquals(20, $order->getBaseShippingRefunded());
$this->assertEquals(30, $order->getTotalRefunded());
$this->assertEquals(30, $order->getBaseTotalRefunded());
$this->assertEquals(30, $order->getTotalOnlineRefunded());
$this->assertEmpty($order->getTotalOfflineRefunded());
}
/**
* Partial refund of order amount by Paypal Express IPN message service.
*
* @magentoDataFixture Magento/Paypal/_files/order_express_with_invoice_and_shipping.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store paypal/general/merchant_country US
*/
public function testProcessIpnRequestPartialRefund()
{
$ipnData = require __DIR__ . '/../_files/ipn_refund.php';
$refundAmount = -15;
$ipnData['mc_gross'] = $refundAmount;
$ipnFactory = $this->_objectManager->create(IpnFactory::class);
$ipnModel = $ipnFactory->create(
[
'data' => $ipnData,
'curlFactory' => $this->_createMockedHttpAdapter()
]
);
$ipnModel->processIpnRequest();
$order = $this->_objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
$creditmemoItems = $order->getCreditmemosCollection()->getItems();
$comments = $order->load($order->getId())->getAllStatusHistory();
$commentData = reset($comments);
$commentOrigin = sprintf(
'IPN "Refunded". Refund issued by merchant. Registered notification about refunded amount of $%d.00. '.
'Transaction ID: "%s". Credit Memo has not been created. Please create offline Credit Memo.',
abs($refundAmount),
$ipnData['txn_id']
);
$this->assertEquals(Order::STATE_PROCESSING, $order->getState()) ;
$this->assertEmpty(count($creditmemoItems));
$this->assertCount(1, $comments);
$this->assertEquals($commentOrigin, $commentData->getComment());
}
/**
* Refund rest of order amount by Paypal Express IPN message service.
*
* @magentoDataFixture Magento/Paypal/_files/order_express_with_invoice_and_shipping.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store paypal/general/merchant_country US
*/
public function testProcessIpnRequestRestRefund()
{
$ipnData = require __DIR__ . '/../_files/ipn_refund.php';
$ipnFactory = $this->_objectManager->create(IpnFactory::class);
$ipnModel = $ipnFactory->create(
[
'data' => $ipnData,
'curlFactory' => $this->_createMockedHttpAdapter()
]
);
$ipnModel->processIpnRequest();
$order = $this->_objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
$creditmemoItems = $order->getCreditmemosCollection()->getItems();
$this->assertEquals(Order::STATE_CLOSED, $order->getState()) ;
$this->assertCount(1, $creditmemoItems);
$this->assertEquals(10, $order->getSubtotalRefunded());
$this->assertEquals(10, $order->getBaseSubtotalRefunded());
$this->assertEquals(20, $order->getShippingRefunded());
$this->assertEquals(20, $order->getBaseShippingRefunded());
$this->assertEquals(30, $order->getTotalRefunded());
$this->assertEquals(30, $order->getBaseTotalRefunded());
$this->assertEquals(30, $order->getTotalOnlineRefunded());
$this->assertEmpty($order->getTotalOfflineRefunded());
}
/**
* Verifies canceling an order that was in payment review state by PayPal Express IPN message service.
*
* @magentoDataFixture Magento/Paypal/_files/order_express_with_invoice_payment_review.php
* @magentoConfigFixture current_store payment/paypal_express/active 1
* @magentoConfigFixture current_store paypal/general/merchant_country US
*/
public function testProcessIpnRequestWithFailedStatus()
{
$ipnData = require __DIR__ . '/../_files/ipn_failed.php';
/** @var IpnFactory $ipnFactory */
$ipnFactory = $this->_objectManager->create(IpnFactory::class);
$ipnModel = $ipnFactory->create(
[
'data' => $ipnData,
'curlFactory' => $this->_createMockedHttpAdapter()
]
);
$ipnModel->processIpnRequest();
$order = $this->getOrder($ipnData['invoice']);
$invoiceItems = $order->getInvoiceCollection()
->getItems();
/** @var Invoice $invoice */
$invoice = array_pop($invoiceItems);
$invoice->getState();
$this->assertEquals(Order::STATE_CANCELED, $order->getState());
$this->assertEquals(Invoice::STATE_CANCELED, $invoice->getState());
}
/**
* Test processIpnRequest() currency check for paypal_express and paypal_standard payment methods
*
* @param string $currencyCode
*/
protected function _processIpnRequestCurrency($currencyCode)
{
$ipnData = require __DIR__ . '/../_files/ipn.php';
$ipnData['mc_currency'] = $currencyCode;
/** @var $ipnFactory \Magento\Paypal\Model\IpnFactory */
$ipnFactory = $this->_objectManager->create(\Magento\Paypal\Model\IpnFactory::class);
$model = $ipnFactory->create(['data' => $ipnData, 'curlFactory' => $this->_createMockedHttpAdapter()]);
$model->processIpnRequest();
$order = $this->_objectManager->create(\Magento\Sales\Model\Order::class);
$order->loadByIncrementId('100000001');
$this->_assertOrder($order, $currencyCode);
}
/**
* Perform order state and status assertions depending on currency code
*
* @param \Magento\Sales\Model\Order $order
* @param string $currencyCode
*/
protected function _assertOrder($order, $currencyCode)
{
if ($currencyCode == 'USD') {
$this->assertEquals('complete', $order->getState());
$this->assertEquals('complete', $order->getStatus());
} else {
$this->assertEquals('payment_review', $order->getState());
$this->assertEquals('fraud', $order->getStatus());
}
}
/**
* Data provider for currency check tests
*
* @static
* @return array
*/
public static function currencyProvider()
{
return [['USD'], ['EUR']];
}
/**
* Mocked HTTP adapter to get VERIFIED PayPal IPN postback result
*
* @return \Magento\Framework\HTTP\Adapter\Curl
*/
protected function _createMockedHttpAdapter()
{
$factory = $this->createPartialMock(\Magento\Framework\HTTP\Adapter\CurlFactory::class, ['create']);
$adapter = $this->createPartialMock(\Magento\Framework\HTTP\Adapter\Curl::class, ['read', 'write']);
$adapter->expects($this->once())->method('read')->with()->willReturn("\nVERIFIED");
$adapter->expects($this->once())->method('write');
$factory->expects($this->once())->method('create')->with()->willReturn($adapter);
return $factory;
}
/**
* Get stored order.
*
* @param string $incrementId
* @return OrderInterface
*/
private function getOrder(string $incrementId)
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(OrderInterface::INCREMENT_ID, $incrementId)
->create();
$orderRepository = $this->_objectManager->get(OrderRepositoryInterface::class);
$orders = $orderRepository->getList($searchCriteria)
->getItems();
/** @var OrderInterface $order */
return array_pop($orders);
}
}
@@ -0,0 +1,245 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Paypal\Model;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\App\MutableScopeConfig;
use Magento\Store\Model\ScopeInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class PayLaterConfigTest extends TestCase
{
/**
* @dataProvider getStyleDataProvider
* @magentoAppIsolation enabled
* @covers \Magento\Paypal\Model\PayLaterConfig::getSectionConfig()
*/
public function testGetStyleConfig($systemConfig, $expectedConfig)
{
$this->setConfig($systemConfig);
/** @var PayLaterConfig $config */
$config = Bootstrap::getObjectManager()->get(PayLaterConfig::class);
$this->assertEquals($expectedConfig, $config->getSectionConfig('test1', PayLaterConfig::CONFIG_KEY_STYLE));
}
/**
* @return array
*/
public function getStyleDataProvider()
{
return [
[
'systemConfig' => [
'payment/paypal_paylater/test1page_stylelayout' => 'flex',
'payment/paypal_paylater/test1page_ratio' => '20x1',
'payment/paypal_paylater/test1page_color' => 'blue'
],
'expectedConfig' => [
'data-pp-style-layout' => 'flex',
'data-pp-style-logo-type' => null,
'data-pp-style-logo-position' => null,
'data-pp-style-text-color' => null,
'data-pp-style-text-size' => null,
'data-pp-style-color' => 'blue',
'data-pp-style-ratio' => '20x1',
]
],
[
'systemConfig' => [
'payment/paypal_paylater/test1page_stylelayout' => 'text',
'payment/paypal_paylater/test1page_logotype' => 'primary',
'payment/paypal_paylater/test1page_logoposition' => 'left',
'payment/paypal_paylater/test1page_textcolor' => 'white',
'payment/paypal_paylater/test1page_textsize' => '10'
],
'expectedConfig' => [
'data-pp-style-layout' => 'text',
'data-pp-style-logo-type' => 'primary',
'data-pp-style-logo-position' => 'left',
'data-pp-style-text-color' => 'white',
'data-pp-style-text-size' => '10',
'data-pp-style-color' => null,
'data-pp-style-ratio' => null,
]
],
];
}
/**
* @dataProvider getPositionDataProvider
* @magentoAppIsolation enabled
* @covers \Magento\Paypal\Model\PayLaterConfig::getSectionConfig()
*/
public function testGetPositionConfig($systemConfig, $expectedConfig)
{
$this->setConfig($systemConfig);
/** @var PayLaterConfig $config */
$config = Bootstrap::getObjectManager()->get(PayLaterConfig::class);
$this->assertEquals($expectedConfig, $config->getSectionConfig('test1', PayLaterConfig::CONFIG_KEY_POSITION));
}
/**
* @return array[]
*/
public function getPositionDataProvider()
{
return [
[
'systemConfig' => [
'payment/paypal_paylater/test1page_position' => 'header',
],
'expectedConfig' => 'header'
],
[
'systemConfig' => [
'payment/paypal_paylater/test1page_position' => 'sidebar',
],
'expectedConfig' => 'sidebar'
],
[
'systemConfig' => [
'payment/paypal_paylater/test2page_position' => 'sidebar',
],
'expectedConfig' => ''
],
];
}
/**
* @magentoAppIsolation enabled
* @dataProvider isEnabledDataProvider
*/
public function testIsEnabled($systemConfig, $expected)
{
$systemConfig = array_replace([
'payment/paypal_paylater/experience_active' => 1,
'payment/paypal_paylater/enabled' => 1,
'payment/paypal_paylater/test1page_display' => 1
], $systemConfig);
$this->setConfig($systemConfig);
/** @var PayLaterConfig $config */
$config = Bootstrap::getObjectManager()->get(PayLaterConfig::class);
$this->assertEquals($expected, $config->isEnabled('test1'));
}
/**
* @return array[]
*/
public function isEnabledDataProvider()
{
$paymentPath = 'payment/%s/active';
return [
'PayPal Express' => [
[sprintf($paymentPath, Config::METHOD_EXPRESS) => 1],
true
],
'PayPal Express - Disabled' => [
[sprintf($paymentPath, Config::METHOD_EXPRESS) => 0],
false
],
'PayPal Express - Disabled funding' => [
[
sprintf($paymentPath, Config::METHOD_EXPRESS) => 1,
'paypal/style/disable_funding_options' => 'CARD,ELV'
],
true
],
'PayPal Express - Disabled funding CREDIT' => [
[
sprintf($paymentPath, Config::METHOD_EXPRESS) => 1,
'paypal/style/disable_funding_options' => 'CREDIT,CARD,ELV'
],
false
],
'PayPal Standard Bml' => [
[
sprintf($paymentPath, Config::METHOD_WPS_EXPRESS) => 1,
sprintf($paymentPath, Config::METHOD_WPS_BML) => 1,
],
true
],
'PayPal Standard Bml - Disabled' => [
[
sprintf($paymentPath, Config::METHOD_WPS_EXPRESS) => 0,
sprintf($paymentPath, Config::METHOD_WPS_BML) => 1,
],
false
],
'PayPal Standard Bml - Disabled PP Credit' => [
[
sprintf($paymentPath, Config::METHOD_WPS_EXPRESS) => 1,
sprintf($paymentPath, Config::METHOD_WPS_BML) => 0,
],
false
],
'PayPal Bill Me Later - Express Checkout (Payflow Edition)' => [
[
sprintf($paymentPath, Config::METHOD_WPP_PE_EXPRESS) => 1,
sprintf($paymentPath, Config::METHOD_WPP_PE_BML) => 1,
],
true
],
'PayPal Bill Me Later - Express Checkout (Payflow Edition) - Disabled' => [
[
sprintf($paymentPath, Config::METHOD_WPP_PE_EXPRESS) => 0,
sprintf($paymentPath, Config::METHOD_WPP_PE_BML) => 1,
],
false
],
'PayPal Bill Me Later - Express Checkout (Payflow Edition) - Disabled PP Credit' => [
[
sprintf($paymentPath, Config::METHOD_WPP_PE_EXPRESS) => 1,
sprintf($paymentPath, Config::METHOD_WPP_PE_BML) => 0,
],
false
],
'PayLater disabled' => [
[
sprintf($paymentPath, Config::METHOD_EXPRESS) => 1,
'payment/paypal_paylater/enabled' => 0
],
false
],
'"Display" for page disabled' => [
[
sprintf($paymentPath, Config::METHOD_EXPRESS) => 1,
'payment/paypal_paylater/test1page_display' => 0
],
false
],
'PayLater experience not active' => [
[
sprintf($paymentPath, Config::METHOD_EXPRESS) => 1,
'payment/paypal_paylater/experience_active' => 0
],
false
],
];
}
/**
* Set system configuration value for test
*
* @param $config
*/
private function setConfig($config)
{
$objectManager = Bootstrap::getObjectManager();
/** @var $scopeConfig MutableScopeConfig */
$scopeConfig = $objectManager->get(MutableScopeConfigInterface::class);
foreach ($config as $path => $value) {
$scopeConfig->setValue($path, $value, ScopeInterface::SCOPE_STORE);
}
}
}
@@ -0,0 +1,226 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Paypal\Model\Payflow\Service\Request;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\DataObject;
use Magento\Framework\Math\Random;
use Magento\Paypal\Model\Payflow\Service\Gateway;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject as MockObject;
/**
* @magentoAppIsolation enabled
* @magentoDbIsolation disabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SecureTokenTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var SecureToken
*/
private $service;
/**
* @var Gateway|MockObject
*/
private $gateway;
/**
* @var CartRepositoryInterface
*/
private $quoteRepository;
/**
* @var Random|MockObject;
*/
private $mathRandom;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->gateway = $this->getMockBuilder(Gateway::class)
->disableOriginalConstructor()
->getMock();
$this->quoteRepository = $this->objectManager->get(CartRepositoryInterface::class);
$this->objectManager->addSharedInstance($this->gateway, Gateway::class);
$this->mathRandom = $this->getMockBuilder(Random::class)
->getMock();
$this->service = $this->objectManager->create(
SecureToken::class,
[
'mathRandom' => $this->mathRandom,
]
);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->objectManager->removeSharedInstance(Gateway::class);
}
/**
* Checks a case when secure token can be obtained with credentials for the default scope.
*
* @magentoDataFixture Magento/Paypal/_files/quote_payflowpro.php
* @magentoDataFixture Magento/Paypal/Fixtures/default_payment_configuration.php
* @magentoAppArea adminhtml
* @return void
*/
public function testRequestToken(): void
{
$quote = $this->getQuote('100000015');
$quote->setStoreId(null);
$this->execute($quote, 'def_partner', 'def_vendor', 'def_user', 'def_pwd');
}
/**
* Checks a case when secure token can be obtained with credentials specified per store.
*
* @magentoDataFixture Magento/Paypal/_files/quote_payflowpro.php
* @magentoDataFixture Magento/Paypal/Fixtures/store_payment_configuration.php
* @magentoAppArea adminhtml
* @return void
*/
public function testRequestTokenWithStoreConfiguration(): void
{
$quote = $this->getQuote('100000015');
$store = $this->getStore('test');
$quote->setStoreId($store->getId());
$this->execute($quote, 'store_partner', 'store_vendor', 'store_user', 'store_pwd');
}
/**
* Checks a case when secure token can be obtained with credentials specified per website.
*
* @magentoDataFixture Magento/Paypal/_files/quote_payflowpro.php
* @magentoDataFixture Magento/Paypal/Fixtures/website_payment_configuration.php
* @magentoAppArea adminhtml
* @return void
*/
public function testRequestTokenWithWebsiteConfiguration(): void
{
$quote = $this->getQuote('100000015');
$store = $this->getStore('fixture_second_store');
$quote->setStoreId($store->getId());
$this->execute($quote, 'website_partner', 'website_vendor', 'website_user', 'website_pwd');
}
/**
* Retrieves secure token and perform test assertions.
*
* @param Quote $quote
* @param string $expPartner
* @param string $expVendor
* @param string $expUser
* @param string $expPwd
* @return void
*/
private function execute(
Quote $quote,
string $expPartner,
string $expVendor,
string $expUser,
string $expPwd
): void {
$secureTokenId = '31f2a7c8d257c70b1c9eb9051b90e0';
$token = '80IgSbabyj0CtBDWHZZeQN3';
$this->mathRandom->method('getUniqueHash')
->willReturn($secureTokenId);
$response = new DataObject([
'result' => '0',
'respmsg' => 'Approved',
'securetoken' => $token,
'securetokenid' => $secureTokenId,
'result_code' => '0',
]);
$self = $this;
$this->gateway->method('postRequest')
/** @var DataObject $request */
->with(self::callback(function ($request) use ($self, $expPartner, $expVendor, $expUser, $expPwd) {
$self->performAssertion($expPartner, $request->getPartner(), '{Partner}');
$self->performAssertion($expVendor, $request->getVendor(), '{Vendor}');
$self->performAssertion($expUser, $request->getUser(), '{User}');
$self->performAssertion($expPwd, $request->getPwd(), '{Password}');
return true;
}))
->willReturn($response);
$response = $this->service->requestToken($quote);
$this->performAssertion($token, $response->getData('securetoken'), '{Secure Token}');
}
/**
* Perform assertions test assertions.
*
* @param string $expected
* @param string $actual
* @param string $property
* @return void
*/
private function performAssertion(string $expected, string $actual, string $property): void
{
self::assertEquals($expected, $actual, "$property should match.");
}
/**
* Loads quote by order increment id.
*
* @param string $orderIncrementId
* @return Quote
*/
private function getQuote(string $orderIncrementId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $orderIncrementId)
->create();
$items = $this->quoteRepository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
/**
* Loads store by provided code.
*
* @param string $code
* @return StoreInterface
*/
private function getStore(string $code): StoreInterface
{
/** @var StoreRepositoryInterface $storeRepository */
$storeRepository = $this->objectManager->get(StoreRepositoryInterface::class);
return $storeRepository->get($code);
}
}
@@ -0,0 +1,167 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Paypal\Model\Payflow;
use Magento\Checkout\Api\PaymentInformationManagementInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Paypal\Model\Config;
use Magento\Paypal\Model\Payflowpro;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Sales\Api\Data\TransactionInterface;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\TransactionRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class TransparentTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var PaymentInformationManagementInterface
*/
private $management;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->management = $this->objectManager->get(PaymentInformationManagementInterface::class);
}
/**
* Checks a case when order should be placed in "Suspected Fraud" status based on account verification.
*
* @magentoDataFixture Magento/Checkout/_files/quote_with_shipping_method.php
* @magentoConfigFixture current_store payment/payflowpro/active 1
* @magentoConfigFixture current_store payment/payflowpro/payment_action Authorization
* @magentoConfigFixture current_store payment/payflowpro/fmf 1
*/
public function testPlaceOrderSuspectedFraud(): void
{
$quote = $this->getQuote('test_order_1');
$this->addFraudPayment($quote);
$payment = $quote->getPayment();
$pnref = $payment->getAdditionalInformation(Payflowpro::PNREF);
$orderId = (int)$this->management->savePaymentInformationAndPlaceOrder($quote->getId(), $payment);
self::assertNotEmpty($orderId);
/** @var OrderRepositoryInterface $orderManagement */
$orderManagement = $this->objectManager->get(OrderRepositoryInterface::class);
$order = $orderManagement->get($orderId);
self::assertEquals(Order::STATUS_FRAUD, $order->getStatus());
self::assertEquals(Order::STATE_PAYMENT_REVIEW, $order->getState());
$transactions = $this->getPaymentTransactionList((int) $orderId);
self::assertCount(1, $transactions, 'Only one transaction should be present.');
/** @var TransactionInterface $transaction */
$transaction = array_pop($transactions);
self::assertEquals(
$pnref,
$transaction->getTxnId(),
'Authorization transaction id should be equal to PNREF.'
);
self::assertStringContainsString(
'Order is suspended as an account verification transaction is suspected to be fraudulent.',
$this->getOrderComment($orderId)
);
}
/**
* Retrieves quote by provided order ID.
*
* @param string $reservedOrderId
* @return CartInterface
*/
private function getQuote(string $reservedOrderId): CartInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->objectManager->get(CartRepositoryInterface::class);
$items = $quoteRepository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
/**
* Sets payment with fraud to quote.
*
* @return void
*/
private function addFraudPayment(CartInterface $quote): void
{
$payment = $quote->getPayment();
$payment->setMethod(Config::METHOD_PAYFLOWPRO);
$payment->setAdditionalInformation(Payflowpro::PNREF, 'A90A0D1B361D');
$payment->setAdditionalInformation('result_code', Payflowpro::RESPONSE_CODE_FRAUDSERVICE_FILTER);
$payment->setCcType('VI');
$payment->setCcLast4('1111');
$payment->setCcExpMonth('3');
$payment->setCcExpYear('2025');
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->objectManager->get(CartRepositoryInterface::class);
$quoteRepository->save($quote);
}
/**
* Get list of order transactions.
*
* @param int $orderId
* @return TransactionInterface[]
*/
private function getPaymentTransactionList(int $orderId): array
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('order_id', $orderId)
->create();
/** @var TransactionRepositoryInterface $transactionRepository */
$transactionRepository = $this->objectManager->get(TransactionRepositoryInterface::class);
return $transactionRepository->getList($searchCriteria)
->getItems();
}
/**
* Returns order comment.
*
* @param int $orderId
* @return string
*/
private function getOrderComment(int $orderId): string
{
/** @var OrderManagementInterface $orderManagement */
$orderManagement = $this->objectManager->get(OrderManagementInterface::class);
$comments = $orderManagement->getCommentsList($orderId)->getItems();
$comment = reset($comments);
return $comment ? $comment->getComment() : '';
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model;
use Magento\Framework\DataObject;
use Magento\Framework\HTTP\LaminasClient;
use Magento\Framework\HTTP\LaminasClientFactory;
use Magento\Framework\Math\Random;
use Magento\Framework\ObjectManagerInterface;
use Magento\Payment\Model\Method\Logger;
use Magento\Paypal\Model\Payflow\Service\Gateway;
use Magento\Sales\Model\Order;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class PayflowproTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
protected $_objectManager;
/**
* @var Payflowpro
*/
protected $_model;
/**
* @var LaminasClient
*/
protected $_httpClientMock;
/**
* @var Gateway
*/
protected $gatewayMock;
protected function setUp(): void
{
$this->_objectManager = Bootstrap::getObjectManager();
$httpClientFactoryMock = $this->getMockBuilder(LaminasClientFactory::class)
->setMethods(['create'])
->disableOriginalConstructor()
->getMock();
$this->_httpClientMock = $this->getMockBuilder(LaminasClient::class)->setMethods([])
->disableOriginalConstructor()->getMock();
$this->_httpClientMock->expects($this->any())->method('setUri')->willReturnSelf();
$this->_httpClientMock->expects($this->any())->method('setOptions')->willReturnSelf();
$this->_httpClientMock->expects($this->any())->method('setMethod')->willReturnSelf();
$this->_httpClientMock->expects($this->any())->method('setParameterPost')->willReturnSelf();
$this->_httpClientMock->expects($this->any())->method('setHeaders')->willReturnSelf();
$this->_httpClientMock->expects($this->any())->method('setUrlEncodeBody')->willReturnSelf();
$httpClientFactoryMock->expects($this->any())->method('create')
->willReturn($this->_httpClientMock);
$mathRandomMock = $this->createMock(Random::class);
$loggerMock = $this->createMock(Logger::class);
$this->gatewayMock =$this->_objectManager->create(
Gateway::class,
[
'httpClientFactory' => $httpClientFactoryMock,
'mathRandom' => $mathRandomMock,
'logger' => $loggerMock,
]
);
$this->_model = $this->_objectManager->create(
Payflowpro::class,
['gateway' => $this->gatewayMock]
);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_paid_with_payflowpro.php
*/
public function testReviewPaymentNullResponce()
{
/** @var Order $order */
$order = $this->_objectManager->create(Order::class);
$order->loadByIncrementId('100000001');
$this->_httpClientMock->expects($this->any())->method('send')
->willReturn(new DataObject(['body' => 'RESULTval=12&val2=34']));
$expectedResult = ['resultval' => '12', 'val2' => '34', 'result_code' => null];
$this->assertEquals($expectedResult, $this->_model->acceptPayment($order->getPayment()));
}
}
@@ -0,0 +1,268 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Paypal\Model;
use Magento\Framework\Api\AttributeValueFactory;
use Magento\Framework\Api\ExtensionAttributesFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Framework\Model\Context;
use Magento\Framework\Module\ModuleListInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Payment\Gateway\Command\CommandException;
use Magento\Payment\Helper\Data;
use Magento\Payment\Model\InfoInterface;
use Magento\Payment\Model\Method\ConfigInterfaceFactory;
use Magento\Payment\Model\Method\Logger;
use Magento\Paypal\Model\Payflow\Service\Gateway;
use Magento\Paypal\Model\Payflow\Service\Response\Handler\HandlerInterface;
use Magento\Quote\Api\Data\PaymentMethodInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PayflowproVoidTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
public function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* Tests PayflowPro payment void operation.
*
* @magentoDataFixture Magento/Paypal/_files/order_payflowpro.php
* @magentoConfigFixture current_store payment/payflowpro/active 1
*/
public function testPaymentVoid(): void
{
$response = new DataObject(
[
'result' => '0',
'pnref' => 'V19A3D27B61E',
'respmsg' => 'Approved',
'authcode' => '510PNI',
'hostcode' => 'A',
'request_id' => 'f930d3dc6824c1f7230c5529dc37ae5e',
'result_code' => '0',
]
);
$order = $this->getOrder();
$payment = $order->getPayment();
$instance = $this->getPaymentMethodInstance($response);
$payment->setMethodInstance($instance);
$this->assertTrue($order->canVoidPayment());
$payment->void(new DataObject());
/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $this->objectManager->get(OrderRepositoryInterface::class);
$orderRepository->save($order);
$order = $this->getOrderByIncrementId('100000001');
$this->assertFalse($order->canVoidPayment());
}
/**
* Tests canceling order with acceptable void transaction results.
*
* @param DataObject $response
* @magentoDataFixture Magento/Paypal/_files/order_payflowpro.php
* @magentoConfigFixture current_store payment/payflowpro/active 1
* @dataProvider orderCancelSuccessDataProvider
*/
public function testOrderCancelSuccess(DataObject $response): void
{
$order = $this->getOrder();
$payment = $order->getPayment();
$instance = $this->getPaymentMethodInstance($response);
$payment->setMethodInstance($instance);
$order->cancel();
$this->assertEquals(Order::STATE_CANCELED, $order->getState());
$this->assertEquals(Order::STATE_CANCELED, $order->getStatus());
}
/**
* @return array
*/
public function orderCancelSuccessDataProvider(): array
{
return [
'Authorization has expired' => [
new DataObject(
[
'respmsg' => 'Declined: 10601-Authorization has expired.',
'result_code' => '10601',
]
)
],
'Authorization voided successfully' => [
new DataObject(
[
'respmsg' => 'Approved',
'result_code' => '0',
]
)
]
];
}
/**
* Tests canceling the order when got an error during transaction voiding.
*
* @magentoDataFixture Magento/Paypal/_files/order_payflowpro.php
* @magentoConfigFixture current_store payment/payflowpro/active 1
*/
public function testOrderCancelWithVoidError(): void
{
$response = new DataObject(
[
'respmsg' => 'Declined: for some reason other then expired authorization',
'result_code' => '111',
]
);
$order = $this->getOrder();
$payment = $order->getPayment();
$instance = $this->getPaymentMethodInstance($response);
$payment->setMethodInstance($instance);
$this->expectException(CommandException::class);
$order->cancel();
}
/**
* Returns prepared order.
*
* @return Order
* @throws \ReflectionException
*/
private function getOrder(): Order
{
/** @var $order Order */
$order = $this->getOrderByIncrementId('100000001');
$orderItem = $this->createMock(Item::class);
$orderItem->method('getQtyToInvoice')
->willReturn(true);
$order->setItems([$orderItem]);
$payment = $order->getPayment();
$canVoidLookupProperty = new \ReflectionProperty(get_class($payment), '_canVoidLookup');
$canVoidLookupProperty->setAccessible(true);
$canVoidLookupProperty->setValue($payment, true);
return $order;
}
/**
* Returns payment method instance.
*
* @param DataObject $response
* @return PaymentMethodInterface
* @throws \ReflectionException
*/
private function getPaymentMethodInstance(DataObject $response): PaymentMethodInterface
{
$gatewayMock = $this->createMock(Gateway::class);
$gatewayMock->expects($this->once())
->method('postRequest')
->willReturn($response);
$configMock = $this->createMock(PayflowConfig::class);
$configFactoryMock = $this->createPartialMock(
ConfigInterfaceFactory::class,
['create']
);
$configFactoryMock->expects($this->once())
->method('create')
->willReturn($configMock);
$configMock->expects($this->any())
->method('getValue')
->willReturnMap(
[
['use_proxy', false],
['sandbox_flag', '1'],
['transaction_url_test_mode', 'https://test_transaction_url']
]
);
/** @var Payflowpro|MockObject $instance */
$instance = $this->getMockBuilder(Payflowpro::class)
->setMethods(['setStore', 'getInfoInstance'])
->setConstructorArgs(
[
$this->objectManager->get(Context::class),
$this->objectManager->get(Registry::class),
$this->objectManager->get(ExtensionAttributesFactory::class),
$this->objectManager->get(AttributeValueFactory::class),
$this->objectManager->get(Data::class),
$this->objectManager->get(ScopeConfigInterface::class),
$this->objectManager->get(Logger::class),
$this->objectManager->get(ModuleListInterface::class),
$this->objectManager->get(TimezoneInterface::class),
$this->objectManager->get(StoreManagerInterface::class),
$configFactoryMock,
$gatewayMock,
$this->objectManager->get(HandlerInterface::class),
null,
null,
[]
]
)
->getMock();
$instance->expects($this->once())
->method('setStore')
->willReturnSelf();
$paymentInfoInstance = $this->createMock(InfoInterface::class);
$instance->method('getInfoInstance')
->willReturn($paymentInfoInstance);
return $instance;
}
/**
* Get stored order.
*
* @param string $incrementId
* @return OrderInterface
*/
private function getOrderByIncrementId(string $incrementId): OrderInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(OrderInterface::INCREMENT_ID, $incrementId)
->create();
$orderRepository = $this->objectManager->get(OrderRepositoryInterface::class);
$orders = $orderRepository->getList($searchCriteria)
->getItems();
/** @var OrderInterface $order */
return array_pop($orders);
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\Payment\Method\Billing;
use Magento\Quote\Api\Data\PaymentInterface;
use Magento\TestFramework\Helper\Bootstrap;
class AbstractAgreementTest extends \Magento\TestFramework\Indexer\TestCase
{
/** @var \Magento\Paypal\Model\Method\Agreement */
protected $_model;
public static function setUpBeforeClass(): void
{
$db = Bootstrap::getInstance()->getBootstrap()
->getApplication()
->getDbInstance();
if (!$db->isDbDumpExists()) {
throw new \LogicException('DB dump does not exist.');
}
$db->restoreFromDbDump();
parent::setUpBeforeClass();
}
protected function setUp(): void
{
$config = $this->getMockBuilder(\Magento\Paypal\Model\Config::class)->disableOriginalConstructor()->getMock();
$config->expects($this->any())->method('isMethodAvailable')->willReturn(true);
$proMock = $this->getMockBuilder(\Magento\Paypal\Model\Pro::class)->disableOriginalConstructor()->getMock();
$proMock->expects($this->any())->method('getConfig')->willReturn($config);
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Paypal\Model\Method\Agreement::class,
['data' => [$proMock]]
);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
* @magentoDataFixture Magento/Paypal/_files/billing_agreement.php
*/
public function testIsActive()
{
$quote = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Quote\Model\ResourceModel\Quote\Collection::class
)->getFirstItem();
$this->assertTrue($this->_model->isAvailable($quote));
}
/**
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
* @magentoDataFixture Magento/Paypal/_files/billing_agreement.php
*/
public function testAssignData()
{
/** @var \Magento\Quote\Model\ResourceModel\Quote\Collection $collection */
$collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Quote\Model\ResourceModel\Quote\Collection::class
);
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $collection->getFirstItem();
/** @var \Magento\Payment\Model\Info $info */
$info = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Payment\Model\Info::class
)->setQuote(
$quote
);
$this->_model->setData('info_instance', $info);
$billingAgreement = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection::class
)->getFirstItem();
$data = new \Magento\Framework\DataObject(
[
PaymentInterface::KEY_ADDITIONAL_DATA => [
AbstractAgreement::TRANSPORT_BILLING_AGREEMENT_ID => $billingAgreement->getId()
]
]
);
$this->_model->assignData($data);
$this->assertEquals(
'REF-ID-TEST-678',
$info->getAdditionalInformation(AbstractAgreement::PAYMENT_INFO_REFERENCE_ID)
);
}
/**
* teardown
*/
protected function tearDown(): void
{
parent::tearDown();
}
}
@@ -0,0 +1,111 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\Report;
class SettlementTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDbIsolation enabled
*/
public function testFetchAndSave()
{
/** @var $model \Magento\Paypal\Model\Report\Settlement; */
$model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Paypal\Model\Report\Settlement::class
);
$connection = $this->createPartialMock(\Magento\Framework\Filesystem\Io\Sftp::class, ['rawls', 'read']);
$filename = 'STL-00000000.00.abc.CSV';
$connection->expects($this->once())->method('rawls')->willReturn([$filename => []]);
$connection->expects($this->once())->method('read')->with($filename, $this->anything());
$model->fetchAndSave($connection);
}
/**
* @param array $config
* @dataProvider createConnectionExceptionDataProvider
*/
public function testCreateConnectionException($config)
{
$this->expectException(\InvalidArgumentException::class);
\Magento\Paypal\Model\Report\Settlement::createConnection($config);
}
/**
* @param array $automaticMode
* @param array $expectedResult
*
* @dataProvider createAutomaticModeDataProvider
*
* @magentoConfigFixture default_store paypal/fetch_reports/active 0
* @magentoConfigFixture default_store paypal/fetch_reports/ftp_ip 192.168.0.1
* @magentoConfigFixture current_store paypal/fetch_reports/active 1
* @magentoConfigFixture current_store paypal/fetch_reports/ftp_ip 127.0.0.1
* @magentoConfigFixture current_store paypal/fetch_reports/ftp_path /tmp
* @magentoConfigFixture current_store paypal/fetch_reports/ftp_login login
* @magentoConfigFixture current_store paypal/fetch_reports/ftp_password password
* @magentoConfigFixture current_store paypal/fetch_reports/ftp_sandbox 0
* @magentoDbIsolation enabled
*/
public function testGetSftpCredentials($automaticMode, $expectedResult)
{
/** @var $model \Magento\Paypal\Model\Report\Settlement; */
$model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Paypal\Model\Report\Settlement::class
);
$result = $model->getSftpCredentials($automaticMode);
$this->assertEquals($expectedResult, $result);
}
/**
* @return array
*/
public function createConnectionExceptionDataProvider()
{
return [
[[]],
[['username' => 'test', 'password' => 'test', 'path' => '/']],
[['hostname' => 'example.com', 'password' => 'test', 'path' => '/']],
[['hostname' => 'example.com', 'username' => 'test', 'path' => '/']],
[['hostname' => 'example.com', 'username' => 'test', 'password' => 'test']]
];
}
/**
* @return array
*/
public function createAutomaticModeDataProvider()
{
return [
[
true,
[
[
'hostname' => '127.0.0.1',
'path' => '/tmp',
'username' => 'login',
'password' => 'password',
'sandbox' => '0'
]
]
],
[
false,
[
[
'hostname' => '127.0.0.1',
'path' => '/tmp',
'username' => 'login',
'password' => 'password',
'sandbox' => '0'
]
]
],
];
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Model\ResourceModel\Billing\Agreement;
use Magento\TestFramework\Helper\Bootstrap;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Paypal/_files/billing_agreement.php
*/
public function testAddCustomerDetails()
{
/** @var \Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection $billingAgreementCollection */
$billingAgreementCollection = Bootstrap::getObjectManager()->create(
\Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection::class
);
$billingAgreementCollection->addCustomerDetails();
$this->assertEquals(1, $billingAgreementCollection->count(), "Invalid collection items quantity.");
/** @var \Magento\Paypal\Model\Billing\Agreement $billingAgreement */
$billingAgreement = $billingAgreementCollection->getFirstItem();
$expectedData = [
'customer_id' => 1,
'method_code' => 'paypal_express',
'reference_id' => 'REF-ID-TEST-678',
'status' => 'active',
'store_id' => 1,
'agreement_label' => 'TEST',
'customer_email' => 'customer@example.com',
'customer_firstname' => 'John',
'customer_lastname' => 'Smith',
];
foreach ($expectedData as $field => $expectedValue) {
$this->assertEquals(
$expectedValue,
$billingAgreement->getData($field),
"'{$field}' field value is invalid."
);
}
}
}