Load transaction for direct payment and create refund payment.

@param int $tranId
@param \Magento\Sales\Model\Order $sale
@throws \Exception
191863
private function refundByTransaction(
        $tranId,
        \Magento\Sales\Model\Order $sale
    ) {
        $saleId = $sale->getId();
        $saleIncId = $sale->getIncrementId();
        /** @var ETrans $transaction */
        $transaction = $this->daoTrans->getById($tranId);
        $accIdCust = $transaction->getDebitAccId();
        $accIdSys = $transaction->getCreditAccId();
        $amount = $transaction->getValue();
        $note = "Refund for sale #$saleIncId";
        $operId = $this->createOperation($accIdSys, $accIdCust, $amount, $note);
        $this->logger->info("Refund operation #$operId is created for sale #$saleIncId/$saleId");
    }
298736
public function processPaypalSale(Transaction $transaction, $delivery=null, $credtCard=null)
    {
        
        $totals = $this->calculateTotals($transaction, $delivery);
  
        $this->paypalToken();
        
        if(is_null($credtCard)){
            $paymentMehod = array("payment_method" => "paypal");
        }else{
            $paymentMehod = array(
            "payment_method" => "credit_card",
            "funding_instruments" => array(
                array(
                  "credit_card" => $credtCard
                )
              )
            );
        }
        
        $returnValues = array();
        foreach ($transaction->getItems() as $productPurchase) {
            $sub = array();
            $sub['quantity'] = $productPurchase->getQuantity();
            if($productPurchase->getProduct() instanceof Product){
                $sub['name'] = $productPurchase->getProduct()->getName();
                $sub['price'] = number_format($productPurchase->getProduct()->getPrice(), 2);
            }elseif($productPurchase->getAdvert() instanceof Advert){
                $sub['name'] = $productPurchase->getAdvert()->getTitle();
                $sub['price'] = number_format($this->advertUnitPrice, 2);
            }
            
            $sub['sku'] = $productPurchase->getId();
            $sub['currency'] = "EUR";
            $returnValues[] = $sub;
        }
        
        $host = $this->paypalFactory->getHost();
        $url = $host.'/v1/payments/payment';
        $payment = array(
                        'intent' => 'sale',
                        'payer' => $paymentMehod,
                        'transactions' => array (array(
                                        'amount' => array(
                                                'total' => number_format($totals['amount'], 2),
                                                'currency' => 'EUR',
                                                'details' =>  array(
                                                    "subtotal" => number_format($totals['amount_clean'], 2),
                                                    "tax" => number_format($totals['vat'], 2),
                                                    "shipping" => $totals['delivery_expenses']
                                                  )
                                                ),
                                        'description' => 'payment using a PayPal account',
                                        "item_list" => array (
                                                "items" => $returnValues
                                                ),
                                        )),
                        'redirect_urls' => array (
                                'return_url' => $this->paypalFactory->getReturnUrl(),
                                'cancel_url' => $this->paypalFactory->getCancelUrl()
                        )
                    );

        $json = json_encode($payment);
        $json_resp = $this->paypalCall('POST', $url, $json);
               
        if(!is_null($credtCard)){
            if($json_resp['state'] == 'approved'){
                 //UPDATE TRANSACTION
                $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('paypal-direct-payment');
                $transaction->setStatus(Transaction::STATUS_PAID);
                $transaction->setPaymentMethod($pm);
                $transaction->setPaymentDetails(json_encode($json_resp));
                $this->manager->persist($transaction);
                $this->manager->flush();
                
                //confirmation payment
                $answer = new \stdClass();
                $answer->redirectUrl = $this->router->generate('ecommerce_checkout_confirmationpayment');

                return $answer;
            }else{
                //cancel payment
                $answer = new \stdClass();
                $answer->redirectUrl = $this->paypalFactory->getCancelUrl();

                return $answer;
            }
        }else{
            //UPDATE TRANSACTION
            $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('paypal');
            $transaction->setStatus(Transaction::STATUS_PENDING);
            $transaction->setPaymentMethod($pm);
            $transaction->setPaymentDetails(json_encode($json_resp));
            $this->manager->persist($transaction);
            $this->manager->flush();


            foreach ($json_resp['links'] as $link) {
                    if($link['rel'] == 'execute'){
                            $payment_execute_url = $link['href'];
                            $payment_execute_method = $link['method'];
                    }elseif($link['rel'] == 'approval_url'){
                            $payment_approval_url = $link['href'];
                            $payment_approval_method = $link['method'];
                    }
            }

            $answer = new \stdClass();
            $answer->redirectUrl = $payment_approval_url;

            return $answer;
        }
        
    }
