Возврат средств

@param int    $provider_id
@param string $bill_id
@param int    $refund_id

@internal param int $id

@return Response
160195
public function update($provider_id, $bill_id, $refund_id)
	{
		$bill = Bill::getBill($bill_id, $provider_id);
		//Проверяем наличие счёта
		if (!$bill) {
			$data['error'] = Catalog::C_BILL_NOT_FOUND;

			return $this->responseFromGate($data);
		}

		//Проверяем refund_id на уникальность в этом счёте
		if (Refund::isRefundExist($bill_id, $refund_id)) {
			$data['error'] = Catalog::C_BILL_ALREADY_EXIST;

			return $this->responseFromGate($data);
		}

		//Проверяем статус
		if (!$bill->isPaid()) {
			$data['error'] = Catalog::C_BILL_NOT_FOUND;

			return $this->responseFromGate($data);
		}

		//Проверяем запрошенную сумму для отмены
		$amountQuery = Input::get('amount');
		$validator = Validator::make(
			array('amount' => $amountQuery),
			Validators::rulesForRefundBill()
		);
		if (!$validator->passes()) {
			$data['error'] = Catalog::C_WRONG_FORMAT;

			return $this->responseFromGate($data);
		}

		//Вычисляем сууму для возврата
		$refundAmount = Refunds::calculateAmount($bill, $amountQuery);

		$data = array(
			'bill_id'   => $bill_id,
			'refund_id' => $refund_id,
			'amount'    => $refundAmount,
			'status'    => 'processing',
		);
		Refunds::NewRefund($data);
		$data['user'] = $bill->user;
		$data['error'] = Catalog::C_WITHOUT_ERRORS;

		return $this->responseFromGate($data);

	}
258260
function _doRefund($oID, $amount = 'Full', $note = '') {
    global $db, $doPayPal, $messageStack;
    $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_REFUNDED_STATUS_ID;
    $orig_order_amount = 0;
    $doPayPal = $this->paypal_init();
    $proceedToRefund = false;
    $refundNote = strip_tags(zen_db_input($_POST['refnote']));
    if (isset($_POST['fullrefund']) && $_POST['fullrefund'] == MODULE_PAYMENT_PAYPAL_ENTRY_REFUND_BUTTON_TEXT_FULL) {
      $refundAmt = 'Full';
      if (isset($_POST['reffullconfirm']) && $_POST['reffullconfirm'] == 'on') {
        $proceedToRefund = true;
      } else {
        $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_REFUND_FULL_CONFIRM_ERROR, 'error');
      }
    }
    if (isset($_POST['partialrefund']) && $_POST['partialrefund'] == MODULE_PAYMENT_PAYPAL_ENTRY_REFUND_BUTTON_TEXT_PARTIAL) {
      $refundAmt = (float)$_POST['refamt'];
      $proceedToRefund = true;
      if ($refundAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_INVALID_REFUND_AMOUNT, 'error');
        $proceedToRefund = false;
      }
    }

    // look up history on this order from PayPal table
    $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID  AND parent_txn_id = '' ";
    $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
    $zc_ppHist = $db->Execute($sql);
    if ($zc_ppHist->RecordCount() == 0) return false;
    $txnID = $zc_ppHist->fields['txn_id'];
    $curCode = $zc_ppHist->fields['mc_currency'];
    $PFamt = $zc_ppHist->fields['mc_gross'];
    if ($doPayPal->_mode == 'payflow' && $refundAmt == 'Full') $refundAmt = $PFamt;

    /**
     * Submit refund request to PayPal
     */
    if ($proceedToRefund) {
       $response = $doPayPal->RefundTransaction($oID, $txnID, $refundAmt, $refundNote, $curCode);
      $error = $this->_errorHandler($response, 'DoRefund');
      $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
      if (!$error) {
        if (!isset($response['GROSSREFUNDAMT'])) $response['GROSSREFUNDAMT'] = $refundAmt;
        // Success, so save the results
        $sql_data_array = array('orders_id' => $oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'REFUND INITIATED. Trans ID:' . $response['REFUNDTRANSACTIONID'] . $response['PNREF']. "\n" . /*' Net Refund Amt:' . urldecode($response['NETREFUNDAMT']) . "\n" . ' Fee Refund Amt: ' . urldecode($response['FEEREFUNDAMT']) . "\n" . */' Gross Refund Amt: ' . urldecode($response['GROSSREFUNDAMT']) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $refundNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_REFUND_INITIATED, urldecode($response['GROSSREFUNDAMT']), urldecode($response['REFUNDTRANSACTIONID']). $response['PNREF']), 'success');
        return true;
      }
    }
  }
