Refund an order
@param string $purchaseOrderId
@param array $order
@return array
@throws \Exception
482768
public function refund($purchaseOrderId, $order)
    {
        if(!is_numeric($purchaseOrderId)){
            throw new \Exception("purchaseOrderId must be numeric",1448480783);
        }

        $schema = [
            '/orderRefund' => [
                'namespace' => 'ns3',
                'childNamespace' => 'ns3',
            ],
            '/orderRefund/orderLines' => [
                'sendItemsAs' => 'orderLine',
            ],
            '/orderRefund/orderLines/orderLine/refunds' => [
                'sendItemsAs' => 'refund',
            ],
            '/orderRefund/orderLines/orderLine/refunds/refund/refundCharges' => [
                'sendItemsAs' => 'refundCharge',
            ],
            '@namespaces' => [
                'ns3' => 'http://walmart.com/mp/v3/orders'
            ],
        ];

        $a2x = new A2X($order, $schema);
        $xml = $a2x->asXml();

        return $this->refundOrder([
            'purchaseOrderId' => $purchaseOrderId,
            'order' => $xml,
        ]);
    }
135726
public function cancelRecurringPayment($orderId)
    {
        $service = $this->getService();

        $recurringPaymentAction = new Request\Action\RecurringPayment\Cancel($service, $orderId);

        return $recurringPaymentAction->cancel();
    }
767925
public function refund(array $order)
    {
        Datasheet::set($order);
        $param_keys = ['appid', 'mch_id', 'out_trade_no', 'transaction_id', 'out_refund_no',
            'total_fee', 'refund_fee', 'nonce_str'];
        return Helper::request(Helper::GATEWAY_REFUNDORDER, $param_keys, Helper::SSL_VERIFY);
    }
895875
public function refund($oOrder = null, $fPrice, $aRequestParameters = array())
    {
        //Refund ID
        if ($oOrder !== null) {
            $aRequestParameters['refund_amount'] = $fPrice;
            $this->_mapOrderToRequestParameters(
                $oOrder,
                $aRequestParameters,
                array('amazon_capture_id', 'currency_code', 'refund_reference_id', 'seller_refund_note')
            );
        }

        //Make request
        $this->_addSandboxSimulationParams('refund', $aRequestParameters);
        $oData = $this->_convertResponse($this->_getAmazonClient()->refund($aRequestParameters));

        //Update/Insert Refund info
        if ($oData && $oOrder !== null) {
            $sError = '';
            $sAmazonRefundId = '';

            if (isset($oData->Error)) {
                $sState = 'Error';
                $sError = $oData->Error->Message;
            } else {
                $sState = $oData->RefundResult->RefundDetails->RefundStatus->State;
                $sAmazonRefundId = $oData->RefundResult->RefundDetails->AmazonRefundId;
            }

            $sId = $oOrder->getFieldData('bestitamazonorderreferenceid').'_'.$this->getUtilsDate()->getTime();

            $sQuery = "
                INSERT bestitamazonrefunds SET 
                  ID = {$this->getDatabase()->quote($sId)},
                  OXORDERID = {$this->getDatabase()->quote($oOrder->getId())},
                  BESTITAMAZONREFUNDID = {$this->getDatabase()->quote($sAmazonRefundId)},
                  AMOUNT = {$fPrice},
                  STATE = {$this->getDatabase()->quote($sState)},
                  ERROR = {$this->getDatabase()->quote($sError)},
                  TIMESTAMP = NOW()";

            $this->getDatabase()->execute($sQuery);
        }

        return $oData;
    }
1051848
public function cancelPurchase( DirectDebit\Purchase $purchase )
    {
        $purchase->setRequiredFields(array('id','status'));
        $purchase->checkRequiredFields();

        $request = new Request(array(
            'method' => Request::PUT,
            'uri' => $this->prepareURI($this->purchasePath . $this->uriseparator . $purchase->id),
            'body' => $purchase
        ));

        $response = $this->client->processRequest($request);
        return new DirectDebit\Purchase($response);
    }
