Transacts the given transaction

@param \Orkestra\Transactor\Entity\Transaction $transaction
@param array                                   $options

@return \Orkestra\Transactor\Entity\Result
977962
protected function doTransact(Transaction $transaction, array $options = array())
    {
        $this->validateTransaction($transaction);
        $params = $this->buildParams($transaction, $options);
        $result = $transaction->getResult();
        $result->setTransactor($this);

        $postUrl = $options['post_url'];
        $client = $this->getClient();

        $request = $client->post($postUrl)
            ->addPostFields($params);

        try {
            $response = $request->send();
            $data = array();
            parse_str($response->getBody(true), $data);
        } catch (BadResponseException $e) {
            $data = array(
                'response' => '3',
                'message' => $e->getMessage()
            );
        }

        if (empty($data['response']) || '1' != $data['response']) {
            $result->setStatus(new Result\ResultStatus((!empty($data['response']) && '2' == $data['response']) ? Result\ResultStatus::DECLINED : Result\ResultStatus::ERROR));
            $result->setMessage(empty($data['responsetext']) ? 'An error occurred while processing the payment. Please try again.' : $data['responsetext']);

            if (!empty($data['transactionid'])) {
                $result->setExternalId($data['transactionid']);
            }
        } else {
            $result->setStatus(new Result\ResultStatus(Result\ResultStatus::APPROVED));
            $result->setExternalId($data['transactionid']);
        }

        $result->setData('request', $params);
        $result->setData('response', $data);

        return $result;
    }
7494
public function authorize($money, Merchant_Billing_CreditCard $creditcard, $options = array())
  {
      $this->required_options('customer_email', $options);
      $this->build_xml($money, 'PreAuth', $creditcard, $options);

      return $this->commit();
  }
139418
public function send(TransactionInterface $transaction)
    {
        return $this->requestFactory->create(
            static::transformRequest($transaction),
            [],
            $this->httpClient,
            $this->loop
        )->then(function (ResponseInterface $response) {
            return \React\Promise\resolve(static::transformResponse($response));
        });
    }
534516
protected function doTransact(Transaction $transaction, array $options = array())
    {
        $this->validateTransaction($transaction);
        $params = $this->buildParams($transaction, $options);

        $result = $transaction->getResult();
        $result->setTransactor($this);

        $postUrl = $options['post_url'];
        $client = $this->getClient();

        $request = $client->post($postUrl)
            ->addPostFields($params);

        try {
            $response = $request->send();

            $data = Transaction\TransactionType::QUERY !== $transaction->getType()->getValue()
                ? json_decode($response->getBody(true))
                : $this->normalizeQueryResponse($response->getBody(true));
        } catch (BadResponseException $e) {
            $data = new \stdClass();
            $data->CommandStatus = 'Error';
            $data->Description = 'Client Error';
            $data->ErrorInformation = 'An error occurred while contacting the PaymentsXpress system';
            $data->Exception = $e->getMessage();
        }

        if ('Approved' !== $data->CommandStatus) {
            $result->setStatus(new Result\ResultStatus('Declined' !== $data->CommandStatus ? Result\ResultStatus::ERROR : Result\ResultStatus::DECLINED));
            $result->setMessage(!empty($data->ErrorInformation) ? $data->Description . ': ' . $data->ErrorInformation : $data->Description);

            if (!empty($data->TransAct_ReferenceID)) {
                $result->setExternalId($data->TransAct_ReferenceID);
            }
        } else {
            if (Transaction\TransactionType::QUERY === $transaction->getType()->getValue()) {
                $this->handleQueryResponse($transaction, $data);
            } else {
                $result->setStatus(new Result\ResultStatus(Result\ResultStatus::PENDING));
            }

            $result->setExternalId($data->TransAct_ReferenceID);
        }

        $result->setData('request', $params);
        $result->setData('response', $data);

        return $result;
    }
