Submit purchase
@param \Paysafe\DirectDebit\Purchase $purchase
@return \Paysafe\DirectDebit\Purchase
@throws PaysafeException
357479
public function submit( DirectDebit\Purchase $purchase )
    {
        if (isset($purchase->ach))
        {
            $return = $this->submitPurchaseACH($purchase);
        } else if (isset($purchase->eft))
        {
            $return = $this->submitPurchaseEFT($purchase);
        } else if (isset($purchase->bacs))
        {
            $return = $this->submitPurchaseBACS($purchase);
        } else if (isset($purchase->sepa))
        {
            $return = $this->submitPurchaseSEPA($purchase);
        }
        return $return;
    }
1287668
function authorize($token, $buyOrder, $gracePeriod, $idQueryShare, $deferredPeriodIndex) {

        try {

            $authorize = new authorize();

            $wsCompletePaymentTypeInput = new wsCompletePaymentTypeInput();
            $wsCompleteQueryShareInput = new wsCompleteQueryShareInput();

            $authorize->token = $token;

            $wsCompletePaymentTypeInput->buyOrder = $buyOrder;
            $wsCompletePaymentTypeInput->commerceCode = $this->config->getCommerceCode();
            $wsCompletePaymentTypeInput->gracePeriod = $gracePeriod; //Si se quiere período de gracia dejar en true

            $wsCompleteQueryShareInput->idQueryShare = $idQueryShare;

			if ($deferredPeriodIndex != 0) {
				$wsCompleteQueryShareInput->deferredPeriodIndex = $deferredPeriodIndex;
			}

            $wsCompletePaymentTypeInput->queryShareInput = $wsCompleteQueryShareInput;
            $authorize->paymentTypeList = $wsCompletePaymentTypeInput;

            $authorizeResponse = $this->_authorize($authorize);

            $xmlResponse = $this->soapClient->__getLastResponse();
            $soapValidation = new SoapValidation($xmlResponse, $this->config->getWebpayCert());
            $validationResult = $soapValidation->getValidationResult();

            if ($validationResult === TRUE) {

                /** Indica a Webpay que se ha recibido conforme el resultado de la transacción */
                if ($this->acknowledgeCompleteTransaction($token)) {

                    $wsCompleteAuthorizeOutput = $authorizeResponse->return;
                    return $wsCompleteAuthorizeOutput;

                } else {

                    $error["error"] = "Error validando conexi&oacute;n a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";
                    $error["detail"] = "No se pudo completar la conexi&oacute;n con Webpay";
                }
            }
        } catch (Exception $e) {

            $error["error"] = "Error conectando a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";

            $replaceArray = array('<!--' => '', '-->' => '');
            $error["detail"] = str_replace(array_keys($replaceArray), array_values($replaceArray), $e->getMessage());
        }

        return $error;
    }
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");
    }
34776
public function create($payment, $paymentId = null)
    {
        if (isset($paymentId)) {
            return $this->client()->put($payment, 'payments/{paymentId}', ['paymentId' => $paymentId]);
        }

        return $this->client()->post($payment, 'payments');
    }
213831
public function place_orderAction()
    {
        $session = $this->getRequest()->getSession();

        $orderCollection = $this->getRepo('OrderCollection')
            ->find($session->get('cart_id'));

        $orderCollection->place();

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($orderCollection);
        $em->flush();

        return $this->redirect($this->generateUrl('Buyer_checkout_receipt'));
    }
433324
public static function createBuy($id, $userContact, $taxSystem, $paymentAddress=null)
    {
        return new static($id, $userContact, static::INTENT_BUY, $taxSystem, $paymentAddress);
    }
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;
    }
524636
def purchase!(payment: 'none', provider: 'none', card: 'none', email: true, skip_buyer_validations: false)
      return false if purchased?
      error = nil

      assign_attributes(
        state: EffectiveOrders::PURCHASED,
        purchased_at: Time.zone.now,
        payment: payment_to_h(payment),
        payment_provider: provider,
        payment_card: (card.presence || 'none'),
        skip_buyer_validations: skip_buyer_validations
      )

      Effective::Order.transaction do
        begin
          run_purchasable_callbacks(:before_purchase)
          save!
          update_purchasables_purchased_order!
        rescue => e
          self.state = state_was
          self.purchased_at = nil

          error = e.message
          raise ::ActiveRecord::Rollback
        end
      end

      raise "Failed to purchase order: #{error || errors.full_messages.to_sentence}" unless error.nil?

      send_order_receipts! if email

      run_purchasable_callbacks(:after_purchase)

      true
    end
