refund a charge
@param RequestModels\ChargeRefund $requestModel
@return ResponseModels\Charge
481225
public function refundCardChargeRequest(RequestModels\ChargeRefund
	                                        $requestModel)
	{

		$chargeMapper = new ChargesMapper($requestModel);

		$requestPayload = array (
			'authorization' => $this->_apiSetting->getSecretKey(),
			'mode'          => $this->_apiSetting->getMode(),
			'postedParam'   => $chargeMapper->requestPayloadConverter(),

		);
		$refundUri = sprintf ($this->_apiUrl->getChargeRefundsApiUri(),$requestModel->getChargeId());

		$processCharge = \com\checkout\helpers\ApiHttpClient::postRequest($refundUri,
			$this->_apiSetting->getSecretKey(),$requestPayload);

		$responseModel = new ResponseModels\Charge($processCharge);


		return $responseModel;
	}
599819
public function refund($params, $opts = null)
    {
        $url = self::classUrl() . '/' . $this->instanceId() . "/refund";
        list($resp, $usedOpts) = self::request(self::METHOD_POST, $url, $params, $opts);
        $this->install($resp, $usedOpts);
        return $this;
    }
914204
private function requestRefund($config)
    {
        \PagSeguro\Configuration\Configure::setEnvironment(
            $this->_library->getEnvironment()
        );
        try {
            return \PagSeguro\Services\Transactions\Refund::create(
                $this->_library->getPagSeguroCredentials(),
                $config->pagseguro_id,
                $config->value
            );
        } catch (\Exception $exception) {
            throw $exception;
        }
    }
259390
public function refund($order): Collection
    {
        $this->payload = Support::filterPayload($this->payload, $order, true);

        Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Refund', $this->gateway, $this->payload));

        return Support::requestApi(
            'secapi/pay/refund',
            $this->payload,
            true
        );
    }
1118631
def refund_payment(self):
        
        Money = MoneyMaker(self.currency)
        filter_kwargs = {
            'transaction_id__startswith': 'ch_',
            'payment_method': StripePayment.namespace,
        }
        for payment in self.orderpayment_set.filter(**filter_kwargs):
            refund = stripe.Refund.create(charge=payment.transaction_id)
            if refund['status'] == 'succeeded':
                amount = Money(refund['amount']) / Money.subunits
                OrderPayment.objects.create(order=self, amount=-amount, transaction_id=refund['id'],
                                            payment_method=StripePayment.namespace)

        del self.amount_paid  # to invalidate the cache
        if self.amount_paid:
            # proceed with other payment service providers
            super(OrderWorkflowMixin, self).refund_payment()
873342
public function refund($amount, $reference, array $options = [])
    {
        $url = sprintf($this->gateway->buildUrlFromString('charges').'/%s/refund', $reference);

        return $this->gateway->commit('post', $url, [
            'amount'      => $this->gateway->amount($amount),
            'description' => Arr::get($options, 'description'),
        ]);
    }
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;
    }
721937
protected function prepareRefundRequest($request, string $reference): RequestInterface
    {
        /** @var AbstractRequest $refundRequest */
        $refundRequest = $this->gateway()->refund($request);
        $refundRequest->setTransactionReference($reference);

        return $refundRequest;

    }
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));
			}
		}
	}
38531
public function refund($amount = null)
    {
        return (new ManagementBuilder(TransactionType::REFUND))
            ->withPaymentMethod($this->transactionReference)
            ->withAmount($amount);
    }
3218
public function getRefund(CardPayments\Refund $refund)
    {
        $refund->setRequiredFields(array('id'));
        $refund->checkRequiredFields();

        $request = new Request(array(
             'method' => Request::GET,
             'uri' => $this->prepareURI("/refunds/" . $refund->id)
        ));

        $response = $this->client->processRequest($request);
        return new CardPayments\Refund($response);
    }
