Authorize and capture funds
6402
def authorize_and_capture
      
      resp = StdClass.new                        
      if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED
        resp.error = "Funds for this invoice have already been captured."
      else
                        
        sc = self.site.store_config                
        case sc.pp_name                                    
          when StoreConfig::PAYMENT_PROCESSOR_STRIPE
                                                                              
            Stripe.api_key = sc.stripe_secret_key.strip
            bt = nil
            begin
              c = Stripe::Charge.create(
                :amount => (self.total * 100).to_i,
                :currency => 'usd',
                :customer => self.customer.stripe_customer_id,
                :capture => true,
                :metadata => { :invoice_id => self.id },
                :statement_descriptor => "#{self.site.description.truncate(22)}"
              )                        
            rescue Exception => ex
              resp.error = "Error during capture process\n#{ex.message}"                
            end            
            if resp.error.nil?
              InvoiceTransaction.create(
                :invoice_id => self.id,
                :transaction_id => c.id,
                :transaction_type => InvoiceTransaction::TYPE_AUTHCAP,
                :payment_processor => sc.pp_name,
                :amount => c.amount / 100.0,
                :captured => true,
                :date_processed => DateTime.now.utc,
                :success => c.status == 'succeeded'
              )
              if c.status == 'succeeded'
                self.financial_status = Invoice::FINANCIAL_STATUS_CAPTURED
                self.save
                resp.success = true
              else
                resp.error = "Error capturing funds."
              end
            end
                      
        end        
      end      
      return resp
    end
1332543
public function authorize($money, CreditCard $creditcard, $options = array())
    {
        $this->required_options('address,order_id', $options);

        $this->post = array();

        $this->addInvoice($options);
        $this->addCreditcard($creditcard);
        $this->addAddress($options);
        $this->addCustomerData($options);
        $this->addOptionalData();

        $this->post['TotalAmount'] = $this->amount($money);

        return $this->commit('xmlauth', $money, $options);
    }
361112
def __sethead(self, access_token):
        """"""
        self.access_token = access_token
        now = calendar.timegm(datetime.datetime.now().timetuple())
        self.expiration = now + 1800
        self.head = {"Authorization": "Bearer %s" % access_token,
                     "User-Agent": self.user_agent
                     }
1014688
public function captureOrderAmount($captureAmount, $amazonAuthorizationId)
    {
        $captureRequest = new OffAmazonPaymentsService_Model_CaptureRequest();
        $captureRequest->setSellerId($this->_sellerId);
        $captureRequest->setAmazonAuthorizationId($amazonAuthorizationId);
        $captureRequest->setCaptureReferenceId($this->_captureReferenceId);
        $captureRequest->setCaptureAmount(new OffAmazonPaymentsService_Model_Price());
        $captureRequest->getCaptureAmount()->setAmount($captureAmount);
        $captureRequest->getCaptureAmount()->setCurrencyCode($this->_service->getMerchantValues()->getCurrency());
         
        return $this->_service->capture($captureRequest);
    }
297029
def authorize(self, ctx, identity, ops):
        '''
        '''
        allowed = []
        caveats = []
        for op in ops:
            ok, fcaveats = self._f(ctx, identity, op)
            allowed.append(ok)
            if fcaveats is not None:
                caveats.extend(fcaveats)
        return allowed, caveats
144568
function(bankAccount, success, error) {
    success = success || noop;
    error = error || noop;
    exec(success, error, "CordovaStripe", "createBankAccountToken", [bankAccount]);
  }
751133
async function () {
    logger.info('* Funding required users with ST\'');
    logger.info('* Utility Chain Owner funding ST\' on utility chain to staker');
    await setupFundManager.transferSTP(utilityChainOwnerAddr, utilityChainOwnerPassphrase, stakerAddr,
      MIN_FUND.mul(100).toString(10));

    logger.info('* Utility Chain Owner funding ST\' on utility chain to redeemer');
    await setupFundManager.transferSTP(utilityChainOwnerAddr, utilityChainOwnerPassphrase, redeemerAddr,
      MIN_FUND.mul(100).toString(10));

    logger.info('* Utility Chain Owner funding ST\' on utility chain to utilityRegistrar');
    await setupFundManager.transferSTP(utilityChainOwnerAddr, utilityChainOwnerPassphrase, utilityRegistrarAddr,
      MIN_FUND.mul(100).toString(10));

    logger.info('* Utility Chain Owner funding ST\' on utility chain to utilityOps');
    await setupFundManager.transferSTP(utilityChainOwnerAddr, utilityChainOwnerPassphrase, utilityOpsAddr,
      MIN_FUND.mul(100).toString(10));

    logger.info('* Utility Chain Owner funding ST\' on utility chain to utilityDeployer');
    await setupFundManager.transferSTP(utilityChainOwnerAddr, utilityChainOwnerPassphrase, utilityDeployerAddr,
      MIN_FUND.mul(100).toString(10));

    return Promise.resolve();
  }
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;
    }