644676
def get_purchase(self, purchase_id, purchase_key='sid'):
        
        data = {'purchase_id': purchase_id,
                'purchase_key': purchase_key}
        return self.api_get('purchase', data)
950790
public function purchase($email, array $items, $incomplete = null, $message_id = null, array $options = [ ]) {
        $data = $options;
        $data['email'] = $email;
        $data['items'] = $items;
        if (!is_null($incomplete)) {
            $data['incomplete'] = (int) $incomplete;
        }
        if (!is_null($message_id)) {
            $data['message_id'] = $message_id;
        }
        return $this->apiPost('purchase', $data);
    }
545533
public function capture($transactionId, $amount = null, $gratuity = null, $clientTransactionId = null, $directMarketData = null)
    {
        $xml = new DOMDocument();
        $hpsTransaction = $xml->createElement('hps:Transaction');
        $hpsCreditAddToBatch = $xml->createElement('hps:CreditAddToBatch');

        $hpsCreditAddToBatch->appendChild($xml->createElement('hps:GatewayTxnId', $transactionId));
        if ($amount != null) {
            $amount = sprintf("%0.2f", round($amount, 3));
            $hpsCreditAddToBatch->appendChild($xml->createElement('hps:Amt', $amount));
        }
        if ($gratuity != null) {
            $hpsCreditAddToBatch->appendChild($xml->createElement('hps:GratuityAmtInfo', $gratuity));
        }

        if ($directMarketData != null && $directMarketData->invoiceNumber != null) {
            $hpsCreditAddToBatch->appendChild($this->_hydrateDirectMarketData($directMarketData, $xml));
        }

        $hpsTransaction->appendChild($hpsCreditAddToBatch);
        $options = array();
        if ($clientTransactionId != null) {
            $options['clientTransactionId'] = $clientTransactionId;
        }
        $response = $this->doRequest($hpsTransaction, $options);
        $this->_processChargeGatewayResponse($response, 'CreditAddToBatch');

        return $this->get($transactionId);
    }
1029817
private function createEditForm(Contract $entity)
    {
        $form = $this->createForm(new ContractType(), $entity, array(
            'action' => $this->generateUrl('ecommerce_contract_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

//        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
256561
public function addTransactionDetail($amount, $buyOrder, $commerceCode = null)
    {
        $detail = new TransactionDetail();
        $detail->amount = $amount;
        $detail->buyOrder = $buyOrder;
        $detail->commerceCode = $commerceCode ? $commerceCode : SecurityHelper::getCommonName(
            $this->service->getCertificationBag()->getClientCertificate()
        );
        $this->transactionDetails[] = $detail;

        return $this;
    }
564064
public function postDispatched(Request $request)
    {
        $purchase = Purchase::findOrFail($request->input('purchase_id'));

        if ($purchase->item->seller->userId != Auth::user()->userId) {
            return redirect('/inventory/sold')->withErrors(["You are not seller of this item."]);
        }

        if ($purchase->isDispatched()) {
            return redirect('/inventory/sold')->withErrors(["This item has already been marked as dispatched."]);
        }

        if (!$purchase->deliveryOption) {
            return redirect('/inventory/sold')->withErrors(["This item is due to be collected."]);
        }

        $purchase->dispatched = time();
        $purchase->trackingNumber = $request->input('tracking_number');

        $purchase->save();

        $purchase->buyer->sendEmail(
            'Your item has been dispatched',
            'emails.item.dispatched',
            [
                'item_name' => $purchase->item->name,
                'delivery_service' => $purchase->deliveryOption->name,
                'tracking_number' => $purchase->trackingNumber,
                'arrival_time' => $purchase->deliveryOption->humanArrivalTime,
            ]
        );

        return redirect('/inventory/sold')->withStatus("This item has been marked as dispatched and the buyer notified.");
    }
1050249
public function createBuy(Buy $buy, array $params = [])
    {
        $this->getClient()->createAccountBuy($this, $buy, $params);
    }
1122564
public function getPay($purchaseId)
    {
        $purchase = Purchase::findOrFail($purchaseId);

        if ($purchase->buyer->userId != Auth::user()->userId) {
            return redirect('/inventory/bought')->withErrors([
                "You are not the buyer of this item."
            ]);
        }

        if ($purchase->isPaid()) {
            return redirect('/inventory/bought')->withStatus(
                'You have already successfully paid for this item.'
            );
        }

        return view('mustard::purchase.pay', [
            'purchase' => $purchase,
        ]);
    }
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;
        }
        
    }