Handle IPN from Bitpay server
 Receives incoming IPN message and retrieves official BitPay invoice for processing
184174
def notification

      begin
        posData = JSON.parse(params["posData"])

        order_id = posData["orderID"]
        payment_id = posData["paymentID"]

        order = Spree::Order.find_by_number(order_id) || raise(ActiveRecord::RecordNotFound)
        begin
          order.process_bitpay_ipn payment_id
          head :ok
        rescue => exception
          logger.debug exception
          head :uprocessable_entity
        end
      rescue => error
        logger.error "Spree_Bitpay:  Unprocessable notification received from #{request.remote_ip}: #{params.inspect}"
        head :unprocessable_entity	
      end
    end
98781
public function easyVerifyIPN()
    {
        $url       = $this->getCurrentUrl();
        $signature = $_SERVER["HTTP_API_SIGN"];
        $api_key   = $_SERVER["HTTP_API_KEY"];
        $nonce     = $_SERVER["HTTP_API_NONCE"];
        $payload   =  file_get_contents("php://input"); //// raw post body
        /// or we could use
        /// $payload   =  stream_get_contents(STDIN);

        if (!$api_key || !$nonce || !$signature || $payload == "") {
            //// missing headers OR an empty payload
            return false;
        }

        $message = $nonce . $url . $payload;
        $calculated_signature = $this->signMessage($message);
        if($calculated_signature <> $signature ){
            //// invalid IPN call
            return false;
        }
        //// valid IPN call
        return true;

    }
463055
def handle_pubcomp(self):
        """"""
        self.logger.info("PUBCOMP received")

        ret, mid = self.in_packet.read_uint16()

        if ret != NC.ERR_SUCCESS:
            return ret

        evt = event.EventPubcomp(mid)
        self.push_event(evt)

        return NC.ERR_SUCCESS
1136479
function handlePrimePumpCompletion(response) {

            var path = response.path,
                type = response.type,
                $deferredHints = getPendingRequest(path, OFFSET_ZERO, type);

            if ($deferredHints) {
                $deferredHints.resolve();
            }
        }
459471
def handle(self):
        
        pid, fd = pty.fork()
        if pid:
            protocol = TelnetServerProtocolHandler(self.request, fd)
            protocol.handle()
        else:
            self.execute()
82111
public function onPayboxIpnResponse(PayboxResponseEvent $event)
    {
        $path = sprintf('%s/../data/%s', $this->rootDir, date('Y\/m\/d\/'));
        $this->filesystem->mkdir($path);

        $content = sprintf('Signature verification : %s%s', $event->isVerified() ? 'OK' : 'KO', PHP_EOL);
        foreach ($event->getData() as $key => $value) {
            $content .= sprintf("%s:%s%s", $key, $value, PHP_EOL);
        }

        file_put_contents(
            sprintf('%s%s.txt', $path, time()),
            $content
        );
    }
138968
function DoExpressCheckoutPayment($token, $payerId, $options = array()) {
    $values = array_merge($options, array('TOKEN'   => $token,
                                          'PAYERID' => $payerId));
    if (PAYPAL_DEV_MODE == 'true') $this->log('DoExpressCheckout - breakpoint 1 - ['.$token  . ' ' . $payerId . ' ' . "]\n\n[" . print_r($values, true) .']', $token);

    if ($this->_mode == 'payflow') {
      $values['ACTION'] = 'D'; /* ACTION=D denotes DoExpressCheckoutPayment via Payflow */
      $values['TENDER'] = 'P';
      $values['TRXTYPE'] = $this->_trxtype;
      $values['NOTIFYURL'] = zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true);
    } elseif ($this->_mode == 'nvp') {
      if (!isset($values['PAYMENTACTION']) || $this->checkHasApiCredentials() === FALSE) $values['PAYMENTACTION'] = ($this->_trxtype == 'S' || ($this->checkHasApiCredentials() === FALSE) ? 'Sale' : 'Authorization');
      $values['NOTIFYURL'] = urlencode(zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true));
    }
    $this->values = $values;
    $this->notify('NOTIFY_PAYPAL_DOEXPRESSCHECKOUTPAYMENT');
    if (PAYPAL_DEV_MODE == 'true') $this->log('DoExpressCheckout - breakpoint 2 '.print_r($this->values, true), $token);
    return $this->_request($this->values, 'DoExpressCheckoutPayment');
  }
