Approve one payment
961064
public function approve()
	{

		$id = Input::get('id');
		$terminal = Terminal::whereUserId($this->userId())->first();
		$payment = Payment::find($id);
		if ($payment->term == $terminal->id) {

			$status = $payment->getPossibleStatus();

			if ($status) {
				$payment->status = $status;
				$payment->save();

				if ($payment->getPossibleStatus()) {
					return array(
						'next'  => true,
						'value' => 'Move to [' . $payment->getPossibleStatus() . ']',
						'status' => $payment->status,
					);
				}

			}

		}

		return array(
			'next' => false,
			'status' => $payment? $payment->status: null,
		);

	}
745908
def create_payment(self, data):
        
        return OrderPayments(self.client).on(self).create(data)
547382
def wait_for_confirmation(provider, transaction_id):
    ''
    while(True):
        transaction = provider.gettransaction(transaction_id)
        if transaction["confirmations"] > 0:
            break
        time.sleep(10)
663617
public function authorize(Varien_Object $payment, $amount)
    {
        parent::authorize($payment, $amount);
        $payment->setLastTransId($this->getTransactionId())->setIsTransactionPending(true);

        /** @var Mage_Sales_Model_Order $order */
        $order = $payment->getOrder();
        $amount = $order->getGrandTotal();

        // check if a zero auth should be done for this order
        $useZeroAuth = (bool)Mage::helper('adyen')->getConfigData('use_zero_auth', null, $order->getStoreId());
        $zeroAuthDateField = Mage::helper('adyen')->getConfigData(
            'base_zero_auth_on_date', null,
            $order->getStoreId()
        );

        if ($useZeroAuth) { // zero auth should be used
            // only orders that are scheduled to be captured later than
            // the auth valid period use zero auth
            // the period is 7 days since this works for most payment methods
            $scheduledDate = strtotime($order->getData($zeroAuthDateField));
            if ($scheduledDate > strtotime("+7 days")) { // scheduled date is higher than now + 7 days
                $amount = 0; // set amount to 0 for zero auth
            }
        }

        /*
         * ReserveOrderId for this quote so payment failed notification
         * does not interfere with new successful orders
         */
        $incrementId = $order->getIncrementId();
        $quoteId = $order->getQuoteId();
        $quote = Mage::getModel('sales/quote')
            ->load($quoteId)
            ->setReservedOrderId($incrementId)
            ->save();

        // by zero authentication payment is authorised when api responds is succesfull
        if ($order->getGrandTotal() == 0) {
            $payment->setIsTransactionPending(false);
        }

        /*
         * Do not send a email notification when order is created.
         * Only do this on the AUHTORISATION notification.
         * For Boleto and Multibanco send it on order creation
         */
        if (!in_array($this->getCode(), array('adyen_boleto', 'adyen_multibanco'))) {
            $order->setCanSendNewEmailFlag(false);
        }

        if ($this->getCode() == 'adyen_boleto' || $this->getCode() == 'adyen_cc' || substr(
            $this->getCode(), 0,
            14
        ) == 'adyen_oneclick' || $this->getCode() == 'adyen_sepa' || $this->getCode() == 'adyen_apple_pay' || $this->getCode() == 'adyen_multibanco') {
            if (substr($this->getCode(), 0, 14) == 'adyen_oneclick') {
                // set payment method to adyen_oneclick otherwise backend can not view the order
                $payment->setMethod("adyen_oneclick");

                $recurringDetailReference = $payment->getAdditionalInformation("recurring_detail_reference");

                // load agreement based on reference_id (option to add an index on reference_id in database)
                $agreement = Mage::getModel('sales/billing_agreement')->load($recurringDetailReference, 'reference_id');

                // agreement could be a empty object
                if ($agreement && $agreement->getAgreementId() > 0 && $agreement->isValid()) {
                    $agreement->addOrderRelation($order);
                    $agreement->setIsObjectChanged(true);
                    $order->addRelatedObject($agreement);
                    $message = Mage::helper('adyen')->__(
                        'Used existing billing agreement #%s.',
                        $agreement->getReferenceId()
                    );

                    $comment = $order->addStatusHistoryComment($message);
                    $order->addRelatedObject($comment);
                }
            }

            $_authorizeResponse = $this->_processRequest($payment, $amount, "authorise");
        }

        return $this;
    }
683961
public function onEmit()
    {
        $microtime = explode('.', (string) microtime(true));

        $this->date = DateTime::parse(date('Y-m-d\TH:i:s') . '.' .
            ($microtime[1] ?? '0000'));
    }
932829
def process(self, request, item):
        """"""
        warn_untested()
        from paypal.pro.helpers import PayPalWPP

        wpp = PayPalWPP(request)
        params = self.cleaned_data
        params['creditcardtype'] = self.fields['acct'].card_type
        params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y")
        params['ipaddress'] = request.META.get("REMOTE_ADDR", "")
        params.update(item)

        try:
            # Create single payment:
            if 'billingperiod' not in params:
                wpp.doDirectPayment(params)
            # Create recurring payment:
            else:
                wpp.createRecurringPaymentsProfile(params, direct=True)
        except PayPalFailure:
            return False
        return True