1279946
final protected function _refund($a) {
		$ii = $this->ii(); /** @var OP $ii */
		/**
		 * 2016-03-17, 2017-11-11
		 * Despite of its name, @uses \Magento\Sales\Model\Order\Payment::getAuthorizationTransaction()
		 * simply returns the previous transaction,
		 * and it can be not only an `authorization` transaction,
		 * but a transaction of another type (e.g. `payment`) too.
		 *		public function getAuthorizationTransaction() {
		 *			return $this->transactionManager->getAuthorizationTransaction(
		 *				$this->getParentTransactionId(),
		 *				$this->getId(),
		 *				$this->getOrder()->getId()
		 *			);
		 *		}
		 * The code is the same in Magento 2.0.0 - 2.2.1:
		 * https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment.php#L1242-#L1253
		 * https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment.php#L1316-L1327
		 * @see \Magento\Sales\Model\Order\Payment\Transaction\Manager::getAuthorizationTransaction()
		 *	public function getAuthorizationTransaction($parentTransactionId, $paymentId, $orderId) {
		 *		$transaction = false;
		 *		if ($parentTransactionId) {
		 *			$transaction = $this->transactionRepository->getByTransactionId(
		 *				$parentTransactionId,
		 *				$paymentId,
		 *				$orderId
		 *			);
		 *		}
		 *		return $transaction ?: $this->transactionRepository->getByTransactionType(
		 *			Transaction::TYPE_AUTH,
		 *			$paymentId,
		 *			$orderId
		 *		);
		 *	}
		 * The code is the same in Magento 2.0.0 - 2.2.1:
		 * https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
		 * https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
		 * It is exactly what we need,
		 * because the module can be set up to capture payments without a preliminary authorization.
		 */
		if ($tPrev = $ii->getAuthorizationTransaction() /** @var T|false $tPrev */) {
			$id = $this->i2e($tPrev->getTxnId()); /** @var string $id */
			// 2016-03-24
			// Credit Memo и Invoice отсутствуют в сценарии Authorize / Capture
			// и присутствуют в сценарии Capture / Refund.
			$cm = $ii->getCreditmemo(); /** @var CM|null $cm */
			$fc = $this->fCharge(); /** @var fCharge $fc */
			$resp = $cm ? $fc->refund($id, $this->amountFormat($a)) : $fc->void($id); /** @var object $resp */
			$this->transInfo($resp);
			$ii->setTransactionId($this->e2i($id, $cm ? Ev::T_REFUND : 'void'));
			if ($cm) {
				/**
				 * 2017-01-19
				 * Записаваем идентификатор операции в БД,
				 * чтобы затем, при обработке оповещений от платёжной системы,
				 * проверять, не было ли это оповещение инициировано нашей же операцией,
				 * и если было, то не обрабатывать его повторно:
				 * @see \Df\Payment\W\Strategy\Refund::_handle()
				 * https://github.com/mage2pro/core/blob/1.12.16/StripeClone/WebhookStrategy/Charge/Refunded.php?ts=4#L21-L23
				 */
				dfp_container_add($this->ii(), self::II_TRANS, fRefund::s($this)->transId($resp));
			}
		}
	}
1039749
public function refundPayment(PayoneRefundTransfer $refundTransfer)
    {
        $payonePaymentTransfer = $refundTransfer->getPayment();

        $paymentEntity = $this->getPaymentEntity($payonePaymentTransfer->getFkSalesOrder());
        $paymentMethodMapper = $this->getPaymentMethodMapper($paymentEntity);
        $requestContainer = $paymentMethodMapper->mapPaymentToRefund($paymentEntity);
        $requestContainer->setAmount(0 - $paymentEntity->getSpyPaymentPayoneDetail()->getAmount());
        $requestContainer = $this->prepareOrderItems($refundTransfer->getOrder(), $requestContainer);
        $requestContainer = $this->prepareOrderShipment($refundTransfer->getOrder(), $requestContainer);
        $requestContainer = $this->prepareOrderDiscount($refundTransfer->getOrder(), $requestContainer);

        $this->setStandardParameter($requestContainer);

        $apiLogEntity = $this->initializeApiLog($paymentEntity, $requestContainer);

        $rawResponse = $this->executionAdapter->sendRequest($requestContainer);
        $responseContainer = new RefundResponseContainer($rawResponse);

        $this->updateApiLogAfterRefund($apiLogEntity, $responseContainer);

        $responseMapper = new RefundResponseMapper();
        $responseTransfer = $responseMapper->getRefundResponseTransfer($responseContainer);

        return $responseTransfer;
    }
695933
public function refund($data = [])
    {
        $resource = "payments/" . urlencode($this->id) . "/refunds";

        $body = null;
        if (count($data) > 0) {
            $body = json_encode($data);
        }

        $result = $this->client->performHttpCall(
            MollieApiClient::HTTP_POST,
            $resource,
            $body
        );

        return ResourceFactory::createFromApiResult(
            $result,
            new Refund($this->client)
        );
    }
38531
public function refund($amount = null)
    {
        return (new ManagementBuilder(TransactionType::REFUND))
            ->withPaymentMethod($this->transactionReference)
            ->withAmount($amount);
    }