744258
protected static function deletePaymentTokenByIdAsyncWithHttpInfo($payment_token_id) 
    {
        $returnType = '';  
        $request = self::deletePaymentTokenByIdRequest($payment_token_id); 

        return self::getHttpClient()
            ->sendAsync($request, self::createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        $response->getBody()
                    );
                }
            );
    }
49140
public static function calculateAmount($bill, $amountQuery)
	{
		//Берём общую сумму счёта
		$amountBill = $bill->amount;
		//Берём суммы прошлых возвратов
		$refundsBefore = Refund::whereBillId($bill->bill_id)->get();
		$amount_refund = 0;
		foreach ($refundsBefore as $one) {
			$amount_refund += $one->amount;
		}
		//Вычисляем возможную сумму возвтрата и отдаём её
		$rest = $amountBill - $amount_refund;
		$amount = ($amountQuery > $rest)
			? $rest
			: $amountQuery;

		return $amount;
	}
115850
def refund(self, callerReference, transactionId, refundAmount=None,
               callerDescription=None):
        
        params = {}
        params['CallerReference'] = callerReference
        params['TransactionId'] = transactionId
        if(refundAmount != None):
            params['RefundAmount'] = refundAmount
        if(callerDescription != None):
            params['CallerDescription'] = callerDescription
        
        response = self.make_request("Refund", params)
        body = response.read()
        if(response.status == 200):
            rs = ResultSet()
            h = handler.XmlHandler(rs, self)
            xml.sax.parseString(body, h)
            return rs
        else:
            raise FPSResponseError(response.status, response.reason, body)
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;
    }
615030
public function recordRefund(string $id, array $data, array $headers = [])
    {
        $url = $this->url('invoices/%s/record_refund', $id);

        return $this->post($url, $data, $headers);
    }
1350413
public function cancelRefund($refundID, $paymentID)
    {
        $obj = new stdClass();

        // Must be in specific order for checksum --
        $obj->Secret = $this->getSecretCode();
        $obj->MerchantID = $this->getMerchantID();
        $obj->Timestamp = $this->getTimeStamp();
        $obj->RefundID = $refundID;
        $obj->PaymentID = $paymentID;
        // -----------------------------------------  
        // Generate Checksum
        $obj->Checksum = $this->generateChecksum($obj);

        // Ask for cancelRefunt and get response
        $result = $this->client->CancelRefund($obj);
        $result = $result->CancelRefundResult;

        $obj->Timestamp = $result->Timestamp;
        $obj->Success = $result->Success;

        // Unset properties for new Checksum
        unset($obj->RefundID, $obj->PaymentID, $obj->Checksum);

        // Verify response data by making a new Checksum
        $Checksum = $this->generateChecksum($obj);

        // Compare Checksums
        if ($result->Checksum != $Checksum)
            throw new Exception('Data could not be verified');

        return (array) $result;
    }
562835
public RefundQuery refundQueryByTransactionId(String transactionId) {
        RefundQueryRequestWrapper refundQueryRequestWrapper = new RefundQueryRequestWrapper();
        refundQueryRequestWrapper.setTransactionId(transactionId);
        return refundQuery(refundQueryRequestWrapper);
    }
821643
public function refund($options, $refund_amount = null)
    {
        if (!is_array($options)) $options = ['out_trade_no' => $options, 'refund_amount' => $refund_amount];
        $this->options->set('method', 'alipay.trade.refund');
        return $this->getResult($options);
    }
170072
public function queryRefund($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->request(self::API_QUERY_REFUND, $params);
    }