159753
public function process(Request $request, Transaction $transaction, Delivery $delivery)
    {
        
        // in your controller
        $transactionService = $this->get('transaction');
        $data = $request->get('braintree');
        $nonce = $data['payment_method_nonce'];

        $result = $transactionService::sale([
            'amount' => $transaction->getTotalPrice(),
            'paymentMethodNonce' => $nonce
        ]);
        
        
        $em = $this->container->get('doctrine')->getManager();
        $pm = $em->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('braintree');
        if ($result->success || !is_null($result->transaction)) {
                        
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_PAID);
            $transaction->setPaymentMethod($pm);
            
            //details
            $details = new stdClass();
            $details->id = $result->transaction->id;
            $details->status = $result->transaction->status;
            $details->type = $result->transaction->type;
            $details->currencyIsoCode = $result->transaction->currencyIsoCode;
            $details->amount = $result->transaction->amount;
            $details->merchantAccountId = $result->transaction->merchantAccountId;
            $details->createdAt = $result->transaction->createdAt;
            $details->updatedAt = $result->transaction->updatedAt;
            $details->customer = $result->transaction->customer;
            $details->billing = $result->transaction->billing;
            $details->shipping = $result->transaction->shipping;
            
            $transaction->setPaymentDetails(json_encode($details));
            $em->persist($transaction);
            $em->flush();

            //confirmation payment
            $answer = new stdClass();
            $answer->redirectUrl = $this->container->get('router')->generate('ecommerce_checkout_confirmationpayment');

            return $answer;
       }else{
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_CANCELLED);
            $transaction->setPaymentMethod($pm);
            
            //details
            $errorString = "";
            foreach($result->errors->deepAll() as $error) {
               $errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
            }
            $this->container->get('session')->getFlashBag()->add('error', $errorString);
            
            $transaction->setPaymentDetails(json_encode($errorString));
            $em->persist($transaction);
            $em->flush();

            //cancel payment
            $answer = new stdClass();
            $answer->redirectUrl = $this->container->get('router')->generate('ecommerce_checkout_cancelationpayment');

            return $answer;
        }
 
    }
399270
protected function initTransaction(array $options = [])
    {
        if (!isset($options['transactionId'])) {
            $this->transactionId = IdGenerator::generateId();
            $this->getClient()->sendFrame(
                $this->getProtocol()->getBeginFrame($this->transactionId)
            );
        } else {
            $this->transactionId = $options['transactionId'];
        }
    }
451091
public function doRequest($request, $options = null)
    {
        $request = array_merge($request, array(
            'Version'        => $this->_config->version,
            'ProcessorId'    => $this->_config->processorId,
            'MerchantId'     => $this->_config->merchantId,
            'TransactionPwd' => $this->_config->transactionPwd,
        ));

        $xml = new DOMDocument('1.0', 'utf-8');
        $envelope = $xml->createElement('CardinalMPI');
        foreach ($request as $k => $v) {
            $envelope->appendChild($xml->createElement($k, $v));
        }
        $xml->appendChild($envelope);

        $url = $this->_config->serviceUri();
        $xmlData = $xml->saveXML();
        $data = 'cmpi_msg=' . urlencode($xmlData);
        $header = array(
            'Content-type: application/x-www-form-urlencoded;charset="utf-8"',
            'Accept: text/xml',
            'Content-length: '.strlen($data),
        );
        // error_log($xmlData);

        return $this->submitRequest($url, $header, $data);
    }
1132423
private function commitInSingleUseTransaction(array $mutations, array $options = [])
    {
        $options['mutations'] = $mutations;

        return $this->runTransaction(function (Transaction $t) use ($options) {
            return $t->commit($options);
        }, [
            'singleUse' => true
        ]);
    }