41970
public function refunds()
    {
        if (!isset($this->_links->refunds->href)) {
            return new RefundCollection($this->client, 0, null);
        }

        $result = $this->client->performHttpCallToFullUrl(MollieApiClient::HTTP_GET, $this->_links->refunds->href);

        return ResourceFactory::createCursorResourceCollection(
            $this->client,
            $result->_embedded->refunds,
            Refund::class,
            $result->_links
        );
    }
1396
public function doneAction(Request $request)
    {
        $debug = $this->container->getParameter('kernel.debug');

        $token = $this->getHttpRequestVerifier()->verify($request);

        $gateway = $this->getPayum()->getGateway($token->getGatewayName());

        $gateway->execute($done = new Done($token));

        if (!$debug) {
            $this->getHttpRequestVerifier()->invalidate($token);
        }

        /** @var \Ekyna\Component\Sale\Payment\PaymentInterface $payment */
        $payment = $done->getFirstModel();

        $event = new PaymentEvent($payment);
        $this->getDispatcher()->dispatch(PaymentEvents::DONE, $event);
        if (null !== $response = $event->getResponse()) {
            return $response;
        }

        if ($debug) {
            return $this->render('EkynaPaymentBundle:Payment:done.html.twig', [
                'payment' => $payment,
            ]);
        }

        return $this->redirect('/');
    }
1318296
public function refund($charge, array $options = []): StripeRefund
    {
        $options['charge'] = $charge;

        return StripeRefund::create($options, ['api_key' => $this->getStripeKey()]);
    }
53329
public function getRefundResult()
    {
        $responseVariables = get_object_vars($this->getResponse());
        if (!array_key_exists('refundResult', $responseVariables)) {
            return new RefundResult();
        }
        $refundResult = $responseVariables['refundResult'];
        if (!($refundResult instanceof RefundResult)) {
            return new RefundResult();
        }
        return $refundResult;
    }
889466
public function newPaymentAction(Request $request)
    {
        $context = $this->loadContext($request);
        /** @var \Ekyna\Component\Sale\Order\OrderInterface $order */
        $order = $context->getResource();

        $this->isGranted('EDIT', $order);

        $redirectPath = $this->generateResourcePath($order);

        $amount = $this
            ->get('ekyna_order.order.calculator')
            ->calculateOrderRemainingTotal($order)
        ;
        if (0 >= $amount) {
            $this->addFlash('ekyna_order.order.message.already_paid', 'info');
            return $this->redirect($redirectPath);
        }

        $paymentClass = $this->container->getParameter('ekyna_order.order_payment.class');
        /** @var \Ekyna\Component\Sale\Order\OrderPaymentInterface $payment */
        $payment = new $paymentClass;
        $payment
            ->setOrder($order)
            ->setAmount($amount)
        ;

        $action = $this->generateUrl(
            'ekyna_order_order_admin_payment_new',
            ['orderId' => $payment->getOrder()->getId()]
        );
        $form = $this->createPaymentForm($payment, $action, $redirectPath);

        $form->handleRequest($request);
        if ($form->isValid()) {
            $order->addPayment($payment);

            $event = new OrderEvent($order);
            $this->get('event_dispatcher')->dispatch(OrderEvents::CONTENT_CHANGE, $event);
            if (!$event->isPropagationStopped()) {
                return $this->redirect($redirectPath);
            }
        }

        $this->appendBreadcrumb(
            'order-payment-new',
            'ekyna_order.payment.button.new'
        );

        return $this->render('EkynaOrderBundle:Admin/Order/Payment:new.html.twig', [
            'form' => $form->createView(),
            'form_template' => 'EkynaOrderBundle:Admin/Order/Payment:_form.html.twig',
            'order' => $order,
        ]);
    }
1356290
public function getTotalRefund()
    {
        //filter by customer id
        $customerOrders = $this->orderCollection->create()
            ->addAttributeToFilter('customer_id', $this->model->getId());

        $totalRefunded = 0;
        //calculate total refunded
        foreach ($customerOrders as $order) {
            $refunded = $order->getTotalRefunded();
            $totalRefunded += $refunded;
        }

        return $totalRefunded;
    }