173097
def handle_inv(self, message_header, inv_packet ):
        
        log.debug("handle inv of %s item(s)" % len(inv_packet.inventory))

        reply_inv = []

        for inv_info in inv_packet.inventory:
            inv_hash = "%064x" % inv_info.inv_hash
            if inv_info.inv_type == INVENTORY_TYPE["MSG_BLOCK"]:
                # only ask for the block if we need it
                if inv_hash in self.block_info.keys() and not self.block_info[inv_hash]['handled']:
                    log.debug("Will request block %s" % inv_hash)
                    reply_inv.append( inv_info )
                    inv_hash = None


        if len(reply_inv) > 0:
            getdata = GetData()
            getdata.inventory = reply_inv
            log.debug("send GetData in reply to Inv for %s item(s)" % len(reply_inv))
            self.send_message(getdata)

        else:
            if self.have_all_block_data():
                self.loop_exit()
1253153
def unsigned_request(self, path, payload=None):
    
    headers = {"content-type": "application/json", "accept": "application/json", "X-accept-version": "2.0.0"}
    try:
      if payload:
        response = requests.post(self.uri + path, verify=self.verify, data=json.dumps(payload), headers=headers)
      else:
        response = requests.get(self.uri + path, verify=self.verify, headers=headers)
    except Exception as pro:
      raise BitPayConnectionError('Connection refused')
    return response
177107
def pay_now
      order = current_order || raise(ActiveRecord::RecordNotFound)
      session[:order_number] = current_order.number
      invoice = order.place_bitpay_order notificationURL: bitpay_notification_url
      @invoice_iframe_url = "#{invoice['url']}&view=iframe"
      render json: @invoice_iframe_url
    end
1193979
protected function PostProcessExternalPaymentHandlerHook()
    {
        $oBasket = TShopBasket::GetInstance();
        if ($oBasket->GetActivePaymentMethod()) {
            if ($oBasket->GetActivePaymentMethod()->PostProcessExternalPaymentHandlerHook()) {
                $oBasket->aCompletedOrderStepList[$this->oActiveOrderStep->fieldSystemname] = true;
                // all good.... jump to next step
                $oNextStep = $this->oActiveOrderStep->GetNextStep();
                $oNextStep->JumpToStep($oNextStep);
            } else {
                TTools::WriteLogEntry("PostProcessExternalPaymentHandlerHook: called 'PostProcessExternalPaymentHandlerHook' on the payment method - and got false", 1, __FILE__, __LINE__);
            }
        } else {
            TTools::WriteLogEntry('PostProcessExternalPaymentHandlerHook: no active payment method found', 1, __FILE__, __LINE__);
        }
    }
814465
function DoCaptTran($hostlogkey,
                        $authcode,
                        $amount,
                        $currency,
                        $instnumber,
                        $multpoint = "00",
                        $extpoint = "000000") {

        $posnetRequest = new PosnetRequest();

        $posnetRequest->hostlogkey = $hostlogkey;
        $posnetRequest->authcode = $authcode;
        $posnetRequest->amount = $amount;
        $posnetRequest->currency = $currency;
        $posnetRequest->instnumber = $instnumber;
        $posnetRequest->multiplepoint = $multpoint;
        $posnetRequest->extrapoint = $extpoint;

        return $this->DoTran($posnetRequest, "capt");
    }
