diff --git a/app/code/Magento/Authorizenet/Model/Authorizenet.php b/app/code/Magento/Authorizenet/Model/Authorizenet.php
index b35e4f4c39911df89d553ef98ad77eba768ccf3c..4ad08d89cc495556bd4b5b794417fb7185817d92 100644
--- a/app/code/Magento/Authorizenet/Model/Authorizenet.php
+++ b/app/code/Magento/Authorizenet/Model/Authorizenet.php
@@ -6,6 +6,7 @@
 namespace Magento\Authorizenet\Model;
 
 use Magento\Authorizenet\Model\TransactionService;
+use Magento\Framework\HTTP\ZendClientFactory;
 
 /**
  * @SuppressWarnings(PHPMD.TooManyFields)
@@ -97,6 +98,11 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
      */
     protected $_debugReplacePrivateDataKeys = ['merchantAuthentication', 'x_login'];
 
+    /**
+     * @var \Magento\Framework\HTTP\ZendClientFactory
+     */
+    protected $httpClientFactory;
+
     /**
      * @param \Magento\Framework\Model\Context $context
      * @param \Magento\Framework\Registry $registry
@@ -111,6 +117,7 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
      * @param \Magento\Authorizenet\Model\Request\Factory $requestFactory
      * @param \Magento\Authorizenet\Model\Response\Factory $responseFactory
      * @param \Magento\Authorizenet\Model\TransactionService $transactionService
+     * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
      * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
      * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
      * @param array $data
@@ -130,6 +137,7 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
         \Magento\Authorizenet\Model\Request\Factory $requestFactory,
         \Magento\Authorizenet\Model\Response\Factory $responseFactory,
         TransactionService $transactionService,
+        ZendClientFactory $httpClientFactory,
         \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
         \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
         array $data = []
@@ -138,6 +146,7 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
         $this->requestFactory = $requestFactory;
         $this->responseFactory = $responseFactory;
         $this->transactionService = $transactionService;
+        $this->httpClientFactory = $httpClientFactory;
 
         parent::__construct(
             $context,
@@ -370,7 +379,8 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
     protected function postRequest(\Magento\Authorizenet\Model\Request $request)
     {
         $result = $this->responseFactory->create();
-        $client = new \Magento\Framework\HTTP\ZendClient();
+        /** @var \Magento\Framework\HTTP\ZendClient $client */
+        $client = $this->httpClientFactory->create();
         $url = $this->getConfigData('cgi_url') ?: self::CGI_URL;
         $debugData = ['url' => $url, 'request' => $request->getData()];
         $client->setUri($url);
diff --git a/app/code/Magento/Authorizenet/Model/Directpost.php b/app/code/Magento/Authorizenet/Model/Directpost.php
index bbfcd0f7d6e128fb7d0e5d0740223ef42282c469..68fd630f21f4593740fed6288e3821b87677d7db 100644
--- a/app/code/Magento/Authorizenet/Model/Directpost.php
+++ b/app/code/Magento/Authorizenet/Model/Directpost.php
@@ -6,6 +6,7 @@
 namespace Magento\Authorizenet\Model;
 
 use Magento\Authorizenet\Model\TransactionService;
+use Magento\Framework\HTTP\ZendClientFactory;
 use Magento\Payment\Model\Method\ConfigInterface;
 use Magento\Payment\Model\Method\TransparentInterface;
 use Magento\Sales\Model\Order\Email\Sender\OrderSender;
@@ -132,6 +133,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
      * @param Directpost\Request\Factory $requestFactory
      * @param Directpost\Response\Factory $responseFactory
      * @param \Magento\Authorizenet\Model\TransactionService $transactionService
+     * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
      * @param \Magento\Sales\Model\OrderFactory $orderFactory
      * @param \Magento\Store\Model\StoreManagerInterface $storeManager
      * @param \Magento\Quote\Model\QuoteRepository $quoteRepository
@@ -156,6 +158,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
         \Magento\Authorizenet\Model\Directpost\Request\Factory $requestFactory,
         \Magento\Authorizenet\Model\Directpost\Response\Factory $responseFactory,
         TransactionService $transactionService,
+        ZendClientFactory $httpClientFactory,
         \Magento\Sales\Model\OrderFactory $orderFactory,
         \Magento\Store\Model\StoreManagerInterface $storeManager,
         \Magento\Quote\Model\QuoteRepository $quoteRepository,
@@ -187,6 +190,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
             $requestFactory,
             $responseFactory,
             $transactionService,
+            $httpClientFactory,
             $resource,
             $resourceCollection,
             $data
@@ -404,9 +408,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
                     if ($result->getXTransId() != $payment->getParentTransactionId()) {
                         $payment->setTransactionId($result->getXTransId());
                     }
-                    $shouldCloseCaptureTransaction = $payment->getOrder()->canCreditmemo() ? 0 : 1;
-                    $payment->setIsTransactionClosed(1)
-                        ->setShouldCloseParentTransaction($shouldCloseCaptureTransaction)
+                    $payment->setIsTransactionClosed(true)
                         ->setTransactionAdditionalInfo(self::REAL_TRANSACTION_ID_KEY, $result->getXTransId());
                     return $this;
                 }
diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php
index 3247ed2cb9329f86e0efda4e07aeae938515f05b..3726d4e5108ae84b6076a8e39b4e8b628620a7f9 100644
--- a/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php
+++ b/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php
@@ -9,13 +9,21 @@ use Magento\Framework\Simplexml\Element;
 use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
 use Magento\Authorizenet\Model\Directpost;
 use Magento\Authorizenet\Model\TransactionService;
+use Magento\Authorizenet\Model\Request;
+use Magento\Authorizenet\Model\Directpost\Request\Factory;
+use Magento\Sales\Model\Order;
 use Magento\Sales\Model\Order\Payment\Transaction\Repository as TransactionRepository;
 
 /**
  * Class DirectpostTest
+ * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
 class DirectpostTest extends \PHPUnit_Framework_TestCase
 {
+    const TOTAL_AMOUNT = 100.02;
+    const INVOICE_NUM = '00000001';
+    const TRANSACTION_ID = '41a23x34fd124';
+
     /**
      * @var \Magento\Authorizenet\Model\Directpost
      */
@@ -56,6 +64,16 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
      */
     protected $transactionServiceMock;
 
+    /**
+     * @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $httpClientMock;
+
+    /**
+     * @var \Magento\Authorizenet\Model\Directpost\Request\Factory|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $requestFactory;
+
     protected function setUp()
     {
         $this->scopeConfigMock = $this->getMockBuilder('Magento\Framework\App\Config\ScopeConfigInterface')
@@ -64,7 +82,8 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
             ->disableOriginalConstructor()
             ->setMethods([
                 'getOrder', 'getId', 'setAdditionalInformation', 'getAdditionalInformation',
-                'setIsTransactionDenied', 'setIsTransactionClosed'
+                'setIsTransactionDenied', 'setIsTransactionClosed', 'decrypt', 'getCcLast4',
+                'getParentTransactionId', 'getPoNumber'
             ])
             ->getMock();
         $this->dataHelperMock = $this->getMockBuilder('Magento\Authorizenet\Helper\Data')
@@ -85,15 +104,20 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
             ->setMethods(['getTransactionDetails'])
             ->getMock();
 
+        $this->requestFactory = $this->getRequestFactoryMock();
+        $httpClientFactoryMock = $this->getHttpClientFactoryMock();
+
         $helper = new ObjectManagerHelper($this);
         $this->directpost = $helper->getObject(
             'Magento\Authorizenet\Model\Directpost',
             [
                 'scopeConfig' => $this->scopeConfigMock,
                 'dataHelper' => $this->dataHelperMock,
+                'requestFactory' => $this->requestFactory,
                 'responseFactory' => $this->responseFactoryMock,
                 'transactionRepository' => $this->transactionRepositoryMock,
-                'transactionService' => $this->transactionServiceMock
+                'transactionService' => $this->transactionServiceMock,
+                'httpClientFactory' => $httpClientFactoryMock
             ]
         );
     }
@@ -376,7 +400,7 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers \Magento\Authorizenet\Model\Directpost::fetchTransactionInfo
+     * @covers       \Magento\Authorizenet\Model\Directpost::fetchTransactionInfo
      *
      * @param $transactionId
      * @param $resultStatus
@@ -440,6 +464,72 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
         $this->directpost->fetchTransactionInfo($this->paymentMock, $transactionId);
     }
 
+    /**
+     * @covers \Magento\Authorizenet\Model\Directpost::refund()
+     * @return void
+     */
+    public function testSuccessRefund()
+    {
+        $card = 1111;
+
+        $this->paymentMock->expects(static::exactly(2))
+            ->method('getCcLast4')
+            ->willReturn($card);
+        $this->paymentMock->expects(static::once())
+            ->method('decrypt')
+            ->willReturn($card);
+        $this->paymentMock->expects(static::exactly(3))
+            ->method('getParentTransactionId')
+            ->willReturn(self::TRANSACTION_ID . '-capture');
+        $this->paymentMock->expects(static::once())
+            ->method('getPoNumber')
+            ->willReturn(self::INVOICE_NUM);
+        $this->paymentMock->expects(static::once())
+            ->method('setIsTransactionClosed')
+            ->with(true)
+            ->willReturnSelf();
+
+        $orderMock = $this->getOrderMock();
+
+        $this->paymentMock->expects(static::exactly(2))
+            ->method('getOrder')
+            ->willReturn($orderMock);
+
+        $transactionMock = $this->getMockBuilder(Order\Payment\Transaction::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['getAdditionalInformation'])
+            ->getMock();
+        $transactionMock->expects(static::once())
+            ->method('getAdditionalInformation')
+            ->with(Directpost::REAL_TRANSACTION_ID_KEY)
+            ->willReturn(self::TRANSACTION_ID);
+
+        $this->transactionRepositoryMock->expects(static::once())
+            ->method('getByTransactionId')
+            ->willReturn($transactionMock);
+
+        $response = $this->getRefundResponseBody(
+            Directpost::RESPONSE_CODE_APPROVED,
+            Directpost::RESPONSE_REASON_CODE_APPROVED,
+            'Successful'
+        );
+        $this->httpClientMock->expects(static::once())
+            ->method('getBody')
+            ->willReturn($response);
+
+        $this->responseMock->expects(static::once())
+            ->method('getXResponseCode')
+            ->willReturn(Directpost::RESPONSE_CODE_APPROVED);
+        $this->responseMock->expects(static::once())
+            ->method('getXResponseReasonCode')
+            ->willReturn(Directpost::RESPONSE_REASON_CODE_APPROVED);
+
+        $this->dataHelperMock->expects(static::never())
+            ->method('wrapGatewayError');
+
+        $this->directpost->refund($this->paymentMock, self::TOTAL_AMOUNT);
+    }
+
     /**
      * Get data for tests
      * @return array
@@ -468,14 +558,48 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
         $this->responseMock = $this->getMockBuilder('Magento\Authorizenet\Model\Directpost\Response')
             ->setMethods(
                 [
-                    'setData', 'isValidHash', 'getXTransId',
-                    'getXResponseCode', 'getXResponseReasonText',
-                    'getXAmount'
+                    'isValidHash',
+                    'getXTransId', 'getXResponseCode', 'getXResponseReasonCode', 'getXResponseReasonText', 'getXAmount',
+                    'setXResponseCode', 'setXResponseReasonCode', 'setXAvsCode', 'setXResponseReasonText',
+                    'setXTransId', 'setXInvoiceNum', 'setXAmount', 'setXMethod', 'setXType', 'setData',
+                    'setXAccountNumber',
+                    '__wakeup'
                 ]
             )
             ->disableOriginalConstructor()
             ->getMock();
 
+        $this->responseMock->expects(static::any())
+            ->method('setXResponseCode')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXResponseReasonCode')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXResponseReasonText')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXAvsCode')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXTransId')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXInvoiceNum')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXAmount')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXMethod')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXType')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setData')
+            ->willReturnSelf();
+
         $this->responseFactoryMock->expects($this->any())
             ->method('create')
             ->willReturn($this->responseMock);
@@ -530,4 +654,105 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
         libxml_use_internal_errors(false);
         return $document;
     }
+
+    /**
+     * Get mock for authorize.net request factory
+     * @return \PHPUnit_Framework_MockObject_MockBuilder
+     */
+    private function getRequestFactoryMock()
+    {
+        $requestFactory = $this->getMockBuilder(Factory::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['create'])
+            ->getMock();
+        $request = $this->getMockBuilder(Request::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['__wakeup'])
+            ->getMock();
+        $requestFactory->expects(static::any())
+            ->method('create')
+            ->willReturn($request);
+        return $requestFactory;
+    }
+
+    /**
+     * Get mock for order
+     * @return \PHPUnit_Framework_MockObject_MockObject
+     */
+    private function getOrderMock()
+    {
+        $orderMock = $this->getMockBuilder(Order::class)
+            ->disableOriginalConstructor()
+            ->setMethods([
+                'getId', 'getIncrementId', 'getStoreId', 'getBillingAddress', 'getShippingAddress',
+                'getBaseCurrencyCode', 'getBaseTaxAmount', '__wakeup'
+            ])
+            ->getMock();
+
+        $orderMock->expects(static::once())
+            ->method('getId')
+            ->willReturn(1);
+
+        $orderMock->expects(static::exactly(2))
+            ->method('getIncrementId')
+            ->willReturn(self::INVOICE_NUM);
+
+        $orderMock->expects(static::once())
+            ->method('getStoreId')
+            ->willReturn(1);
+
+        $orderMock->expects(static::once())
+            ->method('getBaseCurrencyCode')
+            ->willReturn('USD');
+        return $orderMock;
+    }
+
+    /**
+     * Create and return mock for http client factory
+     * @return \PHPUnit_Framework_MockObject_MockObject
+     */
+    private function getHttpClientFactoryMock()
+    {
+        $this->httpClientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['request', 'getBody', '__wakeup'])
+            ->getMock();
+
+        $this->httpClientMock->expects(static::any())
+            ->method('request')
+            ->willReturnSelf();
+
+        $httpClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['create'])
+            ->getMock();
+
+        $httpClientFactoryMock->expects(static::any())
+            ->method('create')
+            ->willReturn($this->httpClientMock);
+        return $httpClientFactoryMock;
+    }
+
+    /**
+     * Get mocked response for refund transaction
+     * @param $code
+     * @param $reasonCode
+     * @param $reasonText
+     * @return string
+     */
+    private function getRefundResponseBody($code, $reasonCode, $reasonText)
+    {
+        $result = array_fill(0, 50, '');
+        $result[0] = $code; // XResponseCode
+        $result[2] = $reasonCode; // XResponseReasonCode
+        $result[3] = $reasonText; // XResponseReasonText
+        $result[6] = self::TRANSACTION_ID; // XTransId
+        $result[7] = self::INVOICE_NUM; // XInvoiceNum
+        $result[9] = self::TOTAL_AMOUNT; // XAmount
+        $result[10] = Directpost::REQUEST_METHOD_CC; // XMethod
+        $result[11] = Directpost::REQUEST_TYPE_CREDIT; // XType
+        $result[37] = md5(self::TRANSACTION_ID); // x_MD5_Hash
+        $result[50] = '48329483921'; // setXAccountNumber
+        return implode(Directpost::RESPONSE_DELIM_CHAR, $result);
+    }
 }