136804
public function update($provider_id, $bill_id)
	{
		//Если это создание - счёта отправляем на создание
		if ($this->isCreateBill()) {
			return $this->store($provider_id, $bill_id);
		}

		if ($this->isCancelBill()) {
			//Находим счёт
			$bill = Bill::getBill($bill_id, $provider_id);
			//Если не нашли - ошибка "Счёт не найден"
			if ($bill == null) {
				$data['error'] = Catalog::C_BILL_NOT_FOUND;

				return $this->responseFromGate($data);
			}
			//Если статус waiting - отменяем счёт, кидаем callback и отдаём счёт в ответе
			if ($bill->isWaiting() && $bill->doCancel($bill_id)) {

				$this->sendCallback($bill_id);
				$canceledBill = Bill::whereBillId($bill_id)->first();
				$data = $this->dataFromObj($canceledBill);
				$data['error'] = 0;

				return $this->responseFromGate($data);
			}

			$data['error'] = Catalog::C_BILL_NOT_FOUND;

			return $this->responseFromGate($data);
		}

		return null;

	}
377010
protected function linkProvider($user_id, $provider, $provider_id, $access_token)
	{
		$user_provider = new Provider;
		$user_provider->user_id = $user_id;
		$user_provider->provider = strtolower($provider);
		$user_provider->provider_id = $provider_id;
		$user_provider->access_token = $access_token;
		$user_provider->save();
		
		return $user_provider;
	}
972985
function _doRefund($oID, $amount = 0) {
    global $db, $messageStack;
    $new_order_status = (int)MODULE_PAYMENT_AUTHORIZENET_ECHECK_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_AUTHORIZENET_ECHECK_TEXT_REFUND_CONFIRM_ERROR, 'error');
      $proceedToRefund = false;
    }
    if (isset($_POST['buttonrefund']) && $_POST['buttonrefund'] == MODULE_PAYMENT_AUTHORIZENET_ECHECK_ENTRY_REFUND_BUTTON_TEXT) {
      $refundAmt = (float)$_POST['refamt'];
      $new_order_status = (int)MODULE_PAYMENT_AUTHORIZENET_ECHECK_REFUNDED_ORDER_STATUS_ID;
      if ($refundAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_INVALID_REFUND_AMOUNT, 'error');
        $proceedToRefund = false;
      }
    }
    if (isset($_POST['cc_number']) && trim($_POST['cc_number']) == '') {
      $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_CC_NUM_REQUIRED_ERROR, 'error');
    }
    if (isset($_POST['trans_id']) && trim($_POST['trans_id']) == '') {
      $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_TRANS_ID_REQUIRED_ERROR, 'error');
      $proceedToRefund = false;
    }

    /**
     * Submit refund request to gateway
     */
    if ($proceedToRefund) {
      $submit_data = array('x_type' => 'CREDIT',
                           'x_card_num' => trim($_POST['cc_number']),
                           'x_amount' => number_format($refundAmt, 2),
                           'x_trans_id' => trim($_POST['trans_id'])
                           );
      unset($response);
      $response = $this->_sendRequest($submit_data);
      $response_code = $response[0];
      $response_text = $response[3];
      $response_alert = $response_text . ($this->commError == '' ? '' : ' Communications Error - Please notify webmaster.');
      $this->reportable_submit_data['Note'] = $refundNote;
      $this->_debugActions($response);

      if ($response_code != '1') {
        $messageStack->add_session($response_alert, 'error');
      } else {
        // Success, so save the results
        $sql_data_array = array('orders_id' => $oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'REFUND INITIATED. Trans ID:' . $response[6] . ' ' . $response[4]. "\n" . ' Gross Refund Amt: ' . $response[9] . "\n" . $refundNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_REFUND_INITIATED, $response[9], $response[6]), 'success');
        return true;
      }
    }
    return false;
  }
890193
public function deleteRefund($transaction_id)
    {
        $response = $this->client->delete('transactions/refunds/' . $transaction_id);
        return json_decode($response->getBody())->refund;
    }
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;
	}
439160
public function refund($id, $amount, $reason = null)
	{
		$data = new OrderUnitRefundTransfer();
		$data->amount = $amount;
		if (null !== $reason) {
			$data->reason = $reason;
		}

		$endpoint = new Refund($this->getTransport());
		$endpoint->setId($id);
		$endpoint->setTransfer($data);

		try {
			$result = $endpoint->performRequest();
		} catch (ResourceNotFoundException $e) {
			return false;
		}

		return $result['status'] == 204;
	}