1133647
protected function getPayment(OrderTransfer $orderTransfer)
    {
        $payment = $this->queryContainer->createPaymentByOrderId($orderTransfer->getIdSalesOrder())->findOne();
        $paymentDetail = $payment->getSpyPaymentPayoneDetail();

        $paymentDetailTransfer = new PaymentDetailTransfer();
        $paymentDetailTransfer->fromArray($paymentDetail->toArray(), true);

        $paymentTransfer = new PayonePaymentTransfer();
        $paymentTransfer->fromArray($payment->toArray(), true);
        $paymentTransfer->setPaymentDetail($paymentDetailTransfer);

        return $paymentTransfer;
    }
928338
public function createSale(Sale $sale){

        $uri = Braspag::$apiBase . 'sales'; 

        $request = json_encode($sale, JSON_UNESCAPED_UNICODE);
        
        $response = Request::post($uri)
            ->sendsJson()
            ->addHeaders($this->headers)
            ->body($request)            
            ->send();
        
        if($response->code == HttpStatus::Created){            
            $responsePayment = $response->body->Payment;

            $sale->payment->paymentId = $responsePayment->PaymentId;
            $sale->payment->status = $responsePayment->Status;
            $sale->payment->reasonCode = $responsePayment->ReasonCode;
            $sale->payment->reasonMessage = $responsePayment->ReasonMessage;
            $sale->payment->currency = $responsePayment->Currency;
            $sale->payment->country = $responsePayment->Country;
            $sale->payment->receivedDate = Utils::getResponseValue($responsePayment, 'ReceivedDate');
            $sale->capturedDate = Utils::getResponseValue($responsePayment, 'CapturedDate');
            $sale->voidedDate = Utils::getResponseValue($responsePayment, 'VoidedDate');
            $sale->capturedAmount = Utils::getResponseValue($responsePayment, 'CapturedAmount');
            $sale->capturedAmount = Utils::getResponseValue($responsePayment, 'VoidedAmount');
            $sale->payment->providerReturnCode = Utils::getResponseValue($responsePayment, 'ProviderReturnCode');
            $sale->payment->providerReturnMessage = Utils::getResponseValue($responsePayment, 'ProviderReturnMessage');
            
            if($responsePayment->Type == 'CreditCard' || $responsePayment->Type == 'DebitCard'){
                $sale->payment->authenticationUrl = Utils::getResponseValue($responsePayment, 'AuthenticationUrl');
                $sale->payment->authorizationCode = Utils::getResponseValue($responsePayment, 'AuthorizationCode');
                $sale->payment->acquirerTransactionId = Utils::getResponseValue($responsePayment, 'AcquirerTransactionId');
                $sale->payment->proofOfSale = Utils::getResponseValue($responsePayment, 'ProofOfSale');
				$sale->payment->creditCard = Utils::getResponseValue($responsePayment, 'CreditCard');

                if(Utils::getResponseValue($responsePayment, 'FraudAnalysis') != null){
                    $antiFraudResponse = Utils::getResponseValue($responsePayment, 'FraudAnalysis');

                    $replyData = new FraudAnalysisReplyData();
                    $replyData->addressInfoCode = Utils::getResponseValue($antiFraudResponse->ReplyData, 'AddressInfoCode');
                    $replyData->factorCode = Utils::getResponseValue($antiFraudResponse->ReplyData, 'FactorCode');
                    $replyData->score = Utils::getResponseValue($antiFraudResponse->ReplyData, 'Score');
                    $replyData->binCountry = Utils::getResponseValue($antiFraudResponse->ReplyData, 'BinCountry');
                    $replyData->cardIssuer = Utils::getResponseValue($antiFraudResponse->ReplyData, 'CardIssuer');
                    $replyData->cardScheme = Utils::getResponseValue($antiFraudResponse->ReplyData, 'CardScheme');
                    $replyData->hostSeverity = Utils::getResponseValue($antiFraudResponse->ReplyData, 'HostSeverity');
                    $replyData->internetInfoCode = Utils::getResponseValue($antiFraudResponse->ReplyData, 'InternetInfoCode');
                    $replyData->ipRoutingMethod = Utils::getResponseValue($antiFraudResponse->ReplyData, 'IpRoutingMethod');
                    $replyData->scoreModelUsed = Utils::getResponseValue($antiFraudResponse->ReplyData, 'ScoreModelUsed');
                    $replyData->casePriority = Utils::getResponseValue($antiFraudResponse->ReplyData, 'CasePriority');

                    $sale->payment->fraudAnalysis->status = $antiFraudResponse->Status;

                    $sale->payment->fraudAnalysis->replyData = $replyData;
                }

            }elseif($response->body->Payment->Type == 'Boleto'){
                $sale->payment->url = Utils::getResponseValue($responsePayment, 'Url');
                $sale->payment->barCodeNumber = Utils::getResponseValue($responsePayment, 'BarCodeNumber');
                $sale->payment->digitableLine = Utils::getResponseValue($responsePayment, 'DigitableLine');
                $sale->payment->boletoNumber = Utils::getResponseValue($responsePayment, 'BoletoNumber');

            }elseif($response->body->Payment->Type == 'EletronicTransfer'){    
                $sale->payment->url = Utils::getResponseValue($responsePayment, 'Url');                

            }            

            $recurrentResponse = Utils::getResponseValue($responsePayment, 'RecurrentPayment');

            if($recurrentResponse != null){
                $sale->payment->recurrentPayment->recurrentPaymentId = Utils::getResponseValue($recurrentResponse, 'RecurrentPaymentId');
                $sale->payment->recurrentPayment->reasonCode = $recurrentResponse->ReasonCode;
                $sale->payment->recurrentPayment->reasonMessage = $recurrentResponse->ReasonMessage;
                $sale->payment->recurrentPayment->nextRecurrency = Utils::getResponseValue($recurrentResponse, 'NextRecurrency');
                $sale->payment->recurrentPayment->startDate = Utils::getResponseValue($recurrentResponse, 'StartDate');
                $sale->payment->recurrentPayment->endDate = Utils::getResponseValue($recurrentResponse, 'EndDate');
                $sale->payment->recurrentPayment->interval = Utils::getResponseValue($recurrentResponse, 'Interval');
                $sale->payment->recurrentPayment->link = $this->parseLink(Utils::getResponseValue($recurrentResponse, 'Link'));
            }

            $sale->payment->links = $this->parseLinks($response->body->Payment->Links);
            
            return $sale;
        }elseif($response->code == HttpStatus::BadRequest){          
            Utils::handleApiError($response);             
        }  
        
        return $response->code;
    }