106256
def perform_request
      parameters = {
        amount: @options[:amount],
        payment_method_token: @options[:token],
        options: {
          skip_advanced_fraud_checking: !@options[:enable_fraud_checking]
        }
      }
      parameters[:merchant_account_id] = @options[:merchant_account_id] if @options[:merchant_account_id].present?
      parameters[:device_data] = @options[:device_data] if @options[:device_data].present?

      @raw_response = Braintree::Transaction.sale(parameters)
      Conduit::Driver::Braintree::Json::Transaction.new(@raw_response).to_json
    end
280244
function handleIncomingMessage(event, message, source) {
		var blocks = event.split(':'),
			id = blocks[2] || blocks[1];
		if (id in self.transactions && source in self.transactions[id]) {
			self.transactions[id][source].resolve([message, source]);
		}
	}
776516
private List<SmtpMessage> handleTransaction(PrintWriter out, BufferedReader input) throws IOException {
		// Initialize the state machine
		SmtpState smtpState = SmtpState.CONNECT;
		SmtpRequest smtpRequest = new SmtpRequest(SmtpActionType.CONNECT, "", smtpState);

		// Execute the connection request
		SmtpResponse smtpResponse = smtpRequest.execute();

		// Send initial response
		sendResponse(out, smtpResponse);
		smtpState = smtpResponse.getNextState();

		List<SmtpMessage> msgList = new ArrayList<>();
		SmtpMessage msg = new SmtpMessage();

		while (smtpState != SmtpState.CONNECT) {
			String line = input.readLine();

			if (line == null) {
				break;
			}

			// Create request from client input and current state
			SmtpRequest request = SmtpRequest.createRequest(line, smtpState);
			// Execute request and create response object
			SmtpResponse response = request.execute();
			// Move to next internal state
			smtpState = response.getNextState();
			// Send response to client
			sendResponse(out, response);

			// Store input in message
			String params = request.getParams();
			msg.store(response, params);

			// If message reception is complete save it
			if (smtpState == SmtpState.QUIT) {
				msgList.add(msg);
				msg = new SmtpMessage();
			}
		}

		return msgList;
	}
47174
def capture(amount = nil)
      
      return { :error => "This invoice doesn't seem to be authorized." } if !self.success
      
      ct = InvoiceTransaction.where(:parent_id => self.id, :transaction_type => InvoiceTransaction::TYPE_CAPTURE, :success => true).first      
      return { :error => "Funds for this invoice have already been captured." } if ct
      
      # Make sure the amount given isn't greater than the invoice total      
      return { :error => "Amount given to capture is greater than the current invoice total." } if amount && amount.to_f > self.invoice.total.to_f        
      amount = self.invoice.total if amount.nil?      
            
      resp = Caboose::StdClass.new
      sc = self.invoice.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.retrieve(self.transaction_id)            
            return { :error => "Amount given to capture is greater than the amount authorized. amount = #{amount}, c.amount = #{c.amount}" } if (amount*100).to_i > c.amount            
            amount = (amount.to_f * 100.0).to_i
            if amount == c.amount              
              c = c.capture
            else
              c = c.capture({ :amount => amount })
            end
            bt = Stripe::BalanceTransaction.retrieve(c.balance_transaction)
          rescue Exception => ex
            resp.error = "Error during capture process\n#{ex.message}"                
          end
          
          if resp.error.nil?
            InvoiceTransaction.create(
              :invoice_id => self.invoice_id,
              :parent_id => self.id,
              :transaction_id => bt.id,
              :transaction_type => InvoiceTransaction::TYPE_CAPTURE,
              :payment_processor => sc.pp_name,
              :amount => bt.amount / 100.0,                
              :date_processed => DateTime.strptime(bt.created.to_s, '%s'),
              :success => bt.status == 'succeeded' || bt.status == 'pending'
            )
            if bt.status == 'succeeded' || bt.status == 'pending'
              self.captured = true
              self.save              
              self.invoice.financial_status = Invoice::FINANCIAL_STATUS_CAPTURED
              self.invoice.save
              resp.success = true
            else
              resp.error = "Error capturing funds."
            end
          end
          
      end
      return resp
      
    end
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');
  }