Used to submit a refund for a given transaction.
545795
function _doRefund($oID, $amount = 0) {
    global $db, $messageStack;
    $_POST['refamt'] = preg_replace('/[^0-9.%]/', '', $_POST['refamt']);
    $new_order_status = (int)MODULE_PAYMENT_LINKPOINT_API_REFUNDED_ORDER_STATUS_ID;
    if ($new_order_status == 0) $new_order_status = 1;
    $proceedToRefund = true;
    $refundNote = strip_tags(zen_db_input($_POST['refnote']));
    if (isset($_POST['refconfirm']) && $_POST['refconfirm'] != 'on') {
      $messageStack->add_session(MODULE_PAYMENT_LINKPOINT_API_TEXT_REFUND_CONFIRM_ERROR, 'error');
      $proceedToRefund = false;
    }
    if (isset($_POST['buttonrefund']) && $_POST['buttonrefund'] == MODULE_PAYMENT_LINKPOINT_API_ENTRY_REFUND_BUTTON_TEXT) {
      $refundAmt = (float)$_POST['refamt'];
      $new_order_status = (int)MODULE_PAYMENT_LINKPOINT_API_REFUNDED_ORDER_STATUS_ID;
      if ($refundAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_LINKPOINT_API_TEXT_INVALID_REFUND_AMOUNT, 'error');
        $proceedToRefund = false;
      }
    }
    if (isset($_POST['cc_number']) && (int)trim($_POST['cc_number']) == 0) {
      $messageStack->add_session(MODULE_PAYMENT_LINKPOINT_API_TEXT_CC_NUM_REQUIRED_ERROR, 'error');
    }
    if (isset($_POST['trans_id']) && (int)trim($_POST['trans_id']) == 0) {
      $messageStack->add_session(MODULE_PAYMENT_LINKPOINT_API_TEXT_TRANS_ID_REQUIRED_ERROR, 'error');
      $proceedToRefund = false;
    }

    $sql = "select lp_trans_num, transaction_time from " . TABLE_LINKPOINT_API . " where order_id = " . (int)$oID . " and transaction_result = 'APPROVED' order by transaction_time DESC";
    $query = $db->Execute($sql);
    if ($query->RecordCount() < 1) {
      $messageStack->add_session(MODULE_PAYMENT_LINKPOINT_API_TEXT_NO_MATCHING_ORDER_FOUND, 'error');
      $proceedToRefund = false;
    }
    /**
     * Submit refund request to gateway
     */
    if ($proceedToRefund) {
      unset($myorder);
      $myorder["ordertype"] = 'CREDIT';
      $myorder["oid"] = $query->fields['lp_trans_num'];
      if ($_POST['trans_id'] != '') $myorder["tdate"] = $_POST['trans_id'];
      $myorder["chargetotal"] = number_format($refundAmt, 2, '.', '');
      $myorder["comments"]  = htmlentities($refundNote, ENT_QUOTES, 'UTF-8');

      $result = $this->_sendRequest($myorder);
      $response_alert = $result['r_approved'] . ' ' . $result['r_error'] . ($this->commError == '' ? '' : ' Communications Error - Please notify webmaster.');
      $this->reportable_submit_data['Note'] = $refundNote;
      $failure = ($result["r_approved"] != "APPROVED");
      if ($failure) {
        $messageStack->add_session($response_alert, 'error');
      } else {
        // Success, so save the results
        $this->_updateOrderStatus($oID, $new_order_status, 'REFUND INITIATED. Order ID:' . $result['r_ordernum'] . ' - ' . 'Trans ID: ' . $result['r_tdate'] . "\n" . 'Amount: ' . $myorder["chargetotal"] . "\n" . $refundNote);
        $messageStack->add_session(sprintf(MODULE_PAYMENT_LINKPOINT_API_TEXT_REFUND_INITIATED, $result['r_tdate'], $result['r_ordernum']), 'success');
        return true;
      }
    }
    return false;
  }
782599
def refund(refund)
      unless @is_valid
        return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), RefundResponse)
      end

      begin
        url = @web_url + Constants::TRANSACTION_METHOD

        request = Message::RefundProcess::RefundMsgProcess.create_request(refund)
        response = Message::RefundProcess::RefundMsgProcess.send_request(url, @api_key, @password, @version, request)
        Message::RefundProcess::RefundMsgProcess.make_result(response)
      rescue => e
        @logger.error(e.to_s) if @logger
        make_response_with_exception(e, RefundResponse)
      end
    end
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));
			}
		}
	}
794013
def transaction_error_code(self):
        """"""
        error = self.response_doc.find('transaction_error')
        if error is not None:
            code = error.find('error_code')
            if code is not None:
                return code.text