diff --git a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml b/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml
index 6c02076b5a7dbe55d9a81b7114599221c6c9f14e..9251ad16e7258cfb7938591fe66c9a1a2d353f50 100644
--- a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml
+++ b/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml
@@ -9,7 +9,7 @@
  * @var \Magento\Authorizenet\Block\Transparent\Iframe $block
  * @see \Magento\Authorizenet\Block\Transparent\Iframe
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $method = $block->getMethod();
 $controller = $block->escapeHtml($block->getRequest()->getControllerName());
 $orderUrl = $block->escapeUrl($this->helper('Magento\Authorizenet\Helper\Backend\Data')->getPlaceOrderAdminUrl());
@@ -20,12 +20,12 @@ $ccExpYear = $block->getInfoData('cc_exp_year');
 <!-- IFRAME for request to our server -->
 <iframe id="order-directpost-iframe" allowtransparency="true" frameborder="0" name="iframeSubmitOrder"
         style="display:none;width:100%;background-color:transparent"
-        src="<?php /* @noEscape */ echo $block->getViewFileUrl('blank.html'); ?>">
+        src="<?php echo $block->escapeUrl($block->getViewFileUrl('blank.html')); ?>">
 </iframe>
 <!-- IFRAME for request to Authorize.net -->
 <iframe id="directpost-iframe" allowtransparency="true" frameborder="0"  name="iframeDirectPost"
         style="display:none;width:100%;background-color:transparent"
-        src="<?php /* @noEscape */ echo $block->getViewFileUrl('blank.html'); ?>">
+        src="<?php echo $block->escapeUrl($block->getViewFileUrl('blank.html')); ?>">
 </iframe>
 <fieldset class="admin__fieldset payment-method" id="payment_form_<?php /* @noEscape */ echo $code; ?>"
           style="display:none;">
@@ -124,9 +124,9 @@ $ccExpYear = $block->getInfoData('cc_exp_year');
             '<?php /* @noEscape */ echo $controller; ?>',
             '<?php /* @noEscape */ echo $orderUrl; ?>',
             '<?php echo $block->escapeUrl($method->getCgiUrl()); ?>',
-            '<?php /* @noEscape */ echo $block->getUrl('*/*/save', [
+            '<?php echo $block->escapeUrl($block->getUrl('*/*/save', [
                 '_secure' => $block->getRequest()->isSecure()
-            ]);?>');
+            ]));?>');
 
         <?php if (!$block->isAjaxRequest()): ?>
             });