1372217
public static function paymentReceived(Purchase $purchase, $amount)
    {
        $purchase->received += $amount;

        if ($purchase->received >= $purchase->grandTotal) {
            $purchase->paid = time();

            $purchase->item->seller->sendEmail(
                'You have received a payment',
                'emails.item.paid',
                [
                    'total' => $purchase->received,
                    'item_name' => $purchase->item->name,
                    'buyer_name' => $purchase->name,
                    'buyer_street1' => $purchase->street1,
                    'buyer_street2' => $purchase->street2,
                    'buyer_city' => $purchase->city,
                    'buyer_county' => $purchase->county,
                    'buyer_postcode' => $purchase->postcode,
                    'buyer_country' => Iso3166::get($purchase->country)->name,
                    'has_delivery' => $purchase->hasDelivery(),
                    'has_address' => $purchase->hasAddress(),
                    'purchase_id' => $purchase->purchaseId,
                    'full' => $purchase->received == 0,
                ]
            );

            $purchase->buyer->sendEmail(
                'Receipt for your item',
                'emails.item.receipt',
                [
                    'total' => $purchase->received,
                    'item_name' => $purchase->item->name,
                    'seller_name' => $purchase->name,
                    'seller_street1' => $purchase->street1,
                    'seller_street2' => $purchase->street2,
                    'seller_city' => $purchase->city,
                    'seller_county' => $purchase->county,
                    'seller_postcode' => $purchase->postcode,
                    'seller_country' => Iso3166::get($purchase->country)->name,
                    'full' => $purchase->received == 0,
                    'has_delivery' => $purchase->hasDelivery(),
                    'has_address' => $purchase->hasAddress(),
                    'is_paid' => $purchase->isPaid()
                ]
            );
        }

        $purchase->save();
    }
1198367
public function authorize($buyOrder, $tbkUser, $username, $amount) {

        try {

            $oneClickPayInput = new oneClickPayInput();

            $oneClickPayInput->buyOrder = $buyOrder;
            $oneClickPayInput->tbkUser = $tbkUser;
            $oneClickPayInput->username = $username;
            $oneClickPayInput->amount = $amount;

            $oneClickauthorizeResponse = $this->_authorize(
                    array("oneClickPayInput" => $oneClickPayInput)
            );

            /** Validación de firma del requerimiento de respuesta enviado por Webpay */
            $xmlResponse = $this->soapClient->__getLastResponse();
            $soapValidation = new SoapValidation($xmlResponse, $this->config->getWebpayCert());
            $validationResult = $soapValidation->getValidationResult();

            if ($validationResult === TRUE) {

                $oneClickPayOutput = $oneClickauthorizeResponse->return;
                return $oneClickPayOutput;

            } 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());

        }
    }
1253837
public function confirmBillingAgreement ()
    {
        $confirmBillingAgreementRequest = new OffAmazonPaymentsService_Model_ConfirmBillingAgreementRequest();
        $confirmBillingAgreementRequest->setAmazonBillingAgreementId(
                $this->_amazonBillingAgreementId);
        $confirmBillingAgreementRequest->setSellerId($this->_sellerId);
        
        return $this->_service->confirmBillingAgreement($confirmBillingAgreementRequest);
    }
1372388
def post(self, request, *args, **kwargs):
        
        return self.approve(request, *args, **kwargs)
117948
function approveWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, arrOtherCosigners, onDone){
	var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate);
	device.addIndirectCorrespondents(arrOtherCosigners, function(){
		addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){
			arrDeviceAddresses.forEach(function(device_address){
				if (device_address !== device.getMyDeviceAddress())
					sendMyXPubKey(device_address, wallet, xPubKey);
			});
			if (onDone)
				onDone();
		});
	});
}
963118
def confirm(self, token=None):
        
        _token = token if token else self._response.get("token")
        return self._process('checkout-invoice/confirm/' + str(_token))
1107873
def pay_loan(self, loan_name):
        """"""
        loan_payments = {
            'student': 600,
            'car': 200
        }
        payment_amount = loan_payments[loan_name]
        self.withdraw(payment_amount)
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;
    }
1238571
function DoDirectPayment($cc, $cvv2 = '', $exp, $fname = null, $lname = null, $cc_type, $options = array(), $nvp = array() ) {
    $values = $options;
    $values['ACCT'] = $cc;
    if ($cvv2 != '') $values['CVV2'] = $cvv2;
    $values['FIRSTNAME'] = $fname;
    $values['LASTNAME'] = $lname;
    if (isset($values['NAME'])) unset ($values['NAME']);

    if ($this->_mode == 'payflow') {
      $values['EXPDATE'] = $exp;
      $values['TENDER'] = 'C';
      $values['TRXTYPE'] = $this->_trxtype;
      $values['VERBOSITY'] = 'MEDIUM';
      $values['NOTIFYURL'] = zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true);
    } elseif ($this->_mode == 'nvp') {
      $values = array_merge($values, $nvp);
      if (isset($values['ECI'])) {
        $values['ECI3DS'] = $values['ECI'];
        unset($values['ECI']);
      }
      $values['CREDITCARDTYPE'] = ($cc_type == 'American Express') ? 'Amex' : $cc_type;
      $values['NOTIFYURL'] = urlencode(zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true));
      if (!isset($values['PAYMENTACTION'])) $values['PAYMENTACTION'] = ($this->_trxtype == 'S' ? 'Sale' : 'Authorization');

      if (isset($values['COUNTRY'])) unset ($values['COUNTRY']);
      if (isset($values['COMMENT1'])) unset ($values['COMMENT1']);
      if (isset($values['COMMENT2'])) unset ($values['COMMENT2']);
      if (isset($values['CUSTREF'])) unset ($values['CUSTREF']);
    }
    $this->values = $values;
    $this->notify('NOTIFY_PAYPAL_DODIRECTPAYMENT');
    ksort($this->values);
    return $this->_request($this->values, 'DoDirectPayment');
  }
407259
def approve(self, creator):
        
        self.approved = True
        self.creator = creator
        self.save()
1234712
public function calculate()
    {
        $this->init();

        foreach ($this->getPaymentList() as $payment) {
            $status = $payment->getStatus();
            $action = $payment->getAction();
            $amount = $payment->getAmount();

            $this->aggregateAmounts($action, $status, $amount);
        }
    }