1252276
public function refund()
    {
        if (!userHasPermission('admin:invoice:payment:refund')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        $oUri          = Factory::service('Uri');
        $oInput        = Factory::service('Input');
        $oPaymentModel = Factory::model('Payment', 'nails/module-invoice');
        $iPaymentId    = $oUri->segment(5);
        $sAmount       = $oInput->post('amount') ?: null;
        $sReason       = $oInput->post('reason') ?: null;
        $sRedirect     = urldecode($oInput->post('return_to')) ?: 'invoice/payment/view/' . $iPaymentId;

        try {

            $oPayment = $oPaymentModel->getById($iPaymentId);
            if (empty($oPaymentModel)) {
                throw new NailsException('Invalid payment ID.');
            }

            // --------------------------------------------------------------------------

            //  Convert the amount to its smallest unit
            $iAmount = intval($sAmount * pow(10, $oPayment->currency->decimal_precision));

            // --------------------------------------------------------------------------

            if (!$oPaymentModel->refund($iPaymentId, $iAmount, $sReason)) {
                throw new NailsException('Failed to refund payment. ' . $oPaymentModel->lastError(), 1);
            }

            $sStatus  = 'success';
            $sMessage = 'Payment refunded successfully.';

        } catch (NailsException $e) {
            $sStatus  = 'error';
            $sMessage = $e->getMessage();
        }

        $oSession = Factory::service('Session', 'nails/module-auth');
        $oSession->setFlashData($sStatus, $sMessage);
        redirect($sRedirect);
    }
757657
function refundPayment(id, callback) {
    var client = new this.clients.Payments();
    client.refund(id, callback);
  }
586834
def submit(cls, client, direction, legs, price, quantity, time_in_force,
               trigger, order_type, run_validations=True):
        '''
        
        '''

        if run_validations:
            assert(direction in ["debit", "credit"])
            assert(type(price) is str)
            assert(type(quantity) is int)
            assert(time_in_force in ["gfd", "gtc"])
            assert(trigger in ["immediate"])
            assert(order_type in ["limit", "market"])
            assert(cls._validate_legs(legs) is True)

        payload = json.dumps({
            "account": client.account_url,
            "direction": direction,
            "legs": legs,
            "price": price,
            "quantity": quantity,
            "time_in_force": time_in_force,
            "trigger": trigger,
            "type": order_type,
            "override_day_trade_checks": False,
            "override_dtbp_checks": False,
            "ref_id": str(uuid.uuid4())
        })

        request_url = "https://api.robinhood.com/options/orders/"
        data = client.post(request_url, payload=payload)
        return data
461578
public function create($orderId, Refund &$refund)
    {
        $data = $refund->exportData();
        $endpoint = '/admin/orders/'.$orderId.'/refunds.json';
        $response = $this->request(
            $endpoint, 'POST', array(
            'refund' => $data
            )
        );
        $refund->setData($response['refund']);
    }
772995
def send_response(self, transaction):
        
        if transaction.cacheHit is False:
            """
            handling response based on the code
            """
            logger.debug("handling response")
            self._handle_response(transaction)
        return transaction
472034
def post_transaction(self, transaction, mode):
        """"""
        if not mode or mode not in self.mode_list:
            raise ValidationError('Mode must be one of the following {}.'
                                  .format(', '.join(self.mode_list)))

        tx_dict = transaction.tx_dict if transaction.tx_dict else transaction.to_dict()
        payload = {
            'method': mode,
            'jsonrpc': '2.0',
            'params': [encode_transaction(tx_dict)],
            'id': str(uuid4())
        }
        # TODO: handle connection errors!
        return requests.post(self.endpoint, json=payload)
1297305
@RequestMapping("/apply")
    @ResponseBody
    public RefundApplyResponse apply(@RequestParam("orderNumber") String orderNumber){
        return wepaySupport.refundApply(orderNumber);
    }
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;
    }
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)
1295395
public static void rollback()
   {
      try {
         if (userTransaction.getStatus() != Status.STATUS_NO_TRANSACTION) {
            userTransaction.rollback();
         }
         else {
            LOGGER.warn("Request to rollback transaction when none was in started.");
         }
      }
      catch (Exception e) {
         LOGGER.warn("Transaction rollback failed.", e);
      }
   }
2258
def refund(options = {})
      response = JSON.parse(@client.patch("items/#{send(:id)}/refund", options).body)
      @attributes = response['items']
      true
    end
426345
private function doRefund($refund)
    {
        /** @var Refund $refund */
        $refund = ClassValidator::getInstance('Eway\Rapid\Model\Refund', $refund);

        return $this->getHttpService()->postTransactionRefund($refund->Refund->TransactionID, $refund->toArray());
    }
816227
def show_refund(self, refund_id):
        """"""
        request = self._get('transactions/refunds/' + str(refund_id))
        return self.responder(request)