diff --git a/app/code/Magento/Braintree/Model/PaymentMethod.php b/app/code/Magento/Braintree/Model/PaymentMethod.php
index 45171956e87bcf8832723f7b7dffeb90ea5f1f79..da5ff0d88e29aaf2bf417fa332cf57659672fe04 100644
--- a/app/code/Magento/Braintree/Model/PaymentMethod.php
+++ b/app/code/Magento/Braintree/Model/PaymentMethod.php
@@ -604,7 +604,7 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
                     if ($result->success) {
                         $payment->setIsTransactionClosed(false)
                             ->setShouldCloseParentTransaction(false);
-                        if ($this->isFinalCapture($payment->getParentId(), $amount)) {
+                        if ($payment->isCaptureFinal($amount)) {
                             $payment->setShouldCloseParentTransaction(true);
                         }
                     } else {
@@ -657,7 +657,6 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
                 : $this->braintreeTransaction->refund($transactionId, $amount);
             $this->_debug($this->_convertObjToArray($result));
             if ($result->success) {
-                $payment->setTransactionId($transactionId . '-' . Transaction::TYPE_REFUND);
                 $payment->setIsTransactionClosed(true);
             } else {
                 throw new LocalizedException($this->errorHelper->parseBraintreeError($result));
@@ -905,7 +904,7 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
             ->setAdditionalInformation($this->getExtraTransactionInformation($result->transaction))
             ->setAmount($amount)
             ->setShouldCloseParentTransaction(false);
-        if ($this->isFinalCapture($payment->getParentId(), $amount)) {
+        if ($payment->isCaptureFinal($amount)) {
             $payment->setShouldCloseParentTransaction(true);
         }
         if (isset($result->transaction->creditCard['token']) && $result->transaction->creditCard['token']) {
@@ -964,21 +963,4 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
     {
         return json_decode(json_encode($data), true);
     }
-
-    /**
-     * Checks whether the capture is final
-     *
-     * @param string $orderId
-     * @param string $amount
-     * @return bool
-     */
-    protected function isFinalCapture($orderId, $amount)
-    {
-        if (!empty($orderId)) {
-            $order = $this->orderRepository->get($orderId);
-            return (float)$order->getTotalDue() === (float) $amount;
-        }
-
-        return false;
-    }
 }
diff --git a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php
index e20af765062e3b3b0713c5732d5b67f8f3c279f3..749c2cf390f36359a4364027e9612a76ed810f89 100644
--- a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php
+++ b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php
@@ -32,6 +32,7 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
     const LNAME = 'Doe';
     const AUTH_TRAN_ID = 'r4z34j';
     const AUTH_AMOUNT = 5.76;
+    const TOTAL_AMOUNT = 10.02;
     const AUTH_CC_LAST_4 = '0004';
     const CUSTOMER_ID = '221b3649effb4bb1b62fc940691bd18c';
 
@@ -325,11 +326,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @param $ccType
      * @param null $ccToken
      */
-    protected function setupInfoInstance(
-        $countryId,
-        $ccType,
-        $ccToken = null
-    ) {
+    protected function setupInfoInstance($countryId, $ccType, $ccToken = null)
+    {
         $quoteObj = new \Magento\Framework\DataObject(
             [
                 'billing_address' => new \Magento\Framework\DataObject(
@@ -501,6 +499,7 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
                     'getCustomerEmail',
                     'getCustomerId',
                     'getStoreId',
+                    'getTotalDue'
                 ]
             )->getMock();
 
@@ -522,18 +521,25 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         $orderMock->expects($this->any())
             ->method('getStoreId')
             ->willReturn($storeId);
+        $orderMock->expects(static::any())
+            ->method('getTotalDue')
+            ->willReturn(self::TOTAL_AMOUNT);
+
+        $this->orderRepository->expects(static::any())
+            ->method('get')
+            ->willReturn($orderMock);
+
         return $orderMock;
     }
+
     /**
      * @param \Magento\Framework\DataObject $paymentObject
      * @param int $storeId
      * @return array
      * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
      */
-    protected function setupPaymentObject(
-        \Magento\Framework\DataObject $paymentObject,
-        $storeId
-    ) {
+    protected function setupPaymentObject(\Magento\Framework\DataObject $paymentObject, $storeId)
+    {
         $customerId = '12';
         $customerEmail = 'abc@example.com';
         $company = 'NA';
@@ -564,13 +570,9 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             'address_type' => 'billing',
         ];
 
-        $billingAddress = new \Magento\Framework\DataObject(
-            $addressData
-        );
+        $billingAddress = new \Magento\Framework\DataObject($addressData);
         $addressData['address_type'] = 'shipping';
-        $shippingAddress = new \Magento\Framework\DataObject(
-            $addressData
-        );
+        $shippingAddress = new \Magento\Framework\DataObject($addressData);
 
         $order = $this->setupOrderMock(
             $billingAddress,
@@ -606,26 +608,26 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturn($regionMock);
 
         $braintreeAddressData = [
-            'firstName'         => self::FNAME,
-            'lastName'          => self::LNAME,
-            'company'           => $company,
-            'streetAddress'     => $street,
-            'extendedAddress'   => $street2,
-            'locality'          => $city,
-            'region'            => $regionCode,
-            'postalCode'        => $postcode,
+            'firstName' => self::FNAME,
+            'lastName' => self::LNAME,
+            'company' => $company,
+            'streetAddress' => $street,
+            'extendedAddress' => $street2,
+            'locality' => $city,
+            'region' => $regionCode,
+            'postalCode' => $postcode,
             'countryCodeAlpha2' => $countryId,
         ];
         return [
-            'channel'   => self::CHANNEL,
-            'orderId'   => $orderId,
-            'customer'  => [
+            'channel' => self::CHANNEL,
+            'orderId' => $orderId,
+            'customer' => [
                 'firstName' => self::FNAME,
-                'lastName'  => self::LNAME,
-                'company'   => $company,
-                'phone'     => $phone,
-                'fax'       => $fax,
-                'email'     => $customerEmail,
+                'lastName' => self::LNAME,
+                'company' => $company,
+                'phone' => $phone,
+                'fax' => $fax,
+                'email' => $customerEmail,
             ],
             'billing' => $braintreeAddressData,
             'shipping' => $braintreeAddressData,
@@ -765,8 +767,11 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
     ) {
         $storeId = 3;
         $amount = self::AUTH_AMOUNT;
-        $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment');
-
+        $currencyMock = $this->getPriceCurrencyMock();
+        /** @var \Magento\Sales\Model\Order\Payment $paymentObject */
+        $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment', [
+            'priceCurrency' => $currencyMock
+        ]);
 
         $expectedRequestAttribs = $this->setupAuthorizeRequest(
             $configData,
@@ -798,14 +803,6 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         }
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->assertEquals($this->model, $this->model->authorize($paymentObject, $amount));
         foreach ($expectedPaymentFields as $key => $value) {
@@ -1598,13 +1595,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @expectedException \Magento\Framework\Exception\LocalizedException
      * @expectedExceptionMessage error
      */
-    public function testAuthorizeError(
-        array $configData,
-        $vault,
-        $registry,
-        $existingCustomer,
-        array $paymentInfo
-    ) {
+    public function testAuthorizeError(array $configData, $vault, $registry, $existingCustomer, array $paymentInfo)
+    {
         $storeId = 3;
         $amount = self::AUTH_AMOUNT;
         $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment');
@@ -1649,13 +1641,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @expectedException \Magento\Framework\Exception\LocalizedException
      * @expectedExceptionMessage Please try again later
      */
-    public function testAuthorizeException(
-        array $configData,
-        $vault,
-        $registry,
-        $existingCustomer,
-        array $paymentInfo
-    ) {
+    public function testAuthorizeException(array $configData, $vault, $registry, $existingCustomer, array $paymentInfo)
+    {
         $storeId = 3;
         $amount = self::AUTH_AMOUNT;
         $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment');
@@ -1716,10 +1703,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @param int $numberOfTransactions
      * @return $this
      */
-    protected function setupSalesTransaction(
-        $paymentId,
-        $numberOfTransactions
-    ) {
+    protected function setupSalesTransaction($paymentId, $numberOfTransactions)
+    {
         $transactionCollectionMock = $this->getMockBuilder(
             'Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection'
         )->disableOriginalConstructor()
@@ -1741,12 +1726,24 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         return $this;
     }
 
-    protected function setupPaymentObjectForCapture(
-        $paymentId
-    ) {
+    protected function setupPaymentObjectForCapture($paymentId)
+    {
+        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
+            ->getMockForAbstractClass();
+        $order->expects(static::any())
+            ->method('getTotalDue')
+            ->willReturn(self::TOTAL_AMOUNT);
+        $this->orderRepository->expects(static::any())
+            ->method('get')
+            ->willReturn($order);
+
+        $currencyMock = $this->getPriceCurrencyMock();
+
         $paymentObject = $this->objectManagerHelper->getObject(
             'Magento\Sales\Model\Order\Payment',
             [
+                'priceCurrency' => $currencyMock,
+                'orderRepository' => $this->orderRepository,
                 'data' => [
                     'id' => $paymentId,
                     'cc_trans_id' => self::AUTH_TRAN_ID,
@@ -1756,6 +1753,11 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
 
         return $paymentObject;
     }
+
+    /**
+     * @covers \Magento\Braintree\Model\PaymentMethod::capture()
+     * @throws LocalizedException
+     */
     public function testCaptureSuccess()
     {
         $amount = self::AUTH_AMOUNT;
@@ -1774,20 +1776,40 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->method('critical');
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->model->capture($paymentObject, $amount);
         $this->assertEquals(0, $paymentObject->getIsTransactionClosed());
         $this->assertFalse($paymentObject->getShouldCloseParentTransaction());
     }
 
+    /**
+     * @covers \Magento\Braintree\Model\PaymentMethod::capture()
+     * @return void
+     */
+    public function testCaptureSuccessAuthTransactionClosed()
+    {
+        $paymentId = 31232;
+        /** @var \Magento\Sales\Model\Order\Payment $payment */
+        $payment = $this->setupPaymentObjectForCapture($paymentId);
+        $this->setupSalesTransaction($paymentId, 0); //no existing capture transaction
+
+        $result = $this->setupSuccessResponse([]);
+        $this->braintreeTransactionMock->expects(static::once())
+            ->method('submitForSettlement')
+            ->with(self::AUTH_TRAN_ID, self::TOTAL_AMOUNT)
+            ->willReturn($result);
+
+        $this->psrLoggerMock->expects(static::never())
+            ->method('critical');
+
+        $payment->setParentId(1);
+        $this->model->capture($payment, self::TOTAL_AMOUNT);
+
+        static::assertFalse($payment->getIsTransactionClosed());
+        static::assertTrue($payment->getShouldCloseParentTransaction());
+
+    }
+
     /**
      * @expectedException \Magento\Framework\Exception\LocalizedException
      * @expectedExceptionMessage There was an error capturing the transaction: error.
@@ -1820,10 +1842,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         $this->model->capture($paymentObject, $amount);
     }
 
-    protected function setupAuthTransaction(
-        $paymentId,
-        $authTransaction
-    ) {
+    protected function setupAuthTransaction($paymentId, $authTransaction)
+    {
         $authTransactionCollectionMock = $this->getMockBuilder(
             'Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection'
         )->disableOriginalConstructor()
@@ -1926,14 +1946,6 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturn($result);
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->model->capture($paymentObject, $amount);
         $this->assertEquals(0, $paymentObject->getIsTransactionClosed());
@@ -2115,17 +2127,10 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
                         'submitForSettlement' => true,
                     ],
                 ]
-            )->willReturn($resultSuccess);
+            )
+            ->willReturn($resultSuccess);
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->model->capture($paymentObject, $amount);
         $this->assertEquals(PaymentMethod::STATUS_APPROVED, $paymentObject->getStatus());
@@ -2192,9 +2197,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
     //End: test capture
 
     //Start: test refund
-    protected function setupPaymentObjectForRefund(
-        $refundTransactionId
-    ) {
+    protected function setupPaymentObjectForRefund($refundTransactionId)
+    {
         $paymentObject = $this->objectManagerHelper->getObject(
             'Magento\Sales\Model\Order\Payment',
             [
@@ -2379,7 +2383,6 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
 
         $this->model->refund($paymentObject, $amount);
         $this->assertEquals(1, $paymentObject->getIsTransactionClosed());
-        $this->assertEquals($refundTransactionId . '-' .Transaction::TYPE_REFUND, $paymentObject->getTransactionId());
     }
 
     /**
@@ -2461,9 +2464,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturnArgument(0);
     }
 
-    protected function setupPaymentObjectForVoid(
-        $orderId
-    ) {
+    protected function setupPaymentObjectForVoid($orderId)
+    {
         $paymentObject = $this->objectManagerHelper->getObject(
             'Magento\Sales\Model\Order\Payment'
         );
@@ -2666,4 +2668,22 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturn($orderMock);
         $this->assertEquals(false, $this->model->canVoid());
     }
+
+    /**
+     * @return \Magento\Directory\Model\PriceCurrency|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function getPriceCurrencyMock()
+    {
+        $currencyMock = $this->getMockBuilder('\Magento\Directory\Model\PriceCurrency')
+            ->disableOriginalConstructor()
+            ->setMethods(['round'])
+            ->getMock();
+        $currencyMock->expects(static::any())
+            ->method('round')
+            ->willReturnMap([
+                [self::TOTAL_AMOUNT, round(self::TOTAL_AMOUNT, 2)],
+                [self::AUTH_AMOUNT, round(self::AUTH_AMOUNT, 2)]
+            ]);
+        return $currencyMock;
+    }
 }
diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml
index 5610e082e1715e36dcecc8f7cc241bf1aeee2798..508313a25527a942d6c55cea7fd64873528e91a6 100644
--- a/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml
+++ b/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Braintree\Block\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $storedCards = $this->helper('\Magento\Braintree\Helper\Createorder')->getLoggedInCustomerCards();
 $useVault = $block->useVault();
 $useCvv = $block->useCvv();
diff --git a/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml b/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml
index 267a6fede0644551bf2e45c5027bf2aebc9effe4..6edb66bd04c8f1c5858104007035a9b83c14fad9 100644
--- a/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml
+++ b/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml
@@ -42,7 +42,7 @@ $config = [
      class="paypal checkout <?php echo $block->escapeHtml($block->getShowOrPosition()) ?> paypal-logo"
     >
     <fieldset class="fieldset paypal items">
-        <div id="<?php /* @noEscape */ echo $containerId ?>"
+        <div id="<?php echo $block->escapeHtml($containerId); ?>"
              data-mage-init='<?php /* @noEscape */ echo json_encode($config); ?>'></div>
     </fieldset>
 </div>
diff --git a/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml b/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml
index 6fcac2eae9c411929472c7b79ef1038836646183..44dc85b5404a1b51b2b3e508cbaa6b575788215e 100644
--- a/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml
+++ b/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml
@@ -164,7 +164,7 @@ $serializedFormData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonE
                                 class="year required-entry"
                                 data-validate="{required:true}">
                                 <?php foreach ($block->getCcYears() as $k => $v): ?>
-                                    <option value="<?php /* @noEscape */ echo $k ? $k : ''; ?>"
+                                    <option value="<?php /* @noEscape */ echo $k ? $block->escapeHtml($k) : ''; ?>"
                                         <?php if ($k == $defaultExpYear): ?> selected="selected"<?php endif; ?>>
                                         <?php echo $block->escapeHtml($v); ?>
                                     </option>
diff --git a/app/code/Magento/Braintree/view/frontend/templates/form.phtml b/app/code/Magento/Braintree/view/frontend/templates/form.phtml
index 459a61568cff7fa67f19d3146b1a2f7e0fb5ff5d..41029526cc388a58d93dc9c8ef119d99a1ccafd4 100644
--- a/app/code/Magento/Braintree/view/frontend/templates/form.phtml
+++ b/app/code/Magento/Braintree/view/frontend/templates/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Braintree\Block\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $loggedIn = $block->isCustomerLoggedIn();
 $storedCards = $block->getStoredCards();
 $useVault = $loggedIn && $block->useVault() && count($storedCards);
diff --git a/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php b/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
index b07b6e82bdc4d04f71bc4c8a46ac686f82bf2332..fb92f2bc3fffd09f5ac54eca2a2fb65e77bd913b 100644
--- a/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
+++ b/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
@@ -463,4 +463,13 @@ class Links extends \Magento\Backend\Block\Template
     {
         return $this->_storeManager->getStore($storeId)->getBaseCurrencyCode();
     }
+
+    /**
+     * @param null|string|bool|int|\Magento\Store\Model\Store $storeId $storeId
+     * @return string
+     */
+    public function getBaseCurrencySymbol($storeId)
+    {
+        return $this->_storeManager->getStore($storeId)->getBaseCurrency()->getCurrencySymbol();
+    }
 }
diff --git a/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml b/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml
index d5c4b6dca86ea769bc9bb04fe98309bffcccd0e5..cf43aa7d3f4f62de46a4d86395648c671a654c2a 100644
--- a/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml
+++ b/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml
@@ -107,8 +107,10 @@ require([
             '</td>'+
             <?php if ($block->getCanReadPrice() !== false) : ?>
                 '<td class="col-price">'+
-                    '<input type="text" id="downloadable_link_<%- data.id %>_price_value" class="input-text admin__control-text validate-number link-prices<?php if ($block->getCanEditPrice() === false) : ?> disabled<?php endif; ?>" name="downloadable[link][<%- data.id %>][price]" value="<%- data.price %>"<?php if ($block->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif; ?> /> ' +
-                    '<div class="note">[<?php /* @escapeNotVerified */ echo $block->getBaseCurrencyCode($_product->getStoreId()) ?>]</div>' +
+                    '<div class="admin__control-addon">' +
+                        '<input type="text" id="downloadable_link_<%- data.id %>_price_value" class="input-text admin__control-text validate-number link-prices<?php if ($block->getCanEditPrice() === false) : ?> disabled<?php endif; ?>" name="downloadable[link][<%- data.id %>][price]" value="<%- data.price %>"<?php if ($block->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif; ?> /> ' +
+                        '<label class="admin__addon-prefix"><span><?php echo $block->escapeHtml($block->getBaseCurrencySymbol($_product->getStoreId())) ?></span></label>' +
+                    '</div>' +
                     <?php if ($_product->getStoreId() && $block->getIsPriceWebsiteScope()) : ?>
                         '<div class="admin__field admin__field-option">'+
                             '<input type="checkbox" id="downloadable_link_<%- data.id %>_price" name="downloadable[link][<%- data.id %>][use_default_price]" value="1"<?php if ($block->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif; ?> class="admin__control-checkbox" />'+
diff --git a/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml b/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml
index dc0c669468da9a1aaae43fc83bfa32cc22776044..21b83793d7d27f94ea511f1e7a6cde2ab0a8384f 100644
--- a/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml
+++ b/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml
@@ -8,16 +8,16 @@
 
 ?>
 <div class="multicheckout success">
-    <h2 class="subtitle"><?php /* @noEscape */ echo __('Thank you for your purchase!') ?></h2>
-    <p><?php /* @escapeNotVerified */ echo __('Thanks for your order. We\'ll email you order details and tracking information.') ?></p>
+    <h2 class="subtitle"><?php echo $block->escapeHtml(__('Thank you for your purchase!')) ?></h2>
+    <p><?php echo $block->escapeHtml(__('Thanks for your order. We\'ll email you order details and tracking information.')) ?></p>
     <?php if ($_orderIds = $block->getOrderIds()): ?>
     <p class="order-number">
         <?php $flag = false ?>
         <span>
             <?php if (count($_orderIds) > 1): ?>
-                <?php /* @noEscape */ echo __('Your order numbers are: ') ?>
+                <?php echo $block->escapeHtml(__('Your order numbers are: ')) ?>
             <?php else : ?>
-                <?php /* @noEscape */ echo __('Your order number is: ') ?>
+                <?php echo $block->escapeHtml(__('Your order number is: ')) ?>
             <?php endif; ?>
         </span>
         <?php foreach ($_orderIds as $orderId => $incrementId): ?><?php if ($flag): ?><?php echo ', ' ?><?php endif; ?><?php $flag = true ?><a href="<?php /* @escapeNotVerified */ echo $block->getViewOrderUrl($orderId) ?>"><?php /* @escapeNotVerified */ echo $incrementId ?></a><?php endforeach; ?>
@@ -25,6 +25,6 @@
     <?php endif; ?>
     <?php echo $block->getChildHtml() ?>
     <div class="actions">
-        <a class="action continue" title="<?php /* @noEscape */ echo __('Continue Shopping') ?>" href="<?php /* @escapeNotVerified */ echo $block->getContinueUrl() ?>"><span><?php /* @noEscape */ echo __('Continue Shopping') ?></span></a>
+        <a class="action continue" title="<?php echo $block->escapeHtml(__('Continue Shopping')) ?>" href="<?php /* @escapeNotVerified */ echo $block->getContinueUrl() ?>"><span><?php echo $block->escapeHtml(__('Continue Shopping')) ?></span></a>
     </div>
 </div>
diff --git a/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml b/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml
index ab38d3752a679f68d8a0371d087c126268707a99..f1109afb7974ef65ee42d01d18162dc121c428ab 100644
--- a/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml
+++ b/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml
@@ -8,7 +8,7 @@
 /**
  * @var \Magento\Payment\Block\Adminhtml\Transparent\Form $block
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccType = $block->getInfoData('cc_type');
 $ccExpMonth = $block->getInfoData('cc_exp_month');
 $ccExpYear = $block->getInfoData('cc_exp_year');
diff --git a/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml b/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml
index 1bb248e6fd5662bced43e2f7ee9d4c5a942a1f69..0d28d33caea9cadcfce22c7fb68e2da557c7935b 100644
--- a/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml
+++ b/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Payment\Block\Transparent\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccType = $block->getInfoData('cc_type');
 $ccExpYear = $block->getInfoData('cc_exp_year');
 $ccExpMonth = $block->getInfoData('cc_exp_month');
@@ -29,7 +29,7 @@ $ccExpMonth = $block->getInfoData('cc_exp_month');
         "controller":"<?php echo $block->escapeHtml($block->getRequest()->getControllerName()); ?>",
         "gateway":"<?php /* @noEscape */ echo $code; ?>",
         "dateDelim":"<?php echo $block->escapeHtml($block->getDateDelim()); ?>",
-        "cardFieldsMap":<?php /* @noEscape */ echo $block->getCardFieldsMap(); ?>,
+        "cardFieldsMap":<?php echo $block->escapeHtml($block->getCardFieldsMap()); ?>,
         "orderSaveUrl":"<?php echo $block->escapeUrl($block->getOrderUrl()); ?>",
         "cgiUrl":"<?php echo $block->escapeUrl($block->getCgiUrl()); ?>",
         "expireYearLength":"<?php echo $block->escapeHtml($block->getMethodConfigData('cc_year_length')); ?>",
@@ -102,7 +102,7 @@ $ccExpMonth = $block->getInfoData('cc_exp_month');
                     data-container="<?php /* @noEscape */ echo $code; ?>-cc-year" data-validate='{required:true}'>
                 <?php foreach ($block->getCcYears() as $k => $v): ?>
                     <option
-                        value="<?php /* @noEscape */ echo $k ? $k : '' ?>"
+                        value="<?php /* @noEscape */ echo $k ? $block->escapeHtml($k) : '' ?>"
                         <?php if ($k == $ccExpYear): ?> selected="selected"<?php endif ?>>
                         <?php echo $block->escapeHtml($v); ?>
                     </option>
diff --git a/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml b/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml
index 8deddb094d1799a1f1459a6be34e7fdbf5a054f0..8b20f64b5a60109508916e2a2ed2b07d36fa586f 100644
--- a/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml
+++ b/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml
@@ -11,6 +11,6 @@
  * @see \Magento\Payment\Block\Transparent\Info
  */
 ?>
-<fieldset id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none" class="fieldset items redirect">
+<fieldset id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>" style="display:none" class="fieldset items redirect">
     <div><?php echo $block->escapeHtml(__('We\'ll ask for your payment details before you place an order.')); ?></div>
 </fieldset>
diff --git a/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml b/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml
index 05d8d3c02c82cdfc54c16a9d77a6863422e7ecbd..a02de6dbaff84f73d2f9d7fa48dcc23c2b482f1d 100644
--- a/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml
@@ -8,7 +8,7 @@
 /**
  * @var \Magento\Payment\Block\Transparent\Form $block
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccType = $block->getInfoData('cc_type');
 $ccExpMonth = $block->getInfoData('cc_exp_month');
 $ccExpYear = $block->getInfoData('cc_exp_year');
diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml
index 64ea503996cd280d8b29dc154b4dc20e9e47f69d..a589900d6233ae186fbef507484d2334a64c1db6 100644
--- a/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Payment\Block\Transparent\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccExpMonth = $block->getInfoData('cc_exp_month');
 $ccExpYear = $block->getInfoData('cc_exp_year');
 $ccType = $block->getInfoData('cc_type');
@@ -20,7 +20,7 @@ $content = '<img src=\"' . $block->getViewFileUrl('Magento_Checkout::cvv.png') .
 <iframe width="0" height="0" id="<?php /* @noescape */ echo $code; ?>-transparent-iframe"
         data-container="<?php /* @noEscape */ echo $code; ?>-transparent-iframe" allowtransparency="true"
         frameborder="0"  name="iframeTransparent" style="display:none;width:100%;background-color:transparent"
-        src="<?php /* @noEscape */ echo $block->getViewFileUrl('blank.html') ?>"></iframe>
+        src="<?php echo $block->escapeUrl($block->getViewFileUrl('blank.html')) ?>"></iframe>
 <form class="form" id="co-transparent-form" action="#" method="post" data-mage-init='{
     "transparent":{
         "controller":"<?php echo $block->escapeHtml($block->getRequest()->getControllerName()); ?>",
@@ -28,7 +28,7 @@ $content = '<img src=\"' . $block->getViewFileUrl('Magento_Checkout::cvv.png') .
         "orderSaveUrl":"<?php echo $block->escapeUrl($block->getOrderUrl()); ?>",
         "cgiUrl":"<?php echo $block->escapeUrl($block->getCgiUrl()); ?>",
         "dateDelim":"<?php echo $block->escapeHtml($block->getDateDelim()); ?>",
-        "cardFieldsMap":<?php /* @noEscape */ echo $block->getCardFieldsMap(); ?>,
+        "cardFieldsMap":<?php echo $block->escapeHtml($block->getCardFieldsMap()); ?>,
         "nativeAction":"<?php echo $block->escapeUrl($block->getUrl('checkout/onepage/saveOrder', ['_secure' => $block->getRequest()->isSecure()])); ?>"
     }, "validation":[]}'>
     <fieldset class="fieldset ccard <?php /* @noEscape */ echo $code; ?>" id="payment_form_<?php /* @noEscape */ echo $code; ?>">
diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml
index b191981585af62dde6804c9dbfc44a3b0258e1b5..fc9624bde1016edc28d53a7bc282ca36ca64625f 100644
--- a/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml
@@ -33,7 +33,7 @@ $params = $block->getParams();
                     'Magento_Checkout/js/action/place-order'
                 ],
                 function(quote, placeOrderAction) {
-                    placeOrderAction(quote.paymentMethod(), true);
+                    placeOrderAction({"method": quote.paymentMethod().method}, true);
                 }
             );
         <?php endif; ?>
diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml
index c3ce1e5dbb7029ed65db079fcbf0230839373a3b..84cd69f6e4f698ff8731f76c5367e1b8244e0dae 100644
--- a/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml
@@ -11,7 +11,7 @@
  * @see \Magento\Payment\Block\Transparent\Info
  */
 ?>
-<fieldset id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none" class="fieldset items redirect">
+<fieldset id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>" style="display:none" class="fieldset items redirect">
     <div>
         <?php echo $block->escapeHtml(__('We\'ll ask for your payment details before you place an order.')); ?>
     </div>
diff --git a/app/code/Magento/Paypal/Model/Config/Rules/Converter.php b/app/code/Magento/Paypal/Model/Config/Rules/Converter.php
index a636188baf1cf571ea572625e6de6dec367b640e..5528f79b385758a89b1c4c1fad3d2fa90e92b08e 100644
--- a/app/code/Magento/Paypal/Model/Config/Rules/Converter.php
+++ b/app/code/Magento/Paypal/Model/Config/Rules/Converter.php
@@ -58,8 +58,8 @@ class Converter implements ConverterInterface
     protected function createEvents(\DOMElement $node)
     {
         $result = [];
-        /** @var \DOMElement $child */
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
                 $result[$child->getAttribute('name')] = [
                     'value' => $child->getAttribute('value'),
@@ -80,8 +80,8 @@ class Converter implements ConverterInterface
     protected function createPredicate(\DOMElement $node)
     {
         $result = [];
-        /** @var \DOMElement $child */
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
                 $result = [
                     'name' => $child->getAttribute('name'),
@@ -105,33 +105,18 @@ class Converter implements ConverterInterface
     {
         $result = [];
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
-                $result = array_merge($result, $this->createRule($child));
+                $result[$child->getAttribute('type')][] = [
+                    'event' => $child->getAttribute('event'),
+                    'argument' => $this->createArgument($child),
+                ];
             }
         }
 
         return [$node->getAttribute('target') => $result];
     }
 
-    /**
-     * Creating rules
-     *
-     * @param \DOMElement $node
-     * @return array
-     */
-    protected function createRule(\DOMElement $node)
-    {
-        $result = [];
-        $type = $node->getAttribute('type');
-        /** @var \DOMElement $node */
-        $result[$type] = [
-            'event' => $node->getAttribute('event'),
-        ];
-        $result[$type]['argument'] = $this->createArgument($node);
-
-        return $result;
-    }
-
     /**
      * Create argument
      *
@@ -141,8 +126,8 @@ class Converter implements ConverterInterface
     protected function createArgument(\DOMElement $node)
     {
         $result = [];
-        /** @var \DOMElement $child */
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
                 $result[$child->getAttribute('name')] = $child->textContent;
             }
diff --git a/app/code/Magento/Paypal/Model/Payflowpro.php b/app/code/Magento/Paypal/Model/Payflowpro.php
index 6efc7e7cca4ed1735aeeaaacc8deee09aaf18eb1..894c0792a99e4ab689f5c40aed6b0d29c0d334a5 100644
--- a/app/code/Magento/Paypal/Model/Payflowpro.php
+++ b/app/code/Magento/Paypal/Model/Payflowpro.php
@@ -500,8 +500,7 @@ class Payflowpro extends \Magento\Payment\Model\Method\Cc implements GatewayInte
         $this->processErrors($response);
 
         if ($response->getResultCode() == self::RESPONSE_CODE_APPROVED) {
-            $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(1);
-            $payment->setShouldCloseParentTransaction(!$payment->getCreditmemo()->getInvoice()->canRefund());
+            $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(true);
         }
         return $this;
     }
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php
index eb62d570481bde11725647a1ab54858c4ca96dcf..ffd2f141e0a0d7da9bc3f642e581e754d3324d6e 100644
--- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php
+++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php
@@ -78,22 +78,27 @@ class ConverterTest extends \PHPUnit_Framework_TestCase
                         'relations' => [
                             'payment_test_1' => [
                                 'test' => [
-                                    'event' => 'event0',
-                                    'argument' => [],
+                                    [
+                                        'event' => 'event0',
+                                        'argument' => [],
+                                    ]
                                 ],
                             ],
                             'payment_test_2' => [
                                 'test' => [
-                                    'event' => 'event1',
-                                    'argument' => [
-                                    ],
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [],
+                                    ]
                                 ],
                                 'test-two' => [
-                                    'event' => 'event1',
-                                    'argument' => [
-                                        'argument1' => 'argument1',
-                                        'argument2' => 'argument2',
-                                    ],
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [
+                                            'argument1' => 'argument1',
+                                            'argument2' => 'argument2',
+                                        ],
+                                    ]
                                 ],
                             ],
                         ],
@@ -122,21 +127,34 @@ class ConverterTest extends \PHPUnit_Framework_TestCase
                         'relations' => [
                             'payment_test_1' => [
                                 'test' => [
-                                    'event' => 'event0',
-                                    'argument' => [],
+                                    [
+                                        'event' => 'event0',
+                                        'argument' => [],
+                                    ]
                                 ],
                             ],
                             'payment_test_2' => [
                                 'test' => [
-                                    'event' => 'event1',
-                                    'argument' => [],
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [],
+                                    ]
                                 ],
                                 'test-two' => [
-                                    'event' => 'event1',
-                                    'argument' => [
-                                        'argument1' => 'argument1',
-                                        'argument2' => 'argument2',
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [
+                                            'argument1' => 'argument1',
+                                            'argument2' => 'argument2',
+                                        ],
                                     ],
+                                    [
+                                        'event' => 'event2',
+                                        'argument' => [
+                                            'argument1' => 'argument1',
+                                            'argument2' => 'argument2',
+                                        ],
+                                    ]
                                 ],
                             ],
                         ],
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml
index 297d3c8e620a06480da9c009f1cfc59ae81d746f..4b4c6833d92c92399d29fae6e687472d24cbedfb 100644
--- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml
+++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml
@@ -52,6 +52,10 @@
                 <argument name="argument1">argument1</argument>
                 <argument name="argument2">argument2</argument>
             </rule>
+            <rule type="test-two" event="event2">
+                <argument name="argument1">argument1</argument>
+                <argument name="argument2">argument2</argument>
+            </rule>
         </relation>
     </payment>
 </rules>
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php
index 215680852225b7b3ed5b4507a223fda725b821b5..c6250a24903ee0e71b30669e762a44c00a3eb06c 100644
--- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php
+++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php
@@ -175,7 +175,6 @@ class PayflowproTest extends \PHPUnit_Framework_TestCase
         $this->payflowpro->fetchTransactionInfo($payment, 'AD49G8N825');
     }
 
-
     /**
      * @param $response
      * @dataProvider setTransStatusDataProvider
@@ -323,6 +322,22 @@ class PayflowproTest extends \PHPUnit_Framework_TestCase
         ];
     }
 
+    /**
+     * @covers \Magento\Paypal\Model\Payflowpro::refund()
+     */
+    public function testRefund()
+    {
+        /** @var \Magento\Sales\Model\Order\Payment $paymentMock */
+        $paymentMock = $this->getPaymentMock();
+
+        $response = $this->execGatewayRequest();
+
+        $amount = 213.04;
+        $this->payflowpro->refund($paymentMock, $amount);
+        static::assertEquals($response['pnref'], $paymentMock->getTransactionId());
+        static::assertTrue($paymentMock->getIsTransactionClosed());
+    }
+
     /**
      * Create mock object for store model
      * @return void
@@ -399,16 +414,16 @@ class PayflowproTest extends \PHPUnit_Framework_TestCase
             'year' => 18,
             'cvv' => 123
         ];
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcNumber')
             ->willReturn($cardData['number']);
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcExpMonth')
             ->willReturn($cardData['month']);
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcExpYear')
             ->willReturn($cardData['year']);
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcCid')
             ->willReturn($cardData['cvv']);
         return $paymentMock;
diff --git a/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml b/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml
index c187130b357b85e975b93c17f457b30c78bd5f0f..4b5acbe6e073e8259ff3a3b4364c7c5c7ef70fac 100644
--- a/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml
+++ b/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml
@@ -329,7 +329,10 @@
                 <argument name="wpp_usuk">wpp_usuk</argument>
                 <argument name="paypal_payflowpro_with_express_checkout">paypal_payflowpro_with_express_checkout</argument>
             </rule>
+
             <rule type="payflow/bml/disable-conditional-express" event="deactivate-express"/>
+            <rule type="payflow/bml/disable-conditional-express" event=":load"/>
+
             <rule type="payflow/bml/enable" event="activate-express"/>
             <rule type="payflow/express/lock-conditional" event=":load"/>
             <rule type="payflow/bml/lock-conditional" event=":load"/>
diff --git a/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml b/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml
index 0d933a861b54182146e34358253ac033072f4c28..e1f6c1ac9655bcaa39a0e78efcf0023c1564b6ae 100644
--- a/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml
+++ b/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 /** @var \Magento\Paypal\Block\Adminhtml\Billing\Agreement\View\Form $block */
 ?>
-<?php $code = $block->getMethodCode() ?>
+<?php $code = $block->escapeHtml($block->getMethodCode()) ?>
 <fieldset class="form-list" id="payment_form_<?php /* @noEscape */ echo $code; ?>" style="display:none;">
     <div class="admin__field _required">
         <label for="<?php /* @noEscape */ echo $code; ?>_ba_agreement_id" class="admin__field-label">
diff --git a/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml b/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml
index d3a6bab129806819191d864a6dde2c60c952703f..66c2184c31012317eaa1cd704b3a3ba3ec0f5385 100644
--- a/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml
+++ b/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 /* @var $block \Magento\Paypal\Block\Payment\Form\Billing\Agreement */
 ?>
-<?php $code = $block->getMethodCode() ?>
+<?php $code = $block->escapeHtml($block->getMethodCode()) ?>
 <fieldset class="admin__fieldset payment-method form-list"
           id="payment_form_<?php /* @noEscape */ echo $code; ?>" style="display:none;">
     <div class="admin__field _required">
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js b/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js
index ea426368243185bc14ed8fded1b77387366dddb3..278b101c9c696aabe05c1c62a28d426ce399acaf 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js
@@ -2,25 +2,28 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function (solution, message, argument) {
         var isConfirm = false;
 
         _.every(argument, function (name) {
-            if (solution.solutionsElements[name]
-                && solution.solutionsElements[name].find(solution.enableButton).val() == 1
+            if (solution.solutionsElements[name] &&
+                solution.solutionsElements[name].find(solution.enableButton).val() == 1
             ) {
                 isConfirm = true;
+
                 return !isConfirm;
             }
+
             return !isConfirm;
         }, this);
 
         if (isConfirm) {
             return confirm(message);
-        } else {
-            return true;
         }
+
+        return true;
     };
 });
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js
index b565aa2d66d6b46c2165650567b06fe440291b4e..c1c12344cc54c15ededbd2bb0b80184b09be19fd 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js
@@ -3,18 +3,24 @@
  * See COPYING.txt for license details.
  */
 define([
-    "uiClass",
-    "underscore"
-], function (Class, _) {
-    "use strict";
+    'uiClass'
+], function (Class) {
+    'use strict';
+
     return Class.extend({
+
         /**
          * Constructor
+         *
+         * @param {Object} config
+         * @returns {exports.initialize}
          */
         initialize: function (config) {
             this.initConfig(config);
+
             return this;
         },
+
         /**
          * To apply the rule
          */
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js
index 4d94f6a2a9ff63cdb9195b4bbdaf012f98ec4cf7..54b263be6421dcdd7534f811c7ef80a02be12e99 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js
@@ -2,32 +2,42 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-(function() {
+(function () {
+    'use strict';
+
     var executed = false;
+
     define([
-        'Magento_Ui/js/modal/alert'
-    ], function (alert) {
-        "use strict";
+        'Magento_Ui/js/modal/alert',
+        'underscore'
+    ], function (alert, _) {
+
         return function ($target, $owner, data) {
-            if ($owner.find(data.enableButton).val() == 1) {
-                var isDisabled = true;
 
+            var isDisabled = true,
+                newLine = String.fromCharCode(10, 13);
+
+            if ($owner.find(data.enableButton).val() === '1') {
                 _.every(data.argument, function (name) {
-                    if (data.solutionsElements[name]
-                        && data.solutionsElements[name].find(data.enableButton).val() == 1
+                    if (data.solutionsElements[name] &&
+                        data.solutionsElements[name].find(data.enableButton).val() === '1'
                     ) {
                         isDisabled = false;
+
                         return isDisabled;
                     }
+
                     return isDisabled;
                 }, this);
 
                 if (!isDisabled && !executed) {
                     executed = true;
                     alert({
-                        content: "The following error(s) occured:\n\r"
-                                +"Some PayPal solutions conflict.\n\r"
-                                +"Please re-enable the previously enabled payment solutions."
+                        content: 'The following error(s) occurred:' +
+                        newLine +
+                        'Some PayPal solutions conflict.' +
+                        newLine +
+                        'Please re-enable the previously enabled payment solutions.'
                     });
                 }
             }
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js
index a5cc52ed96bc2b145d06a638cef1be7135ce920b..54e355580394b5437fb79b6d2ecc6e20be54e184 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js
@@ -5,7 +5,8 @@
 define([
     'Magento_Paypal/js/rules/simple/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         disable($target, $owner, data);
         $target.find(data.enableButton).change();
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js
index 8fccdd054558b3e289fd79ec88c52fbb32dac7ce..e3d95340b8bfe534f1da36452b36dcc63bc2e4db 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/payflow/bml/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableExpress).val() == "0") {
+        if ($target.find(data.enableExpress).val() === '0') {
             disable($target, $owner, data);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js
index 2c5ae4265342b266e9fe76d9b60994482e371a0e..20182ef0205f4135e853b77b3c937d17f59c66bc 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/payflow/bml/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             disable($target, $owner, data);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js
index 873eea979583c30b3fdc10906b968b1c7a1fba00..01d241a0e36197981029a2cfa63eaf1399193967 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find('label[for="' + $target.find(data.enableBml).attr('id') + '"]').removeClass('enabled');
         $target.find(data.enableBml + ' option[value="0"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js
index f5d796397c705af56a476831d3710ff0c66f504b..9770d463f45fc676eeda339a9d7849368822f93f 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js
@@ -2,18 +2,21 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js
index e7710d80cf07fc84a6ee9769ee8bb4388c155921..3ddfc3b0f60446334670836e98fffcf2cdac2dd4 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableBml).prop('disabled', false);
         $target.find(data.enableBml + ' option[value="1"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js
index 09007924b0b4bb53f90f968717766af6e5ba9d74..607c56984e7dc6f4047a20a55b8a262442bd69ba 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js
@@ -3,9 +3,10 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             $target.find(data.enableBml).prop('disabled', true);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js
index f37306731b8857896fcade130783a5de86ccbe20..94b178c071642e09b80771094946ba7522541815 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/payflow/express/disable'
 ], function (disableExpress) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             disableExpress($target, $owner, data);
             $target.find(data.enableExpress).change();
         }
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js
index 4d8b6fa3ca39918293381d36e23d1314304f1439..77649695f3c11394c98f95d7e50bd57d4857971a 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find('label[for="' + $target.find(data.enableExpress).attr('id') + '"]').removeClass('enabled');
         $target.find(data.enableExpress + ' option[value="0"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js
index cc76875080a4ee00e98e93c56b182982bd06e233..ea9fc5f2d0ccbe6741615fed4bb9cd5cb0c85b74 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js
@@ -2,18 +2,21 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js
index 456b4a6ac78ddd8bc591653a45aaf247303f1d2a..6dc1a0a49cfba72168b9e0d69b067b9dab2fa380 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableExpress).prop('disabled', false);
         $target.find(data.enableExpress + ' option[value="1"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js
index 476af3b58366a86ffef757addeb4230a4f0436de..c07a0b5cf713e2b7c65bda537e331e47980f6e37 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js
@@ -3,9 +3,10 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             $target.find(data.enableExpress).prop('disabled', true);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js
index ed327a4678fbc1db79bc1250cee0557aa06f9e5f..d4b8d4100e56d5e9e5e2ffc134ae79e6a5445859 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/paypal/bml/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             disable($target, $owner, data);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js
index 124c325c445dce34969c7e02a4ad89455daedbcf..c6ef93d332fb64b102a4ec2ba30370e5cc61d384 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find('label[for="' + $target.find(data.enableBmlPayPal).attr('id') + '"]').removeClass('enabled');
         $target.find(data.enableBmlPayPal + ' option[value="0"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js
index 1beb826bf39a003926868e7b420537a03686da50..90f7561734f14f34d21e126ba7df9d2d9926dadc 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableBmlPayPal).prop('disabled', false);
         $target.find(data.enableBmlPayPal + ' option[value="1"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js
index 8421803de67a2e84fc1030fcb60ab6909547b814..25e7b611a24692ed05b544bb8bcf8e80b05862b3 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableButton + ' option[value="0"]').prop('selected', true);
         $target.find('label.enabled').removeClass('enabled');
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js
index bd2c2f62a29f5b20a08910fdf3e2504c584bfdff..55a82e3cc19322136dec33e5b6c14e41ec0525f8 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js
@@ -3,19 +3,23 @@
  * See COPYING.txt for license details.
  */
 define([
-    'Magento_Paypal/js/rules/paypal/express/lock-configuration'
-], function (lockConfiguration) {
-    "use strict";
+    'Magento_Paypal/js/rules/paypal/express/lock-configuration',
+    'underscore'
+], function (lockConfiguration, _) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js
index e549bda0adf3db7d2a8e8f0f626a72097f96530c..351f799b57b28a3739d23f37cb46bc0afaedafe8 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.buttonConfiguration).addClass('disabled')
             .attr('disabled', 'disabled');
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js
index 6bcf9a559b39a05e5d9a76ef35afb8e2b029d81a..7943c843b13cde484d9d0baf1149110ac4885754 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js
@@ -3,19 +3,23 @@
  * See COPYING.txt for license details.
  */
 define([
-    'Magento_Paypal/js/rules/simple/disable'
-], function (disable) {
-    "use strict";
+    'Magento_Paypal/js/rules/simple/disable',
+    'underscore'
+], function (disable, _) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js
index 413a8bf08b1d013bfc0c1b0d7f4d49beb25b2997..fda160c6d94f4babe5257180db769a37aa667537 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js
@@ -2,18 +2,21 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isUnlock = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isUnlock = false;
+
                 return isUnlock;
             }
+
             return isUnlock;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js
index 4b7c4234dd3ede12113f544c9f3c76a3cd72ed41..7531d4fae1aaab06dc14f3ffd611b7bc63508e53 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableButton + ' option[value="0"]').prop('selected', true);
         $target.find('label.enabled').removeClass('enabled');
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js
index b686f1be7c949c484de9f9dc416611c4459fcb2b..1dec21bb5b4931c2109fe2c3ab4adec651c06c3d 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js
@@ -3,8 +3,9 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
-    return function ($target, $owner, data) {
+    'use strict';
+
+    return function ($target) {
         $target.find('.section-config').addClass('enabled');
     };
 });
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js b/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js
index 787d9e066cdbe0234bb434f57d39919d00639181..4f8de68474d7a53dc3af22f5c73c12e4ce28ef98 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js
@@ -3,39 +3,47 @@
  * See COPYING.txt for license details.
  */
 define([
-    "jquery",
-    "uiClass",
-    "Magento_Paypal/js/rule",
-    "mageUtils",
-    "underscore"
+    'jquery',
+    'uiClass',
+    'Magento_Paypal/js/rule',
+    'mageUtils',
+    'underscore'
 ], function ($, Class, Rule, utils, _) {
-    "use strict";
+    'use strict';
+
     return Class.extend({
         defaults: {
+
             /**
              * The event corresponding to the state change
              */
             systemEvent: 'change',
+
             /**
              * The rules applied after the page is loaded
              */
             afterLoadRules: [],
+
             /**
              * An attribute of the element responsible for the activation of the payment method (data attribute)
              */
             enableButton:   '[data-enable="payment"]',
+
             /**
              * An attribute of the element responsible for the activation of the Payflow Express (data attribute)
              */
             enableExpress:  '[data-enable="express"]',
+
             /**
              * An attribute of the element responsible for the activation of the Payflow Bml (data attribute)
              */
             enableBml:      '[data-enable="bml"]',
+
             /**
              * An attribute of the element responsible for the activation of the PayPal Bml (data attribute)
              */
             enableBmlPayPal:      '[data-enable="bml-api"]',
+
             /**
              * Templates element selectors
              */
@@ -43,100 +51,149 @@ define([
                 elementSelector: 'div.section-config tr[id$="${ $.identifier }"]:first'
             }
         },
+
         /**
          * Constructor
+         *
+         * @param {Object} config
+         * @param {String} identifier
+         * @returns {exports.initialize}
          */
         initialize: function (config, identifier) {
             this.initConfig(config);
             this.$self = this.createElement(identifier);
+
             return this;
         },
+
         /**
          * Initialization events
+         *
+         * @returns {exports.initEvents}
          */
         initEvents: function () {
             _.each(this.config.events, function (elementEvents, selector) {
+
                 var solution = this,
                     selectorButton = solution.$self.find(selector),
                     $self = solution.$self,
                     events = elementEvents;
-                selectorButton.on(solution.systemEvent, function (event) {
+
+                selectorButton.on(solution.systemEvent, function () {
                     _.each(events, function (elementEvent, name) {
+
                         var predicate = elementEvent.predicate,
-                            result = true;
+                            result = true,
+
+                            /**
+                             * @param {Function} functionPredicate
+                             */
+                            predicateCallback = function (functionPredicate) {
+                                result = functionPredicate(solution, predicate.message, predicate.argument);
+
+                                if (result) {
+                                    $self.trigger(name);
+                                } else {
+                                    $self.trigger(predicate.event);
+                                }
+                            };
+
                         if (solution.getValue($(this)) === elementEvent.value) {
                             if (predicate.name) {
                                 require([
                                     'Magento_Paypal/js/predicate/' + predicate.name
-                                ], function (functionPredicate) {
-                                    result = functionPredicate(solution, predicate.message, predicate.argument);
-                                    if (result) {
-                                        $self.trigger(name);
-                                    } else {
-                                        $self.trigger(predicate.event);
-                                    }
-                                });
+                                ], predicateCallback);
                             } else {
                                 $self.trigger(name);
                             }
-                            }
+                        }
                     }, this);
-                    });
+                });
             }, this);
+
             return this;
         },
 
+        /**
+         * @param {Object} $element
+         * @returns {*}
+         */
         getValue: function ($element) {
             if ($element.is(':checkbox')) {
                 return $element.prop('checked') ? '1' : '0';
             }
+
             return $element.val();
         },
+
         /**
          * Adding event listeners
+         *
+         * @returns {exports.addListeners}
          */
         addListeners: function () {
+
             _.each(this.config.relations, function (rules, targetName) {
+
                 var $target = this.createElement(targetName);
-                _.each(rules, function (rule, name) {
-                    var handler = new Rule({
-                        name :name,
-                        $target: $target,
-                        $owner: this.$self,
-                        data: {
-                            buttonConfiguration: this.buttonConfiguration,
-                            enableButton: this.enableButton,
-                            enableExpress: this.enableExpress,
-                            enableBml: this.enableBml,
-                            enableBmlPayPal: this.enableBmlPayPal,
-                            solutionsElements: this.solutionsElements,
-                            argument: rule.argument
+
+                _.each(rules, function (instances, instanceName) {
+
+                    _.each(instances, function (instance) {
+                        var handler = new Rule({
+                            name: instanceName,
+                            $target: $target,
+                            $owner: this.$self,
+                            data: {
+                                buttonConfiguration: this.buttonConfiguration,
+                                enableButton: this.enableButton,
+                                enableExpress: this.enableExpress,
+                                enableBml: this.enableBml,
+                                enableBmlPayPal: this.enableBmlPayPal,
+                                solutionsElements: this.solutionsElements,
+                                argument: instance.argument
+                            }
+                        });
+
+                        if (instance.event === ':load') {
+                            this.afterLoadRules.push(handler);
+
+                            return;
                         }
-                    });
-                    if (rule.event === ':load') {
-                        this.afterLoadRules.push(handler);
-                        return;
-                    }
-                    this.$self.on(rule.event, _.bind(handler.apply, handler));
+
+                        this.$self.on(instance.event, _.bind(handler.apply, handler));
+                    }, this);
                 }, this);
             }, this);
+
             return this;
         },
+
         /**
          * Create a jQuery element according to selector
+         *
+         * @param {String} identifier
+         * @returns {*}
          */
         createElement: function (identifier) {
-            if (':self' === identifier) {
+            if (identifier === ':self') {
                 return this.$self;
             }
-            var selector = utils.template(this.templates.elementSelector, {identifier: identifier});
-            return $(selector);
+
+            return $(utils.template(this.templates.elementSelector, {
+                'identifier': identifier
+            }));
         },
+
         /**
          * Assign solutions elements
+         *
+         * @param {Object} elements
+         * @returns {exports.setSolutionsElements}
          */
         setSolutionsElements: function (elements) {
             this.solutionsElements = elements;
+
             return this;
         }
     });
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js b/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js
index b1e124aca387a556069a776721a90d0c529db62a..f92a531e91414da86c78fcc564d8accf96a32191 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js
@@ -3,47 +3,64 @@
  * See COPYING.txt for license details.
  */
 define([
-    "jquery",
-    "uiClass",
-    "Magento_Paypal/js/solution",
-    "underscore"
+    'jquery',
+    'uiClass',
+    'Magento_Paypal/js/solution',
+    'underscore'
 ], function ($, Class, Solution, _) {
-    "use strict";
+    'use strict';
+
     return Class.extend({
         defaults: {
+
             /**
              * Initialized solutions
              */
             solutions: {},
+
             /**
              * The elements of created solutions
              */
             solutionsElements: {},
+
             /**
              * The selector element responsible for configuration of payment method (CSS class)
              */
             buttonConfiguration: '.button.action-configure'
         },
+
         /**
          * Constructor
+         *
+         * @param {Object} config
+         * @returns {exports.initialize}
          */
         initialize: function (config) {
             this.initConfig(config)
                 .initSolutions();
+
             return this;
         },
+
         /**
          * Initialization and configuration solutions
+         *
+         * @returns {exports.initSolutions}
          */
         initSolutions: function () {
             _.each(this.config.solutions, this.addSolution, this);
             this.initializeSolutions()
                 .wipeButtonsConfiguration();
             _.each(this.solutions, this.applicationRules);
+
             return this;
         },
+
         /**
          * The creation and addition of the solution according to the configuration
+         *
+         * @param {Object} solution
+         * @param {String} identifier
          */
         addSolution: function (solution, identifier) {
             this.solutions[identifier] = new Solution({
@@ -52,6 +69,7 @@ define([
             }, identifier);
             this.solutionsElements[identifier] = this.solutions[identifier].$self;
         },
+
         /**
          * Wiping buttons configuration of the payment method
          */
@@ -59,16 +77,22 @@ define([
             $(this.buttonConfiguration).removeClass('disabled')
                 .removeAttr('disabled');
         },
+
         /**
          * Application of the rules
+         *
+         * @param {Object} solution
          */
         applicationRules: function (solution) {
             _.each(solution.afterLoadRules, function (rule) {
                 rule.apply();
             });
         },
+
         /**
          * Initialize solutions
+         *
+         * @returns {exports.initializeSolutions}
          */
         initializeSolutions: function () {
             _.each(this.solutions, function (solution) {
@@ -76,6 +100,7 @@ define([
                     .initEvents()
                     .addListeners();
             }, this);
+
             return this;
         }
     });
diff --git a/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml b/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml
index 892e8771da7dce8e89e43717a2cf0fbfd5f626da..9146130881cabf5d0bd40352950db4b897b58b4a 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml
@@ -84,7 +84,7 @@
                     </strong>
                     <div class="box-content">
                         <address>
-                            <?php /* @noEscape */ echo $block->renderAddress($block->getShippingAddress()); ?>
+                            <?php echo $block->escapeHtml($block->renderAddress($block->getShippingAddress())); ?>
                         </address>
                     </div>
                     <?php if ($block->getCanEditShippingAddress()): ?>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml b/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml
index fa9afa80e5fa8abd356ed6ccfe3d54e80e3638a4..5858917ed8964d3c56b696e78d787f33f411819b 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml
@@ -43,9 +43,7 @@ if ($block->getConfirmationUrl() || $block->getIsInCatalogProduct()) {
     {
         ".paypal-logo.<?php /* @noEscape */ echo $shortcutHtmlId; ?>": {
             "paypalCheckout": {
-                "confirmMessage": "<?php /* @noEscape */ echo $block->escapeJsQuote(
-                        $block->getConfirmationMessage()
-                    ); ?>",
+                "confirmMessage": "<?php /* @noEscape */ echo $block->escapeJsQuote($block->getConfirmationMessage()); ?>",
                 "confirmUrl": "<?php /* @noEscape */ echo !empty($confirmationUrl) ? $confirmationUrl : false; ?>",
                 "isCatalogProduct": "<?php /* @noEscape */ echo !empty($isInCatalogProduct) ?
                         (bool)$isInCatalogProduct : false;
diff --git a/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml b/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml
index 69bf40f9314e3efe35056fa5b0b1bc1915f61c33..c29f82418f83748e61f17632a13f6c891276bf38 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml
@@ -11,7 +11,8 @@
  * @see \Magento\Paypal\Block\Payflow\Link\Info
  */
 ?>
-<div id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none" class="hss items">
+<div id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>"
+     style="display:none" class="hss items">
     <?php echo $block->escapeHtml(__(
         'You will be required to enter your payment details after you place an order.'
     )); ?>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml b/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml
index a11a3786c2c2d9f40e13dddb8b5546c6d546016c..252622af0f40880c76412aa4a06e29d066275e05 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml
@@ -9,7 +9,7 @@
  * @var \Magento\Paypal\Block\Payflow\Advanced\Form $block
  */
 ?>
-<fieldset id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none"
+<fieldset id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>" style="display:none"
           class="fieldset payflowadvanced items redirect">
     <div>
         <?php echo $block->escapeHtml(__('You will be required to enter your payment details after you place an order.')); ?>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml b/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml
index 629141539e2aacd9865c42e85ec04396fc77a999..7296aaabccf4ea15d86f1be1ef07fcf62950b08d 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml
@@ -8,7 +8,7 @@
  * @var \Magento\Paypal\Block\Payflow\Link\Form $block
  */
 ?>
-<div class="payflowlink items" id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>"
+<div class="payflowlink items" id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>"
      style="display:none">
     <?php echo $block->escapeHtml(__('You will be required to enter your payment details after you place an order.'));?>
 </div>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml b/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml
index 834a623d65b3f0b59a37ae59e2cab5e67e3e0695..7eb9423ce3be47a5d0528d786e59d898e0eb5aa3 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml
@@ -8,7 +8,7 @@
 /**
  * @var \Magento\Paypal\Block\Payment\Form\Billing\Agreement $block
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 ?>
 <div class="field items required" id="payment_form_<?php /* @noEscape */ echo $code; ?>" style="display:none;">
     <label for="<?php /* @noEscape */ echo $code; ?>_ba_agreement_id" class="label">
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml b/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml
index 5397d9aba46151905be8f46ee6da030f2567c5eb..b10e2f975964f649791f9c5788d57b76819beb17 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml
@@ -12,7 +12,7 @@
 $code = $block->escapeHtml($block->getBillingAgreementCode());
 ?>
 <fieldset class="fieldset paypal items redirect" style="display:none;"
-          id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>">
+          id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>">
     <div><?php echo $block->escapeHtml($block->getRedirectMessage()); ?></div>
     <?php  ?>
     <?php if ($code): ?>
diff --git a/app/code/Magento/Sales/Model/Order/Payment.php b/app/code/Magento/Sales/Model/Order/Payment.php
index 690bde68d5c575ece27f56d68165d1ccf31bc7d5..83cf0853fdab41721a8bde05cdfc46426fc6cd94 100644
--- a/app/code/Magento/Sales/Model/Order/Payment.php
+++ b/app/code/Magento/Sales/Model/Order/Payment.php
@@ -629,7 +629,7 @@ class Payment extends Info implements OrderPaymentInterface
                     $this->getOrder()->getId()
                 );
                 if ($captureTxn) {
-                    $this->setParentTransactionId($captureTxn->getTxnId());
+                    $this->setTransactionIdsForRefund($captureTxn);
                 }
                 $this->setShouldCloseParentTransaction(true);
                 // TODO: implement multiple refunds per capture
@@ -638,10 +638,7 @@ class Payment extends Info implements OrderPaymentInterface
                         $this->getOrder()->getStoreId()
                     );
                     $this->setRefundTransactionId($invoice->getTransactionId());
-                    $gateway->refund(
-                        $this,
-                        $baseAmountToRefund
-                    );
+                    $gateway->refund($this, $baseAmountToRefund);
 
                     $creditmemo->setTransactionId($this->getLastTransId());
                 } catch (\Magento\Framework\Exception\LocalizedException $e) {
@@ -1263,16 +1260,8 @@ class Payment extends Info implements OrderPaymentInterface
      */
     public function isCaptureFinal($amountToCapture)
     {
-        $amountPaid = $this->formatAmount($this->getBaseAmountPaid(), true);
-        $amountToCapture = $this->formatAmount($amountToCapture, true);
-        $orderGrandTotal = $this->formatAmount($this->getOrder()->getBaseGrandTotal(), true);
-        if ($orderGrandTotal == $amountPaid + $amountToCapture) {
-            if (false !== $this->getShouldCloseParentTransaction()) {
-                $this->setShouldCloseParentTransaction(true);
-            }
-            return true;
-        }
-        return false;
+        $total = $this->getOrder()->getTotalDue();
+        return $this->formatAmount($total, true) == $this->formatAmount($amountToCapture, true);
     }
 
     /**
@@ -2414,5 +2403,24 @@ class Payment extends Info implements OrderPaymentInterface
         return (bool)$this->getData('should_close_parent_transaction');
     }
 
+    /**
+     * Set payment parent transaction id and current transaction id if it not set
+     * @param Transaction $transaction
+     * @return void
+     */
+    private function setTransactionIdsForRefund(Transaction $transaction)
+    {
+        if (!$this->getTransactionId()) {
+            $this->setTransactionId(
+                $this->transactionManager->generateTransactionId(
+                    $this,
+                    Transaction::TYPE_REFUND,
+                    $transaction
+                )
+            );
+        }
+        $this->setParentTransactionId($transaction->getTxnId());
+    }
+
     //@codeCoverageIgnoreEnd
 }
diff --git a/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php b/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php
index 590422b153130b34b55dddb6f1777fd206ec4149..3bb13ccca2bf88b3d99cce521f59e7e0b6fb2126 100644
--- a/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php
+++ b/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php
@@ -37,13 +37,6 @@ class CaptureOperation extends AbstractOperation
         $amountToCapture = $payment->formatAmount($invoice->getBaseGrandTotal());
         $order = $payment->getOrder();
 
-        // prepare parent transaction and its amount
-        $paidWorkaround = 0;
-        if (!$invoice->wasPayCalled()) {
-            $paidWorkaround = (double)$amountToCapture;
-        }
-        $payment->isCaptureFinal($paidWorkaround);
-
         $payment->setTransactionId(
             $this->transactionManager->generateTransactionId(
                 $payment,
@@ -72,38 +65,48 @@ class CaptureOperation extends AbstractOperation
             );
         }
 
-        if (!$invoice->getIsPaid()) {
-            // attempt to capture: this can trigger "is_transaction_pending"
-            $method = $payment->getMethodInstance();
-            $method->setStore(
-                $order->getStoreId()
+        if ($invoice->getIsPaid()) {
+            throw new \Magento\Framework\Exception\LocalizedException(
+                __('The transaction "%1" cannot be captured yet.', $invoice->getTransactionId())
             );
-            //TODO replace for sale usage
-            $method->capture($payment, $amountToCapture);
+        }
+
+        // attempt to capture: this can trigger "is_transaction_pending"
+        $method = $payment->getMethodInstance();
+        $method->setStore(
+            $order->getStoreId()
+        );
+        //TODO replace for sale usage
+        $method->capture($payment, $amountToCapture);
 
-            $transactionBuilder = $this->transactionBuilder->setPayment($payment);
-            $transactionBuilder->setOrder($order);
-            $transactionBuilder->setFailSafe(true);
-            $transactionBuilder->setTransactionId($payment->getTransactionId());
-            $transactionBuilder->setAdditionalInformation($payment->getTransactionAdditionalInfo());
-            $transactionBuilder->setSalesDocument($invoice);
-            $transaction = $transactionBuilder->build(Transaction::TYPE_CAPTURE);
+        // prepare parent transaction and its amount
+        $paidWorkaround = 0;
+        if (!$invoice->wasPayCalled()) {
+            $paidWorkaround = (double)$amountToCapture;
+        }
+        if ($payment->isCaptureFinal($paidWorkaround)) {
+            $payment->setShouldCloseParentTransaction(true);
+        }
 
-            $message = $this->stateCommand->execute($payment, $amountToCapture, $order);
-            if ($payment->getIsTransactionPending()) {
-                $invoice->setIsPaid(false);
-            } else {
-                $invoice->setIsPaid(true);
-                $this->updateTotals($payment, ['base_amount_paid_online' => $amountToCapture]);
-            }
-            $message = $payment->prependMessage($message);
-            $payment->addTransactionCommentsToOrder($transaction, $message);
-            $invoice->setTransactionId($payment->getLastTransId());
+        $transactionBuilder = $this->transactionBuilder->setPayment($payment);
+        $transactionBuilder->setOrder($order);
+        $transactionBuilder->setFailSafe(true);
+        $transactionBuilder->setTransactionId($payment->getTransactionId());
+        $transactionBuilder->setAdditionalInformation($payment->getTransactionAdditionalInfo());
+        $transactionBuilder->setSalesDocument($invoice);
+        $transaction = $transactionBuilder->build(Transaction::TYPE_CAPTURE);
 
-            return $payment;
+        $message = $this->stateCommand->execute($payment, $amountToCapture, $order);
+        if ($payment->getIsTransactionPending()) {
+            $invoice->setIsPaid(false);
+        } else {
+            $invoice->setIsPaid(true);
+            $this->updateTotals($payment, ['base_amount_paid_online' => $amountToCapture]);
         }
-        throw new \Magento\Framework\Exception\LocalizedException(
-            __('The transaction "%1" cannot be captured yet.', $invoice->getTransactionId())
-        );
+        $message = $payment->prependMessage($message);
+        $payment->addTransactionCommentsToOrder($transaction, $message);
+        $invoice->setTransactionId($payment->getLastTransId());
+
+        return $payment;
     }
 }
diff --git a/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php b/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php
index 7c5e892ce035878f1ae41ee5c55d89c0bab8056c..8b7759b79a680079aadee62d56279e59a267cc2d 100644
--- a/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php
+++ b/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php
@@ -44,6 +44,7 @@ class RegisterCaptureNotificationOperation extends AbstractOperation
                 $invoice->setOrder($order);
                 $order->addRelatedObject($invoice);
                 $payment->setCreatedInvoice($invoice);
+                $payment->setShouldCloseParentTransaction(true);
             } else {
                 $payment->setIsFraudDetected(!$skipFraudDetection);
                 $this->updateTotals($payment, ['base_amount_paid_online' => $amount]);
diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php
index 29757fc570f2380410376d09d3ca137062ffad9d..b56c83e38d724a1783f82744e4c53d69846e42d8 100644
--- a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php
+++ b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php
@@ -17,6 +17,8 @@ use Magento\Sales\Model\Order\Payment\Transaction;
  */
 class PaymentTest extends \PHPUnit_Framework_TestCase
 {
+    const TRANSACTION_ID = 'ewr34fM49V0';
+
     private $mockContext;
     /**
      * @var Payment
@@ -166,6 +168,7 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
                     'order',
                     'isInitializeNeeded',
                     'initialize',
+                    'refund'
                 ]
             )
             ->getMock();
@@ -258,7 +261,10 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
                 'register',
                 'addComment',
                 'save',
-                'getGrandTotal'
+                'getGrandTotal',
+                'getBaseGrandTotal',
+                'getDoTransaction',
+                'getInvoice'
             ],
             [],
             '',
@@ -268,7 +274,7 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
         $this->payment = $this->initPayment();
         $this->payment->setMethod('any');
         $this->payment->setOrder($this->orderMock);
-        $this->transactionId = 100;
+        $this->transactionId = self::TRANSACTION_ID;
     }
 
     protected function tearDown()
@@ -825,13 +831,13 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
      */
     protected function mockInvoice($transactionId, $countCall = 1)
     {
-        $this->invoiceMock->expects($this->once())
+        $this->invoiceMock->expects(static::any())
             ->method('getTransactionId')
             ->willReturn($transactionId);
-        $this->invoiceMock->expects($this->once())
+        $this->invoiceMock->expects(static::any())
             ->method('load')
             ->with($transactionId);
-        $this->invoiceMock->expects($this->once())
+        $this->invoiceMock->expects(static::any())
             ->method('getId')
             ->willReturn($transactionId);
         $this->orderMock->expects($this->exactly($countCall))
@@ -1314,7 +1320,8 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
      */
     public function testRegisterRefundNotification()
     {
-        $message = 'Registered notification about refunded amount of . Transaction ID: "100-refund"';
+        $message = 'Registered notification about refunded amount of . Transaction ID: "' .
+            self::TRANSACTION_ID . '-refund"';
         $amount = 50;
         $grandTotalCreditMemo = 50;
         $invoiceBaseGrandTotal = 50;
@@ -1429,6 +1436,73 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($canRefund, $this->payment->canRefund());
     }
 
+    /**
+     * @covers \Magento\Sales\Model\Order\Payment::refund()
+     */
+    public function testRefund()
+    {
+        $amount = 204.04;
+        $this->creditMemoMock->expects(static::once())
+            ->method('getBaseGrandTotal')
+            ->willReturn($amount);
+        $this->creditMemoMock->expects(static::once())
+            ->method('getGrandTotal')
+            ->willReturn($amount);
+        $this->creditMemoMock->expects(static::once())
+            ->method('getDoTransaction')
+            ->willReturn(true);
+
+        $this->paymentMethodMock->expects(static::once())
+            ->method('canRefund')
+            ->willReturn(true);
+
+        $this->mockInvoice(self::TRANSACTION_ID, 0);
+        $this->creditMemoMock->expects(static::once())
+            ->method('getInvoice')
+            ->willReturn($this->invoiceMock);
+
+        $captureTranId = self::TRANSACTION_ID . '-' . Transaction::TYPE_CAPTURE;
+        $captureTransaction = $this->getMockBuilder(Transaction::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['getTxnId'])
+            ->getMock();
+
+        $refundTranId = $captureTranId . '-' . Transaction::TYPE_REFUND;
+        $this->transactionManagerMock->expects(static::once())
+            ->method('generateTransactionId')
+            ->willReturn($refundTranId);
+        $captureTransaction->expects(static::once())
+            ->method('getTxnId')
+            ->willReturn($captureTranId);
+        $this->transactionRepositoryMock->expects(static::once())
+            ->method('getByTransactionId')
+            ->willReturn($captureTransaction);
+
+        $this->paymentMethodMock->expects(static::once())
+            ->method('refund')
+            ->with($this->payment, $amount);
+
+        $isOnline = true;
+        $this->getTransactionBuilderMock([], $isOnline, Transaction::TYPE_REFUND, $refundTranId);
+
+        $this->currencyMock->expects(static::once())
+            ->method('formatTxt')
+            ->willReturn($amount);
+        $this->orderMock->expects(static::once())
+            ->method('getBaseCurrency')
+            ->willReturn($this->currencyMock);
+
+        $status = 'status';
+        $message = 'We refunded ' . $amount . ' online. Transaction ID: "' . $refundTranId . '"';
+        $this->mockGetDefaultStatus(Order::STATE_PROCESSING, $status);
+        $this->assertOrderUpdated(Order::STATE_PROCESSING, $status, $message);
+
+        static::assertSame($this->payment, $this->payment->refund($this->creditMemoMock));
+        static::assertEquals($amount, $this->payment->getData('amount_refunded'));
+        static::assertEquals($amount, $this->payment->getData('base_amount_refunded_online'));
+        static::assertEquals($amount, $this->payment->getData('base_amount_refunded'));
+    }
+
     public function boolProvider()
     {
         return [
@@ -1437,6 +1511,36 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
         ];
     }
 
+    /**
+     * @covers \Magento\Sales\Model\Order\Payment::isCaptureFinal()
+     * @return void
+     */
+    public function testIsCaptureFinal()
+    {
+        $amount = 23.02;
+        $partialAmount = 12.00;
+
+        $this->orderMock->expects(static::exactly(2))
+            ->method('getTotalDue')
+            ->willReturn($amount);
+
+        static::assertFalse($this->payment->isCaptureFinal($partialAmount));
+        static::assertTrue($this->payment->isCaptureFinal($amount));
+    }
+
+    /**
+     * @covers \Magento\Sales\Model\Order\Payment::getShouldCloseParentTransaction()
+     * @return void
+     */
+    public function testGetShouldCloseParentTransaction()
+    {
+        $this->payment->setShouldCloseParentTransaction(1);
+        static::assertTrue($this->payment->getShouldCloseParentTransaction());
+
+        $this->payment->setShouldCloseParentTransaction(0);
+        static::assertFalse($this->payment->getShouldCloseParentTransaction());
+    }
+
     protected function initPayment()
     {
         return (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject(
diff --git a/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml b/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml
index c3ca415c7c2869ffad51232487b894c7599a2f9f..7cffb845b9387b55dbb5d51eb89e8d332ee9b3bb 100644
--- a/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml
+++ b/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml
@@ -20,19 +20,19 @@ if (!$storeCode && $websiteCode) {
     /** @var $web \Magento\Store\Model\Website */
     $web = $block->getWebsiteModel()->load($websiteCode);
     $storedAllowedMethods = explode(',', $web->getConfig('carriers/ups/allowed_methods'));
-    $storedOriginShipment = $web->getConfig('carriers/ups/origin_shipment');
-    $storedFreeShipment   = $web->getConfig('carriers/ups/free_method');
-    $storedUpsType        = $web->getConfig('carriers/ups/type');
+    $storedOriginShipment = $block->escapeHtml($web->getConfig('carriers/ups/origin_shipment'));
+    $storedFreeShipment   = $block->escapeHtml($web->getConfig('carriers/ups/free_method'));
+    $storedUpsType        = $block->escapeHtml($web->getConfig('carriers/ups/type'));
 } elseif ($storeCode) {
     $storedAllowedMethods = explode(',', $block->getConfig('carriers/ups/allowed_methods', $storeCode));
-    $storedOriginShipment = $block->getConfig('carriers/ups/origin_shipment', $storeCode);
-    $storedFreeShipment   = $block->getConfig('carriers/ups/free_method', $storeCode);
-    $storedUpsType        = $block->getConfig('carriers/ups/type', $storeCode);
+    $storedOriginShipment = $block->escapeHtml($block->getConfig('carriers/ups/origin_shipment', $storeCode));
+    $storedFreeShipment   = $block->escapeHtml($block->getConfig('carriers/ups/free_method', $storeCode));
+    $storedUpsType        = $block->escapeHtml($block->getConfig('carriers/ups/type', $storeCode));
 } else {
     $storedAllowedMethods = explode(',', $block->getConfig('carriers/ups/allowed_methods'));
-    $storedOriginShipment = $block->getConfig('carriers/ups/origin_shipment');
-    $storedFreeShipment   = $block->getConfig('carriers/ups/free_method');
-    $storedUpsType        = $block->getConfig('carriers/ups/type');
+    $storedOriginShipment = $block->escapeHtml($block->getConfig('carriers/ups/origin_shipment'));
+    $storedFreeShipment   = $block->escapeHtml($block->getConfig('carriers/ups/free_method'));
+    $storedUpsType        = $block->escapeHtml($block->getConfig('carriers/ups/type'));
 }
 ?>
 <script>
diff --git a/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php b/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php
index 5c27950d64f00760345068372d780397163c04f0..3949117079b68d8ecc8a93bcd86dac4a886b87ce 100644
--- a/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php
+++ b/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php
@@ -8,6 +8,7 @@ return [
     'mc_gross' => '100.00',
     'invoice' => '100000001',
     'payment_status' => 'Completed',
+    'auth_status' => 'Completed',
     'mc_currency' => 'USD',
     'receiver_email' => 'merchant_2012050718_biz@example.com'
 ];
diff --git a/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php b/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php
index cc659a62b1eb2361855aa61bfeb812ff92966c2d..9fbab06028d7988f983157325c5f8e64fdb38eec 100644
--- a/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php
+++ b/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php
@@ -18,30 +18,21 @@ $shippingAddress->setId(null)->setAddressType('shipping');
 $payment = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order\Payment');
 $payment->setMethod(\Magento\Paypal\Model\Config::METHOD_WPP_EXPRESS);
 
-$order = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order');
-$order
-    ->setCustomerEmail('co@co.co')
-    ->setIncrementId(
-    '100000001'
-)->setSubtotal(
-    100
-)->setBaseSubtotal(
-    100
-)->setBaseGrandTotal(
-    100
-)->setBaseCurrencyCode(
-    'USD'
-)->setCustomerIsGuest(
-    true
-)->setStoreId(
-    1
-)->setEmailSent(
-    1
-)->setBillingAddress(
-    $billingAddress
-)->setShippingAddress(
-    $shippingAddress
-)->setPayment(
-    $payment
-);
+$amount = 100;
+
+/** @var \Magento\Sales\Model\Order $order */
+$order = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(Magento\Sales\Model\Order::class);
+$order->setCustomerEmail('co@co.co')
+    ->setIncrementId('100000001')
+    ->setSubtotal($amount)
+    ->setBaseSubtotal($amount)
+    ->setBaseGrandTotal($amount)
+    ->setGrandTotal($amount)
+    ->setBaseCurrencyCode('USD')
+    ->setCustomerIsGuest(true)
+    ->setStoreId(1)
+    ->setEmailSent(true)
+    ->setBillingAddress($billingAddress)
+    ->setShippingAddress($shippingAddress)
+    ->setPayment($payment);
 $order->save();
diff --git a/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php b/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php
index d727bd9fa40598dba7c3cf65330c8da88155d361..95fe57227895b643dd4bbbbdc8596699fb692918 100644
--- a/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php
+++ b/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php
@@ -96,7 +96,7 @@ class AlternativeSource implements AlternativeSourceInterface
         }
 
         try {
-            $this->lockerProcess->lockProcess($this->lockName . sprintf('%x', crc32($path . $content)));
+            $this->lockerProcess->lockProcess($this->lockName);
 
             $module = $chain->getAsset()->getModule();