108786
protected function getCommand(Transaction $transaction)
    {
        switch ($transaction->getType()->getValue()) {
            case Transaction\TransactionType::SALE:
                return 'ECheck.ProcessPayment';

            case Transaction\TransactionType::AUTH:
                return 'ECheck.Authorize';

            case Transaction\TransactionType::CAPTURE:
                return 'ECheck.Capture';

            case Transaction\TransactionType::REFUND:
                return 'ECheck.Refund';

            case Transaction\TransactionType::VOID:
                return 'ECheck.Void';

            case Transaction\TransactionType::QUERY:
                return 'ECheckReports.StatusTrackingQuery';

            case Transaction\TransactionType::UPDATE:
                return 'ECheck.Update';
        }
    }
421157
protected function buildParams(Transaction $transaction, array $options = array())
    {
        $credentials = $transaction->getCredentials();

        $params = array(
            'type' => $this->getNmiType($transaction),
            'username' => $credentials->getCredential('username'),
            'password' => $credentials->getCredential('password'),
        );

        if (in_array($transaction->getType()->getValue(), array(
            Transaction\TransactionType::REFUND))
        ) {
            $params = array_merge($params, array(
                'transactionid' => $transaction->getParent()->getResult()->getExternalId(),
            ));
        } else {
            $account = $transaction->getAccount();

            $names = explode(' ', $account->getName(), 2);
            $firstName = isset($names[0]) ? $names[0] : '';
            $lastName = isset($names[1]) ? $names[1] : '';

            $params = array_merge($params, array(
                'firstname' => $firstName,
                'lastname' => $lastName,
                'address' => $account->getAddress(),
                'city' => $account->getCity(),
                'state' => $account->getRegion(),
                'zip' => $account->getPostalCode(),
                'country' => $account->getCountry(),
                'ipaddress' => $account->getIpAddress(),
                'payment' => 'check',
                'sec_code' => $credentials->getCredential('secCode') ?: 'WEB',
                'account_holder_type' => in_array($account->getAccountType()->getValue(), array(
                    AccountType::PERSONAL_SAVINGS,
                    AccountType::PERSONAL_CHECKING
                )) ? 'personal' : 'business',
                'account_type' => in_array($transaction->getAccount()->getAccountType()->getValue(), array(
                    AccountType::PERSONAL_SAVINGS,
                    AccountType::BUSINESS_SAVINGS
                )) ? 'savings' : 'checking',
                'amount' => $transaction->getAmount(),
                'checkname' => $account->getName(),
                'checkaba' => $account->getRoutingNumber(),
                'checkaccount' => $account->getAccountNumber()
            ));
        }

        return $params;
    }
398427
protected function validateTransaction(Transaction $transaction)
    {
        if (!$transaction->getParent() && in_array($transaction->getType()->getValue(), array(Transaction\TransactionType::CAPTURE, Transaction\TransactionType::REFUND, Transaction\TransactionType::VOID))) {
            throw ValidationException::parentTransactionRequired();
        }

        $credentials = $transaction->getCredentials();

        if (!$credentials) {
            throw ValidationException::missingCredentials();
        } elseif (null === $credentials->getCredential('username') || null === $credentials->getCredential('password')) {
            throw ValidationException::missingRequiredParameter('username or password');
        }

        $account = $transaction->getAccount();

        if (!$account) {
            throw ValidationException::missingAccountInformation();
        }

        if ((!($account instanceof CardAccount) && !($account instanceof SwipedCardAccount))
            || (!($account instanceof SwipedCardAccount) && $transaction->getNetwork() == Transaction\NetworkType::SWIPED)
        ) {
            throw ValidationException::invalidAccountType($account);
        }

        if (!$account instanceof SwipedCardAccount) {
            if (null === $account->getAccountNumber()) {
                throw ValidationException::missingRequiredParameter('account number');
            } elseif (null === $account->getExpMonth() || null === $account->getExpYear()) {
                throw ValidationException::missingRequiredParameter('card expiration');
            }
        }
    }
716801
public function sendTrackingCodeEmailMessage(Transaction $transaction)
    {
        $templateName = 'PaymentBundle:Email:trackingCode.html.twig';
        $toEmail = $transaction->getActor()->getEmail();

        $context = array(
            'order_number'  => $transaction->getTransactionKey(),
            'tracking_code' => $transaction->getDelivery()->getTrackingCode(),
            'carrier_name'  => 'Transporte'//$transaction->getDelivery()->getCarrier()->getName()
        );

        $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email'), $toEmail);
    }