1049819
public function capture(Varien_Object $payment, $amount)
    {
        parent::capture($payment, $amount);
        $payment->setStatus(self::STATUS_APPROVED)
            ->setTransactionId($this->getTransactionId())
            ->setIsTransactionClosed(0);
        $order = $payment->getOrder();
        $currency = $order->getOrderCurrencyCode();

        if ($payment->hasCurrentInvoice() && $currency != $order->getBaseCurrencyCode()) {
            $invoice = $payment->getCurrentInvoice();
            $amount = $invoice->getGrandTotal();
        }

        // do capture request to adyen
        $order = $payment->getOrder();
        $pspReference = Mage::getModel('adyen/event')->getOriginalPspReference($order->getIncrementId());
        $order->getPayment()->getMethodInstance()->sendCaptureRequest($payment, $amount, $pspReference);

        return $this;
    }
175080
public function capture($paymentId, CaptureRequest $captureRequest){        
        $uri = Braspag::$apiBase . "sales/{$paymentId}/capture"; 
        
        if($captureRequest != null){
            $uri = $uri . "?amount={$captureRequest->amount}&serviceTaxAmount={$captureRequest->serviceTaxAmount}";
        }
        
        $response = Request::put($uri)
            ->sendsJson()
            ->addHeaders($this->headers)
            ->send();
        
        if($response->code == HttpStatus::Ok){    
            
            $captureResponse = new CaptureResponse();
            $captureResponse->status = $response->body->Status;
            $captureResponse->reasonCode = $response->body->ReasonCode;
            $captureResponse->reasonMessage = $response->body->ReasonMessage;
            
            $captureResponse->links = $this->parseLinks($response->body->Links);
            
            return $captureResponse;
            
        }elseif($response->code == HttpStatus::BadRequest){            
            Utils::handleApiError($response);            
        }   
        
        return $response->code;
    }
288382
def withdraw(self, account_id, **params):
        """"""
        for required in ['payment_method', 'amount', 'currency']:
            if required not in params:
                raise ValueError("Missing required parameter: %s" % required)
        response = self._post('v2', 'accounts', account_id, 'withdrawals', data=params)
        return self._make_api_object(response, Withdrawal)
1050513
private function authorise()
	{
		$url = $this->getOption('authoriseURL') . '?oauth_token=' . $this->token['key'];

		if ($this->getOption('scope'))
		{
			$scope = \is_array($this->getOption('scope')) ? implode(' ', $this->getOption('scope')) : $this->getOption('scope');
			$url .= '&scope=' . urlencode($scope);
		}

		if ($this->getOption('sendheaders'))
		{
			$this->application->redirect($url);
		}
	}
1189331
function getAuthorization(user, auth) {
    if (auth === AUTH_BASIC) {
        return 'Basic ' + btoa(user.username + ':' + user.password);
    } else if (auth === AUTH_TOKEN) {
        return 'Token token=' + user.token;
    }
}
523581
def authorize!(action, subject, *args)
      message = args.last.is_a?(Hash) && args.last.key?(:message) ? args.pop[:message] : nil
      if cannot?(action, subject, *args)
        message ||= unauthorized_message(action, subject)
        raise AccessDenied.new(message, action, subject, args)
      end
      subject
    end