704283
public function refundReversal($iOrderNumber, $iCreditNumber)
    {
        $this->_requestData[self::COMMAND] = self::$COMMAND_REFUND_REVERSAL;

        $this->_setField(self::ORDER_NUMBER, $iOrderNumber);
        $this->_setField(self::CREDIT_NUMBER, $iCreditNumber);

        $this->_fingerprintOrder->setOrder(Array(
            self::CUSTOMER_ID,
            self::SHOP_ID,
            self::TOOLKIT_PASSWORD,
            self::SECRET,
            self::COMMAND,
            self::LANGUAGE,
            self::ORDER_NUMBER,
            self::CREDIT_NUMBER
        ));

        return new WirecardCEE_QPay_Response_Toolkit_RefundReversal($this->_send());
    }
774508
def refund(self, idempotency_key=None, **params):
        """"""
        headers = populate_headers(idempotency_key)
        url = self.instance_url() + '/refund'
        d = self.request('post', url, params, headers)
        return d.addCallback(self.refresh_from).addCallback(lambda _: self)
323953
public function purchase(array $productsToBuy, array $productIds, DataBaseExporter $exporter, int $internalOrderId): int
    {
        $preOrdersCount = 0;
        $order = Order::createOrder($productsToBuy, $internalOrderId, true);

        foreach ($order->getProducts() as $product) {
            $numberOfPreOrders = 0;
            $links = [];

            foreach ($product->getCodes() as $code) {

                if ($code->isPreOrder()) {
                    $numberOfPreOrders++;
                    $preOrdersCount++;
                }

                $links[] = $code->getCodeId();
            }

            $orderedCodes = [
                'cwOrderId' => $order->getOrderId(),
                'links' => $links,
                'preOrders' => $numberOfPreOrders
            ];

            $exporter->export(null, $orderedCodes, $productIds[$product->getProductId()], $internalOrderId);
        }

        return $preOrdersCount;
    }
42964
public function refund($guid, Amount $refundAmount) {
        return new Transaction(
            $this->client->post('transactions/' . $guid . '/refunds', ["amount" => $refundAmount])
        );
    }
112618
def refund_transaction(options = {})
      @logger.debug("[refund_transaction] options=#{options.inspect}")

      validate_refund_transaction_params!(options)

      response = execute_request(:refund_info, options)
      unless response.refundable?
        raise NonRefundableTransactionException, options[:transaction_id]
      end

      # Pick maximum refundable amount if amount is not supplied.
      options[:amount] = response.maximum_amount unless options[:amount]

      # Fill required parameters with data from refund info request.
      options.merge!(
        payment_method: response.payment_method,
        invoicenumber: response.invoicenumber,
        currency: response.currency
      )

      execute_request(:refund_transaction, options)
    end
668040
public function PaymentOrderCancel($paymentOrderId, $amount, $currency)
    {
        $request = new Request();
        $request->setMethod('POST');

        foreach (array('paymentOrderId', 'amount', 'currency') as $param) {
            if (null == $$param) {
                throw new InvalidArgumentException($param);
            }
        }

        $params = array(
            'PaymentOrderId' => $paymentOrderId,
            'CancelAmount'   => $amount,
            'Currency'       => $currency
        );

        $request->setContent(json_encode($params));

        return $this->doRequest('PaymentOrder/Cancel', $request)->getContentJson();
    }
1322670
public function saveTransactionRef($orderId, $transactionRef)
    {
        try {
            $orderId = \intval($orderId);

            if (null !== $order = $this->getOrder($orderId)) {
                $event = new OrderEvent($order);

                $event->setTransactionRef($transactionRef);

                $this->dispatch(TheliaEvents::ORDER_UPDATE_TRANSACTION_REF, $event);

                $this->getLog()->addInfo(
                    $this->getTranslator()->trans(
                        "Payment transaction %transaction_ref for order ref. %ref, ID %id has been successfully saved.",
                        [
                            '%transaction_ref' => $transactionRef,
                            '%ref' => $order->getRef(),
                            '%id' => $order->getId()
                        ]
                    )
                );
            }
        } catch (\Exception $ex) {
            $this->getLog()->addError(
                $this->getTranslator()->trans(
                    "Error occurred while saving payment transaction %transaction_ref for order ID %id.",
                    [
                        '%transaction_ref' => $transactionRef,
                        '%id' => $orderId
                    ]
                )
            );

            throw $ex;
        }
    }
135442
public static function isAllowedSum($order, $sumReturn)
	{
		$returnsBefore = PayReturn::whereOrderId($order->id)->get();
		$sumOldReturn = 0;
		foreach ($returnsBefore as $one) {
			$sumOldReturn += $one->sum;
		}
		$possibleReturn = $order->sum - $sumOldReturn;

		return $sumReturn <= $possibleReturn;
	}