500403
public function retrieveBackendOperations($transaction, $limit = false)
    {
        $parentTransaction = $this->getTransactionByTransactionId(
            $transaction->getParentTransactionId(),
            $transaction::NAME != MaestroTransaction::NAME ? $transaction::NAME : CreditCardTransaction::NAME
        );
        if (!is_null($parentTransaction) && (
            !$limit ||
            !$this->isFinal($parentTransaction[Transaction::PARAM_PAYMENT][Transaction::PARAM_TRANSACTION_TYPE])
            )) {
            $transaction->setParentTransactionType(
                $parentTransaction[Transaction::PARAM_PAYMENT][Transaction::PARAM_TRANSACTION_TYPE]
            );
        } else {
            return false;
        }

        $operations = false;
        if ($transaction->getBackendOperationForPay() && (!$limit ||
            $transaction->getParentTransactionType() == Transaction::TYPE_AUTHORIZATION)) {
            $operations[Operation::PAY] = self::CAPTURE_BUTTON_TEXT;
        }
        if ($transaction->getBackendOperationForCancel()) {
            if (stristr($transaction->getBackendOperationForCancel(), 'refund')) {
                $operations[Operation::CANCEL] = self::REFUND_BUTTON_TEXT;
            } else {
                $operations[Operation::CANCEL] = self::CANCEL_BUTTON_TEXT;
            }
        }
        if ($transaction->getBackendOperationForRefund()) {
            $operations[Operation::REFUND] = self::REFUND_BUTTON_TEXT;
        }
        if ($transaction->getBackendOperationForCredit() || $transaction->getSepaCredit()) {
            if ($limit && $transaction->getSepaCredit()) {
                $operations[Operation::CREDIT] = self::REFUND_BUTTON_TEXT;
            } elseif (!$limit) {
                $operations[Operation::CREDIT] = self::CREDIT_BUTTON_TEXT;
            }
        }

        return $operations;
    }
681252
public function execute(Session $session, $sql, array $options = [])
    {
        $options += [
            'parameters' => [],
            'types' => [],
            'transactionContext' => null
        ];

        $parameters = $this->pluck('parameters', $options);
        $types = $this->pluck('types', $options);
        $options += $this->mapper->formatParamsForExecuteSql($parameters, $types);

        $context = $this->pluck('transactionContext', $options);

        $call = function ($resumeToken = null) use ($session, $sql, $options) {
            if ($resumeToken) {
                $options['resumeToken'] = $resumeToken;
            }

            return $this->connection->executeStreamingSql([
                'sql' => $sql,
                'session' => $session->name(),
                'database' => $session->info()['database']
            ] + $options);
        };

        return new Result($this, $session, $call, $context, $this->mapper);
    }
512483
protected function _executeQuery(Query $query, array $options = [])
    {
        switch ($query->action()) {
            case Query::ACTION_CREATE:
                return $this->_executeCreateQuery($query, $options);
            case Query::ACTION_READ:
                return $this->_executeReadQuery($query, $options);
            case Query::ACTION_UPDATE:
                return $this->_executeUpdateQuery($query, $options);
            case Query::ACTION_DELETE:
                return $this->_executeDeleteQuery($query, $options);
        }

        return false;
    }
87474
public function applyTransactionId(TransactionInterface $transaction)
    {
        $transactionId = $transaction->get('txn_id', null);

        if (!$transactionId) {
            // no transaction id provided
            $transactionId = -1;
        }

        $transaction->setTransactionId($transactionId);
    }
752629
public function transCreateTable($table, $options = null, $advanced_options = null)
    {
        $this->schemaUpdateTransaction[$table] = array(
            'command' => 'create',
            'newFields' => array(),
            'newIndexes' => array(),
            'options' => $options,
            'advancedOptions' => $advanced_options
        );
    }