Create Payment record in Xero
182892
def create_payment(payment)
      b = Builder::XmlMarkup.new

      request_xml = b.Payments do
        payment.to_xml(b)
      end

      response_xml = http_put(@client, "#{xero_url}/Payments", request_xml)
      parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/payments'})
    end
398506
@Override
	@Transactional(enabled = false)
	public CommerceOrderPayment createCommerceOrderPayment(
		long commerceOrderPaymentId) {
		return commerceOrderPaymentPersistence.create(commerceOrderPaymentId);
	}
1335946
def charge(self, amount):
        
        try:
            result = Transaction.sale(
                {
                    'amount': amount.quantize(Decimal('.01')),
                    'customer_id': self.vault_id,
                    "options": {
                        "submit_for_settlement": True
                    }
                }
            )

            if result.is_success:
                # create a payment log
                payment_log = PaymentLog.objects.create(user=self.user, amount=amount, transaction_id=result.transaction.id)
                return payment_log
            else:
                raise Exception('Logical error in CC transaction')
        except Exception:
            logging.error('Failed to charge $%s to user: %s with vault_id: %s' % (amount, self.user, self.vault_id))
            return None
195122
protected function build()
    {
        $operation = $this->buildOperation('AcceptPayment');

        $merchantID = $this->document->createElement('merchantID', $this->merchantId);
        $operation->appendChild($merchantID);

        $tid = $this->document->createElement('tid', $this->tid);
        $operation->appendChild($tid);

        $pType = $this->document->createElement('pType', $this->pType);
        $operation->appendChild($pType);


        $payment = $this->document->createElement('payment');
        $payment->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi:type', 'etp:Payment' . $this->pType);
        $payment = $operation->appendChild($payment);

        $this->appendArray($payment, $this->payment);

        $this->appendArray($operation, $this->additional);
    }
982904
def create_request
      raise AttributeMissing.new "(2500) TransactionReference or OrderReference need to be present." if (transaction_reference.nil? && order_reference.nil?)
      raise AttributeMissing.new "(2500) SiteReference must be present." if (site_reference.nil? && (REXML::XPath.first(@request_xml, "//SiteReference").text.blank? rescue true))
      REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = "TRANSACTIONQUERY"
      ops = REXML::XPath.first(@request_xml, "//Operation")
      ["TermUrl", "MerchantName", "Currency", "SettlementDay"].each { |e| ops.delete_element e }
      (ops.elements["SiteReference"] || ops.add_element("SiteReference")).text = self.site_reference if self.site_reference
      (ops.elements["TransactionReference"] || ops.add_element("TransactionReference")).text = self.transaction_reference if self.transaction_reference
      order = REXML::XPath.first(@request_xml, "//Operation")
      (order.elements["OrderReference"] || order.add_element("OrderReference")).text = self.order_reference if self.order_reference
      root = @request_xml.root
      (root.elements["Certificate"] || root.add_element("Certificate")).text = self.site_alias if self.site_alias
    end
445634
def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
        
        return self.get_vm().create_transaction(*args, **kwargs)
1352987
public Result processPayment(Payment payment) throws PaytrailException {
		try {
			String data = marshaller.objectToString(payment);
			String url = serviceUrl + "/api-payment/create";
			
			IOHandlerResult requestResult = postJsonRequest(url, data);
			
			if (requestResult.getCode() != 201) {
				JsonError jsonError = marshaller.stringToObject(JsonError.class, requestResult.getResponse());
				throw new PaytrailException(jsonError.getErrorMessage());
	  	}
			
			return marshaller.stringToObject(Result.class, requestResult.getResponse());
		} catch (IOException e) {
			throw new PaytrailException(e);
		}
	}
18291
public function recordPayment(string $id, array $data, array $headers = [])
    {
        $url = $this->url('invoices/%s/record_payment', $id);

        return $this->post($url, $data, $headers);
    }
1076026
def create_request(payment_transaction)
      request = super payment_transaction

      payment_transaction.payment.status  = payment_status
      payment_transaction.processor_type  = PaymentTransaction::PROCESSOR_QUERY
      payment_transaction.processor_name  = @api_method
      payment_transaction.status          = PaymentTransaction::STATUS_PROCESSING

      request
    end