397783
protected function loadOrderPayment($transactionId)
    {
        $orderPayment = oxNew(\OxidEsales\PayPalModule\Model\OrderPayment::class);
        $orderPayment->loadByTransactionId($transactionId);

        return $orderPayment;
    }
62256
public function addTransaction(TPkgShopPaymentTransactionData $transactionData)
    {
        $transactionData->checkRequirements();

        $sTransactionType = $transactionData->getType();
        $amount = $transactionData->getTotalValue();
        $oContext = $transactionData->getContext();
        $iSequenceNumber = $transactionData->getSequenceNumber();

        $oTransactionType = $this->getTransactionTypeObject($sTransactionType);

        if (null === $iSequenceNumber) {
            $iSequenceNumber = $this->getNextTransactionSequenceNumber();
        }
        if (self::TRANSACTION_TYPE_CREDIT == $sTransactionType || self::TRANSACTION_TYPE_PAYMENT_REVERSAL === $sTransactionType) {
            $amount = -1 * $amount;
        }
        $aData = array(
            'shop_order_id' => $this->order->id,
            'data_extranet_user_id' => (null !== $oContext->getExtranetUser()) ? ($oContext->getExtranetUser(
            )->id) : (''),
            'cms_user_id' => (null !== $oContext->getCmsUser()) ? ($oContext->getCmsUser()->id) : (''),
            'datecreated' => date('Y-m-d H:i:s'),
            'ip' => $oContext->getIp(),
            'amount' => $amount,
            'context' => $oContext->getContext(),
            'pkg_shop_payment_transaction_type_id' => $oTransactionType->id,
            'sequence_number' => $iSequenceNumber,
            'confirmed' => '0',
        );

        $oTransaction = TdbPkgShopPaymentTransaction::GetNewInstance($aData);

        $oTransaction->AllowEditByAll(true);
        $oTransaction->SaveFieldsFast($aData);
        $oTransaction->AllowEditByAll(false);

        // add items
        $aItems = $transactionData->getItems();
        /** @var TPkgShopPaymentTransactionItemData $oItem */
        $itemAmountMultiplier = 1;
        if (self::TRANSACTION_TYPE_CREDIT == $sTransactionType || self::TRANSACTION_TYPE_PAYMENT_REVERSAL === $sTransactionType) {
            $itemAmountMultiplier = -1;
        }

        foreach ($aItems as $oItem) {
            $aData = array(
                'pkg_shop_payment_transaction_id' => $oTransaction->id,
                'amount' => ($itemAmountMultiplier * $oItem->getAmount()),
                'value' => $oItem->getValue(),
                'shop_order_item_id' => $oItem->getOrderItemId(),
                'type' => $oItem->getType(),
            );
            $oTransactionPosition = TdbPkgShopPaymentTransactionPosition::GetNewInstance($aData);
            $oTransactionPosition->AllowEditByAll(true);
            $oTransactionPosition->SaveFieldsFast($aData);
        }

        if (true === $transactionData->getConfirmed()) {
            $this->confirmTransaction($iSequenceNumber, $transactionData->getConfirmedTimestamp());
        }

        return $oTransaction;
    }