529013
function parseArgs (f) {
  return function (args, opts, callback) {
    var credentials = auth(opts.req)
    var guid = credentials.name
    var walletOpts = { password: credentials.pass, apiCode: apiCode }

    if (!guid) throw 'Missing wallet guid'
    if (!walletOpts.password) throw 'Missing wallet password'

    if (args.length > f.$params.length) {
      throw 'Expected max of ' + f.$params.length + ' parameters, received ' + args.length
    }

    var params = f.$params
      .map(function (param, i) {
        return {
          name: param.split('?')[0],
          value: args[i],
          required: !~param.indexOf('?')
        }
      })
      .reduce(function (acc, param) {
        if (param.value == null && param.required) throw 'Missing parameter: ' + param.name
        acc[param.name] = param.value
        return acc
      }, {})

    var action = f.$nowallet
      ? Promise.resolve(f(params))
      : api.getWallet(guid, walletOpts).then(f.bind(f, params))

    action
      .then(callback.bind(null, null))
      .catch(callback)
  }
}
1151447
async function () {
    const oThis = this
    ;

    // validations
    if (!basicHelper.isNonZeroWeiValid(oThis.amountToStakeInWeis)) {
      logger.error('Invalid amount');
      process.exit(1);
    }

    // Format to big number
    oThis.amountToStakeInWeis = basicHelper.convertToBigNumber(oThis.amountToStakeInWeis);

    const amountToStakeForBT = ((oThis.amountToStakeInWeis.mul(0.9)).minus(oThis.amountToStakeInWeis.mul(0.9).modulo(1)))
      , amountToStakeForSTP = oThis.amountToStakeInWeis.minus(amountToStakeForBT)
      , stPrimeUuid = coreConstants.OST_OPENSTUTILITY_ST_PRIME_UUID
    ;

    // validations
    if (!basicHelper.isNonZeroWeiValid(amountToStakeForBT)) {
      logger.error('Invalid wei amount to stake for BT', amountToStakeForBT.toString(10));
      process.exit(1);
    }
    if (!basicHelper.isNonZeroWeiValid(amountToStakeForSTP)) {
      logger.error('Invalid wei amount to stake for ST Prime', amountToStakeForSTP.toString(10));
      process.exit(1);
    }

    logger.step('** Starting stake mint for branded token for beneficiary reserve of BT Reserve:', oThis.reserveAddr);

    // NOTE: In real case, Member Company transfers ST to staker and then approve is called. To simulate this, foundation
    // is transfering ST to staker.
    logger.info('* Foundation transfers ST to BT Reserve');
    await fundManager.transferST(
        foundationAddr, foundationPassphrase, stakerAddr, oThis.amountToStakeInWeis,
        {tag: 'transferSTToBTReserve', returnType: 'txReceipt'}
    );

    logger.info('* Staker approves openSTValue contract');
    const approveResponse = await (new approveService()).perform();
    if (approveResponse.isFailure()) {
      process.exit(1);
    }

    const approveTransactionHash = approveResponse.data.transaction_hash;

    logger.info('* Get approval status and keep doing so till success');
    const approveReceiptResponse =  await contractInteractHelper.waitAndGetTransactionReceipt(web3Provider, approveTransactionHash, {});
    if (!approveReceiptResponse.isSuccess()) {
      logger.error('Approval receipt error ', approveReceiptResponse);
      process.exit(1);
    }

    logger.info('* Start stake for Branded Token');
    await (new startStakeService({
      beneficiary: oThis.reserveAddr,
      to_stake_amount: amountToStakeForBT,
      uuid: oThis.brandedTokenUuid
    })).perform();

    logger.info('* Waiting for credit of Branded Token to BT Reserve');
    await oThis._waitForBrandedTokenMint();

    logger.info('* Start stake for Simple Token Prime');
    await (new startStakeService({
      beneficiary: oThis.reserveAddr,
      to_stake_amount: amountToStakeForSTP,
      uuid: stPrimeUuid
    })).perform();

    logger.info('* Waiting for credit of Simple Token Prime to BT Reserve');
    await oThis._waitForSimpleTokenPrimeMint();

    return Promise.resolve(responseHelper.successWithData({}));
  }
1086639
def authorize(self, ctx, identity, ops):
        '''
        '''
        if len(ops) == 0:
            # Anyone is allowed to do nothing.
            return [], []
        allowed = [False] * len(ops)
        has_allow = isinstance(identity, ACLIdentity)
        for i, op in enumerate(ops):
            acl = self._get_acl(ctx, op)
            if has_allow:
                allowed[i] = identity.allow(ctx, acl)
            else:
                allowed[i] = self._allow_public and EVERYONE in acl
        return allowed, []