392638
def create(source, ids, force, pid_minter=None):
    """"""
    records_deprecation_warning()

    # Make sure that all imports are done with application context.
    from .api import Record
    from .models import RecordMetadata

    pid_minter = [process_minter(minter) for minter in pid_minter or []]

    data = json.load(source)

    if isinstance(data, dict):
        data = [data]

    if ids:
        assert len(ids) == len(data), 'Not enough identifiers.'

    for record, id_ in zip_longest(data, ids):
        id_ = id_ or uuid.uuid4()
        try:
            for minter in pid_minter:
                minter(id_, record)

            click.echo(Record.create(record, id_=id_).id)
        except exc.IntegrityError:
            if force:
                current_app.logger.warning(
                    "Trying to force insert: {0}".format(id_))
                # IMPORTANT: We need to create new transaction for
                # SQLAlchemy-Continuum as we are using no auto-flush
                # in Record.get_record.
                vm = current_app.extensions['invenio-db'].versioning_manager
                uow = vm.unit_of_work(db.session)
                uow.create_transaction(db.session)
                # Use low-level database model to retrieve an instance.
                model = RecordMetadata.query.get(id_)
                rec = Record(record, model=model).commit()
                current_app.logger.info("Created new revision {0}".format(
                    rec.revision_id))
                click.echo(rec.id)
            else:
                raise click.BadParameter(
                    'Record with id={0} already exists. If you want to '
                    'override its data use --force.'.format(id_),
                    param_hint='ids',
                )
        db.session.flush()
    db.session.commit()
47929
public function create($amount, $payment, $options = [])
    {
        $params = [];

        $params['transaction'] = 'fail';

        if ($payment === 'success') {
            $params['transaction'] = 'success';
        }

        return $this->gateway->commit('post', 'charges', $params);
    }
779018
private function doProcessType()
	{
		$type = new Type($this->payment->type, $this->payment->toArray());

		switch ($type->sid()) {

			case Type::CITY:

				break;

			case Type::FEE:

				break;

			case Type::CHECK:

				// todo check 'check' request

				// register check request
				$this->payment->status = Status::ENABLED;

				break;

			case Type::PAY:


				// pay after 'check' request
				$payment = self::findCheck(
					$this->payment->term,
					$this->payment->city,
					$this->payment->amount,
					$this->payment->to,
					Status::ENABLED
				);

				if (!$payment) {
					throw new ProcessorException(ProcessorException::RC_CHECK_NOT_FOUND);
				}

				// close 'check' request
				$payment->status = Status::PAY;
				$payment->saveByType();

				// processed 'payment' request
				$this->payment->status = Status::PROCESSED;
				$this->payment->code = uniqid();

				break;

			case Type::CANCEL:

				// find pay in status 'processed'
				$payment = self::findPayTo(
					$this->payment->term,
					$this->payment->code,
					$this->payment->to,
					Status::PROCESSED
				);

				if ($payment) {

					// cancel 'pay' request
					$payment->status = Status::CANCELED;
					$payment->saveByType();

					// save cancel request in 'processed'
					$this->payment->status = Status::PROCESSED;
					$this->payment->amount = $payment->amount;
					$this->payment->name = $payment->name;
					$this->payment->to = $payment->to;

				} else {
					throw new ProcessorException(ProcessorException::RC_PAY_NOT_FOUND);
				}

				break;

			case Type::STATUS:

				// status for pay
				$payment = self::findPayTo(
					$this->payment->term,
					$this->payment->code,
					$this->payment->to
				);

				// init data from 'pay' request into current 'status' request
				if ($payment) {
					$this->payment->id = $payment->id;
					$this->payment->status = $payment->status;
					$this->payment->amount = $payment->amount;
					$this->payment->to = $payment->to;
					$this->payment->name = $payment->name;
				} else {
					throw new ProcessorException(ProcessorException::RC_PAY_NOT_FOUND);
				}

				break;

		}

		return '00';

	}