736057
public function updatePaymentDetail(PaymentDetailTransfer $paymentDataTransfer, $idOrder)
    {
        $paymentEntity = $this->queryContainer->createPaymentByOrderId($idOrder)->findOne();
        $paymentDetailEntity = $paymentEntity->getSpyPaymentPayoneDetail();

        $paymentDetailEntity->fromArray($paymentDataTransfer->toArray());

        $paymentDetailEntity->save();
    }
1055529
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $details = ArrayObject::ensureArrayObject($request->getModel());

        $this->gateway->execute(new RefundTransaction($details));
    }
179652
public function createTransactionStatusLogsBySalesOrder($idIdSalesOrder)
    {
        $query = $this->getFactory()->createPaymentPayoneTransactionStatusLogQuery()
            ->useSpyPaymentPayoneQuery()
            ->filterByFkSalesOrder($idIdSalesOrder)
            ->endUse()
            ->orderByCreatedAt();

        return $query;
    }
808429
public function refundByTransactionId(
        $orderNo,
        $refundNo,
        $totalFee,
        $refundFee = null,
        $opUserId = null,
        $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS'
    ) {
        return $this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, self::TRANSACTION_ID, $refundAccount);
    }
1339746
private function createOrderInvoice($order, $transactionId, $amount)
    {
        if ($order->getTotalInvoiced() + $amount == $order->getGrandTotal()) {
            $invoice = $this->invoiceService->prepareInvoice($order);
        } else {
            $invoice = $this->invoiceService->prepareInvoiceWithoutItems($order, $amount);
        }

        $invoice->setRequestedCaptureCase(Invoice::CAPTURE_OFFLINE);
        $invoice->setTransactionId($transactionId);
        $invoice->setBaseGrandTotal($amount);
        $invoice->setGrandTotal($amount);
        $invoice->register();
        $invoice->save();

        $order->addRelatedObject($invoice);

        if (!$invoice->getEmailSent()) {
            $this->invoiceSender->send($invoice);
        }

        //Add notification comment to order
        $order->addStatusHistoryComment(
            __('Invoice #%1 is created. Notification email is sent to customer.', $invoice->getId())
        )->setIsCustomerNotified(true)->save();

        return $invoice;
    }