1051762
public function initiateAction()
    {
        $api = Mage::getSingleton('adyen/api');
        $quote = (Mage::getModel('checkout/type_onepage') !== false) ? Mage::getModel('checkout/type_onepage')->getQuote() : Mage::getModel('checkout/session')->getQuote();
        $storeId = Mage::app()->getStore()->getId();
        $adyenHelper = Mage::helper('adyen');

        $params = $this->getRequest()->getParams();
        $poiId = $params['terminalId'];

        $serviceID = date("dHis");
        $initiateDate = date("U");
        $timeStamper = date("Y-m-d") . "T" . date("H:i:s+00:00");
        $customerId = $quote->getCustomerId();

        # Always create new order increment ID, assuring payment transaction is linked to one order only
        $quote->unsReservedOrderId();
        $reference = $quote->reserveOrderId()->getReservedOrderId();

        $request = array(
            'SaleToPOIRequest' => array(
                'MessageHeader' => array(
                    'MessageType' => 'Request',
                    'MessageClass' => 'Service',
                    'MessageCategory' => 'Payment',
                    'SaleID' => 'Magento1Cloud',
                    'POIID' => $poiId,
                    'ProtocolVersion' => '3.0',
                    'ServiceID' => $serviceID
                ),
                'PaymentRequest' => array(
                    'SaleData' => array(
                        'TokenRequestedType' => 'Customer',
                        'SaleTransactionID' => array(
                            'TransactionID' => $reference,
                            'TimeStamp' => $timeStamper
                        ),
                    ),
                    'PaymentTransaction' => array(
                        'AmountsReq' => array(
                            'Currency' => $quote->getBaseCurrencyCode(),
                            'RequestedAmount' => doubleval($quote->getGrandTotal())
                        ),
                    ),
                    'PaymentData' => array(
                        'PaymentType' => 'Normal'
                    ),
                ),
            ),
        );

        // If customer exists add it into the request to store request
        if (!empty($customerId)) {
            $shopperEmail = $quote->getCustomerEmail();
            $recurringContract = $adyenHelper->getConfigData('recurring_type', 'adyen_pos_cloud', $storeId);

            if (!empty($recurringContract) && !empty($shopperEmail) && !empty($customerId)) {
                $recurringDetails = array(
                    'shopperEmail' => $shopperEmail,
                    'shopperReference' => strval($customerId),
                    'recurringContract' => $recurringContract
                );
                $request['SaleToPOIRequest']['PaymentRequest']['SaleData']['SaleToAcquirerData'] = http_build_query($recurringDetails);
            }
        }

        $quote->getPayment()->setAdditionalInformation('serviceID', $serviceID);
        $quote->getPayment()->setAdditionalInformation('initiateDate', $initiateDate);

        $result = self::PAYMENT_ERROR;
        $errorCondition = "Payment Error";

        // Continue only if success or timeout
        try {
            $response = $api->doRequestSync($request, $storeId);
            if (!empty($response['SaleToPOIResponse']['PaymentResponse']) && $response['SaleToPOIResponse']['PaymentResponse']['Response']['Result'] == 'Success') {
                $result = self::PAYMENT_SUCCESSFUL;
            } elseif (!empty($response['SaleToPOIResponse']['PaymentResponse']) && $response['SaleToPOIResponse']['PaymentResponse']['Response']['Result'] == 'Failure') {
                $errorCondition = $response['SaleToPOIResponse']['PaymentResponse']['Response']['ErrorCondition'];
            }
        } catch (Adyen_Payment_Exception $e) {
            if ($e->getCode() == CURLE_OPERATION_TIMEOUTED) {
                $result = self::PAYMENT_RETRY;
            }
        }

        if (!empty($response['SaleToPOIResponse']['PaymentResponse']['PaymentReceipt'])) {
            $formattedReceipt = $adyenHelper->formatTerminalAPIReceipt($response['SaleToPOIResponse']['PaymentResponse']['PaymentReceipt']);
            $quote->getPayment()->setAdditionalInformation('receipt', $formattedReceipt);
        }

        $terminalResponse = "";
        if (!empty($response['SaleToPOIResponse']['PaymentResponse'])) {
            $terminalResponse = $response['SaleToPOIResponse']['PaymentResponse'];
        }

        $quote->getPayment()->setAdditionalInformation(
            'terminalResponse',
            $terminalResponse
        );

        try {
            $quote->save();
        } catch (Exception $e) {
            $result = self::PAYMENT_RETRY;
            $errorCondition = $e->getMessage();
            Mage::logException($e);
        }

        $resultArray = array(
            'result' => $result,
            'error' => $errorCondition
        );

        $this->getResponse()->setHeader('Content-type', 'application/json');
        $this->getResponse()->setBody(json_encode($resultArray));
        return $result;
    }
510950
def transaction_request_object(amount, creditcard, gateway_options)
     {  'AccountHolder' => creditcard.name,
        'ClientIP' => gateway_options[:ip],
        'Details' => transaction_details(amount, creditcard, gateway_options),
        'BillingAddress' => address_hash(creditcard, gateway_options, :billing_address),
        'ShippingAddress' => address_hash(creditcard, gateway_options, :shipping_address),
        'CreditCardData' => {
          'CardNumber' => creditcard.number,
          'CardExpiration' => expiration_date(creditcard),
          'AvsStreet' => gateway_options[:billing_address][:address1],
          'AvsZip' => gateway_options[:billing_address][:zip],
          'CardCode' => creditcard.verification_value } }
    end
953953
def to_xml(self):
        '''
        
        '''
        for n, v in { "amount": self.amount, "date": self.date,
                     "method":self.method}.items():
            if is_empty_or_none(v):
                raise PaymentError("'%s' attribute cannot be empty or " \
                                       "None." % n)

        doc = Document()
        root = doc.createElement("payment")
        super(Payment, self).to_xml(root)
        self._create_text_node(root, "amount", self.amount)
        self._create_text_node(root, "method", self.method)
        self._create_text_node(root, "reference", self.ref, True)
        self._create_text_node(root, "date", self.date)
        return root
679387
function createCardTransaction(cardId, _ref2, commit, otp, options) {
  let amount = _ref2.amount,
      currency = _ref2.currency,
      destination = _ref2.destination,
      origin = _ref2.origin,
      message = _ref2.message,
      securityCode = _ref2.securityCode;

  options = (0, _lodash2.default)({
    body: {
      denomination: {
        amount: amount,
        currency: currency
      },
      destination: destination,
      message: message,
      origin: origin,
      securityCode: securityCode
    },
    method: 'post'
  }, options);

  if (commit) {
    options.queryParams = _extends({
      commit: true
    }, options.queryParams);
  }

  if (otp) {
    options.headers = _extends({
      'otp-token': otp
    }, options.headers);
  }

  return this.api(`/me/cards/${cardId}/transactions`, options);
}
694963
def esr_recipe(invoice, account, sender, print_payment_for)
      bounding_box [cm2pt(0.4), cm2pt(9.6)], :width => cm2pt(5) do
        indent cm2pt(0.4) do
          draw_account_detail(account.bank, sender, print_payment_for)
        end
        draw_account(account)
        draw_amount(invoice.balance.currency_round)

        bounding_box [cm2pt(0.4), bounds.top - cm2pt(5.2)], :width => cm2pt(5) do
          text esr9_reference(invoice, account), :size => 7

          text " "

          draw_address invoice.customer.vcard
        end
      end

      bounding_box [cm2pt(6.4), cm2pt(9.6)], :width => cm2pt(5) do
        draw_account_detail(account.bank, sender, print_payment_for)
        draw_account(account)
        draw_amount(invoice.balance.currency_round)
      end

      font_size 10 do
        character_spacing 1.1 do
          draw_text esr9_reference(invoice, account), :at => [cm2pt(12.7), cm2pt(6.8)]
        end
      end

      bounding_box [cm2pt(12.7), cm2pt(5.5)], :width => cm2pt(7.5) do
        draw_address(invoice.customer.vcard)
      end

      # ESR-Reference
      if ::Rails.root.join('data/ocrb10.ttf').exist?
        ocr_font = ::Rails.root.join('data/ocrb10.ttf')
      else
        ocr_font = "Helvetica"
        ::Rails.logger.warn("No ocrb10.ttf found for ESR reference in #{::Rails.root.join('data')}!")
      end

      font ocr_font, :size => 11 do
        character_spacing 0.5 do
          draw_text esr9(invoice, account), :at => [cm2pt(6.7), cm2pt(1.7)]
        end
      end
    end