426308
def execute_transaction(t, header: nil, block_info: nil, ignore_exception: false)
      unless state.find_account(t.sender).balance >= t.gas_price * t.gas_limit + t.value
        raise InvalidTransaction.new('account balance not enough')
      end

      # remove gas fee from account balance
      state.add_balance(t.sender, -1 * t.gas_limit * t.gas_price)

      intrinsic_gas = fork_schema.intrinsic_gas_of_transaction(t)
      if intrinsic_gas > t.gas_limit
        raise InvalidTransaction.new('intrinsic gas overflowed gas limit')
      end

      gas_limit = t.gas_limit - intrinsic_gas

      instruction = Instruction.new(
        origin: t.sender,
        price: t.gas_price,
        sender: t.sender,
        value: t.value,
        header: header,
      )

      if t.contract_creation?
        instruction.bytes_code = t.data
      else
        instruction.bytes_code = get_account_code(t.to)
        instruction.address = t.to
        instruction.data = t.data
      end

      block_info ||= header && BlockInfo.from_header(header)
      context = Ciri::EVM::ExecutionContext.new(
        instruction: instruction, gas_limit: gas_limit,
        block_info: block_info, fork_schema: fork_schema
      )
      vm = Ciri::EVM::VM.new(state: state, chain: @chain, burn_gas_on_exception: true)

      unless instruction.value > state.find_account(instruction.sender).balance
        state.increment_nonce(instruction.sender)
      end

      vm.with_context(context) do
        if t.contract_creation?
          # contract creation
          vm.create_contract(context: context)
        else
          vm.call_message(context: context)
        end
        raise context.exception if !ignore_exception && context.exception

        # refund gas
        sub_state_refund_gas = fork_schema.calculate_refund_gas(vm)
        context.refund_gas(sub_state_refund_gas)
        refund_gas = context.reset_refund_gas
        remain_gas = context.remain_gas
        actually_gas_used = t.gas_limit - remain_gas
        actually_refund_gas = [refund_gas, actually_gas_used / 2].min
        refund_gas_amount = (actually_refund_gas + remain_gas) * t.gas_price
        debug("Transaction refund #{refund_gas_amount} to #{t.sender.to_s.hex}")
        state.add_balance(t.sender, refund_gas_amount)

        # gas_used after refund gas
        gas_used = actually_gas_used - actually_refund_gas

        # miner fee
        fee = gas_used * t.gas_price
        debug("Transaction fee #{fee}")
        miner_account = find_account(block_info.coinbase)
        miner_account.balance += fee
        state.set_balance(block_info.coinbase, miner_account.balance)

        # EIP158 fork, we need to delete miner account if account become empty
        vm.sub_state.add_touched_account(block_info.coinbase)
        vm.delete_empty_accounts

        # destroy accounts
        vm.execution_context.all_suicide_accounts.each do |address|
          state.set_balance(address, 0)
          state.delete_account(address)
        end

        ExecutionResult.new(status: context.status, state_root: state_root, logs: context.all_log_series,
                            gas_used: gas_used, gas_price: t.gas_price, exception: context.exception,
                            output: context.output)
      end
    end
1008035
def create_refund(self, data=None, **params):
        """"""
        if data is None:
            data = {'lines': []}
        refund = OrderRefunds(self.client).on(self).create(data, **params)
        return refund
1046657
public function refundOrder(Order $order, $currency, array $params = [])
    {
        $params['currency'] = $currency;

        $this->postAndMap($order->getResourcePath().'/refund', $params, 'toOrder', $order);
    }
562835
public RefundQuery refundQueryByTransactionId(String transactionId) {
        RefundQueryRequestWrapper refundQueryRequestWrapper = new RefundQueryRequestWrapper();
        refundQueryRequestWrapper.setTransactionId(transactionId);
        return refundQuery(refundQueryRequestWrapper);
    }
666908
function create($txn = true) {
		if ($txn && !($txn instanceof pq\Transaction)) {
			$txn = $this->table->getConnection()->startTransaction();
		}
		try {
			foreach ($this->rows as $row) {
				$row->create();
			}
		} catch (\Exception $e) {
			if ($txn) {
				$txn->rollback();
			}
			throw $e;
		}
		if ($txn) {
			$txn->commit();
		}
		return $this;
	}
360239
public void setTransactionID(byte[] tranID) throws StunException {
		if (tranID == null || (tranID.length != TRANSACTION_ID_LENGTH && tranID.length != RFC3489_TRANSACTION_ID_LENGTH))
			throw new StunException(StunException.ILLEGAL_ARGUMENT, "Invalid transaction id length");

		int tranIDLength = tranID.length;
		this.transactionID = new byte[tranIDLength];
		System.arraycopy(tranID, 0, this.transactionID, 0, tranIDLength);
	}