For every Order if there are defined billing_data creates invoice proforma,
    which is an order confirmation document
173822
def create_proforma_invoice(sender, instance, created, **kwargs):
    
    if created:
        Invoice.create(instance, Invoice.INVOICE_TYPES['PROFORMA'])
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
630200
private function doProcessType()
	{
		$type = new Type($this->payment->type, $this->payment->toArray());

		$paymentExist = self::findDouble(
			$this->payment->id,
			$this->payment->term,
			$this->payment->order,
			$this->payment->amount,
			$type->sid(),
			array(Status::SUCCESS, Status::PROCESSED)
		);

		if ($paymentExist) {
			return '-3';
		}

		switch ($type->sid()) {

			case Type::AUTH:
			case Type::SALE:
			case Type::PAYMENT:
				break;

			case Type::COMPLETE:

				// completing auth request
				$payment = self::find(
					$this->payment->term,
					$this->payment->order,
					$this->payment->irn,
					$this->payment->rrn,
					Type::AUTH,
					Status::SUCCESS
				);

				if (!$payment) {
					return '-2';
				}
				break;

			case Type::REFUND:

				// refund for finished processing: sale, complete, payment
				$payment = self::find(
					$this->payment->term,
					$this->payment->order,
					$this->payment->irn,
					$this->payment->rrn,
					array(Type::SALE, Type::COMPLETE, Type::PAYMENT),
					Status::SUCCESS
				);

				if (!$payment) {

					// refund for not finishing processing: auth
					$payment = self::find(
						$this->payment->term,
						$this->payment->order,
						$this->payment->irn,
						$this->payment->rrn,
						Type::AUTH,
						Status::SUCCESS
					);

					if (!$payment) {
						return '-2';
					}

				}
				break;

		}

		return '00';

	}
1305286
public boolean confirmPayment(String orderNumber, String timestamp, String paid, String method, String authCode) {
		String base = new StringBuilder()
  	  .append(orderNumber)
  	  .append('|')
  	  .append(timestamp)
  	  .append('|')
  	  .append(paid)
  	  .append('|')
  	  .append(method)
  	  .append('|')
  	  .append(merchantSecret)
  	  .toString();
		
		return 
			StringUtils.equals(
				StringUtils.upperCase(DigestUtils.md5Hex(base)),
				authCode
			);
	}
857697
function before_process() {
    global $order, $order_totals, $db, $messageStack, $lp_avs, $lp_trans_num;
    $myorder = array();

    // Calculate the next expected order id
    $last_order_id = $db->Execute("select * from " . TABLE_ORDERS . " order by orders_id desc limit 1");
    $new_order_id = $last_order_id->fields['orders_id'];
    $new_order_id = ($new_order_id + 1);
    // add randomized suffix to order id to produce uniqueness ... since it's unwise to submit the same order-number twice to the gateway
    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6);

    // Build Info to send to Gateway
    $myorder["result"] = "LIVE";
    switch (MODULE_PAYMENT_LINKPOINT_API_TRANSACTION_MODE_RESPONSE) {
      case "TESTING: Successful": $myorder["result"] = "GOOD"; break;
      case "TESTING: Decline"   : $myorder["result"] = "DECLINE"; break;
      case "TESTING: Duplicate" : $myorder["result"] = "DUPLICATE"; break;
    }

    // "oid" - Order ID number must be unique. If not set, gateway will assign one.
    //$oid = zen_create_random_value(16, 'digits'); // Create a UID for the order
    $myorder["oid"] = $new_order_id; //"";    // time(); ????

    // prepare totals for submission
    $surcharges = 0;
    $creditsApplied = 0;
    global $order_totals;
    reset($order_totals);
    $myorder['subtotal'] = $myorder['tax'] = $myorder['shipping'] = $myorder['chargetotal'] = 0;
    for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
      if ($order_totals[$i]['code'] == '') continue;
      if (in_array($order_totals[$i]['code'], array('ot_total','ot_subtotal','ot_tax','ot_shipping'))) {
        if ($order_totals[$i]['code'] == 'ot_subtotal') $myorder["subtotal"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_tax')      $myorder["tax"]        += round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_shipping') $myorder["shipping"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_total')    $myorder["chargetotal"] = round($order_totals[$i]['value'],2);
      } else {
        global $$order_totals[$i]['code'];
        if (substr($order_totals[$i]['text'], 0, 1) == '-' || (isset($$order_totals[$i]['code']->credit_class) && $$order_totals[$i]['code']->credit_class == true)) {
          $creditsApplied += round($order_totals[$i]['value'],2);
        } else {
          $surcharges += round($order_totals[$i]['value'],2);
        }
      }
    }
    foreach(array('subtotal', 'tax', 'chargetotal', 'shipping') as $i) {
      if (isset($myorder[$i])) $myorder[$i] = number_format($myorder[$i], 2, '.', '');
    }

    if ($surcharges == 0 && $creditsApplied == 0 && $order->info['total'] >= $order->info['subtotal'] && sizeof($order->products) <= 20) {
    // itemized contents
      $num_line_items = 0;
      reset($order->products);
      for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = $order->products[$i]['id'];

        $myorder["items"][$num_line_items]['description'] = substr(htmlentities($order->products[$i]['name'], ENT_QUOTES, 'UTF-8'), 0, 128);
        $myorder["items"][$num_line_items]['quantity']    = $order->products[$i]['qty'];
        $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), 2, '.', '');
        // check and adjust for fractional quantities, which cannot be submitted as line-item details
        $q = $order->products[$i]['qty']; $q1 = strval($q); $q2 = (int)$q; $q3 = strval($q2);
        if ($q1 != $q3 || $myorder["items"][$num_line_items]['quantity'] * $myorder["items"][$num_line_items]['price'] != number_format($order->products[$i]['qty'] * $order->products[$i]['final_price'], 2, '.', '')) {
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $decimals) * $order->products[$i]['qty'], 2, '.', '');
          $myorder["items"][$num_line_items]['description'] = '(' . $order->products[$i]['qty'] . ' x )' . substr($myorder["items"][$num_line_items]['description'], 115);
        }

        if (isset($order->products[$i]['attributes'])) {
          $options_text_length = 0;
          for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
            $options_text_length += strlen($order->products[$i]['attributes'][$j]['option'] . $order->products[$i]['attributes'][$j]['value']);
          }
          if ($options_text_length < 128) {
            for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
              $myorder["items"][$num_line_items]['options' . $j]['name'] = substr(htmlentities($order->products[$i]['attributes'][$j]['option'], ENT_QUOTES, 'UTF-8'), 0, 128);
              $myorder["items"][$num_line_items]['options' . $j]['value'] = substr(htmlentities($order->products[$i]['attributes'][$j]['value'], ENT_QUOTES, 'UTF-8'), 0, 128);
            }
          }
        }
        // track one-time charges
        if ($order->products[$i]['onetime_charges'] != 0 ) {
          $num_line_items++;
          $myorder["items"][$num_line_items]['id']          = 'OTC';
          $myorder["items"][$num_line_items]['description'] = 'One Time Charges';
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), 2, '.', '');
        }
      }
/*
        // deal with surcharges/fees
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Surcharge';
        $myorder["items"][$num_line_items]['description'] = $order_totals[$i]['title'];
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($order_totals[$i]['value'], 2, '.', '');
        $myorder["subtotal"] += $surcharges;
*/

     // FirstData can't accept more than 20 line-item submissions per transaction
      if ($num_line_items > 20) {
        unset($myorder["items"]);
        $num_line_items = 0;
      }
      // Verify that the line-item math works
      for ($i=1, $n=$num_line_items; $i <= $n; $i++) {
        $sum2 += ($myorder["items"][$i]['quantity'] * $myorder["items"][$i]['price']);
      }
      if (strval($sum2) != strval($myorder['subtotal'])) {
        unset($myorder['items']);
        $num_line_items = 0;
      }
    }

    // Subtotal Sanity Check in case there are addon modules affecting calculations
    $sum1 = strval($myorder['subtotal'] + $myorder['shipping'] + $myorder['tax']);
    if ($sum1 > $myorder['chargetotal']) {
      foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
        if (isset($myorder[$i])) unset($myorder[$i]);
      }
    } elseif ($sum1 < $myorder['chargetotal']) {
      if ($num_line_items > 0 && $num_line_items < 20 && isset($myorder['items'])) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Adj';
        $myorder["items"][$num_line_items]['description'] = 'Rounding Adjustment';
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($myorder['chargetotal'] - $sum1, 2, '.', '');
        $myorder['subtotal'] += round($myorder['chargetotal'] - $sum1, 2);
        $myorder['subtotal'] = number_format($myorder['subtotal'], 2, '.', '');
      } else {
        foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
      }
    }
    // clean up zeros
    foreach(array('subtotal', 'tax', 'shipping') as $i) {
      if (isset($myorder[$i]) && $myorder[$i] == 0) unset($myorder[$i]);
    }

    $myorder["ip"]  = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $myorder["ponumber"]    = "";

    // CARD INFO
    $myorder["cardnumber"]   = $_POST['cc_number'];
    $myorder["cardexpmonth"] = $_POST['cc_expires_month'];
    $myorder["cardexpyear"]  = $_POST['cc_expires_year'];
    $myorder["cvmindicator"] = "provided";
    $myorder["cvmvalue"]     = $_POST['cc_cvv'];

    // BILLING INFO
    $myorder["userid"]   = $_SESSION['customer_id'];
    $myorder["customerid"] = $_SESSION['customer_id'];
    $myorder["name"]     = htmlentities($_POST['cc_owner'], ENT_QUOTES, 'UTF-8'); //$order->billing['firstname'] . ' ' . $order->billing['lastname']);
    $myorder["company"]  = htmlentities($order->billing['company'], ENT_QUOTES, 'UTF-8');
    $myorder["address1"] = htmlentities($order->billing['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["address2"] = htmlentities($order->billing['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["city"]     = $order->billing['city'];
    $myorder["state"]    = $order->billing['state'];
    $myorder["country"]  = $order->billing['country']['iso_code_2'];
    $myorder["phone"]    = $order->customer['telephone'];
    //$myorder["fax"]      = $order->customer['fax'];
    $myorder["email"]    = $order->customer['email_address'];
    $myorder["addrnum"]  = $order->billing['street_address'];   // Required for AVS. If not provided, transactions will downgrade.
    $myorder["zip"]      = $order->billing['postcode']; // Required for AVS. If not provided, transactions will downgrade.

    // SHIPPING INFO
    $myorder["sname"]     = htmlentities($order->delivery['firstname'] . ' ' . $order->delivery['lastname'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress1"] = htmlentities($order->delivery['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress2"] = htmlentities($order->delivery['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["scity"]     = $order->delivery['city'];
    $myorder["sstate"]    = $order->delivery['state'];
    $myorder["szip"]      = $order->delivery['postcode'];
    $myorder["scountry"]  = $order->delivery['country']['iso_code_2'];

    // MISC
    $myorder["comments"] = "Website Order";
    // $myorder["referred"] = "";
    $myorder["ordertype"]  = (MODULE_PAYMENT_LINKPOINT_API_AUTHORIZATION_MODE == 'Authorize Only' ? 'PREAUTH': 'SALE');
    $this->payment_status = $myorder["ordertype"];

    // send request to gateway
    $result = $this->_sendRequest($myorder);

    // alert to customer if communication failure
    if (!is_array($result)) {
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }

    // resubmit without subtotals if subtotal error occurs
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (in_array(substr($result['r_error'],0,10), array('SGS-002301', 'SGS-010503', 'SGS-005003'))) {
        foreach(array('items', 'subtotal', 'tax', 'shipping') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
        $myorder["oid"] .= '-b';
        $myorder["chargetotal"] = ($myorder["chargetotal"] - 0.01);
        $result = $this->_sendRequest($myorder);
        if (!is_array($result)) {
          $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }
      }
    }

// PARSE Results
    $all_response_info = '';
    foreach($result as $key=>$value) {
      $all_response_info .= ' ' .$key . '='.$value;
    }
    if ($this->code_debug) $messageStack->add_session('header', $all_response_info, 'caution');

    $chargetotal = $myorder["chargetotal"];

// prepare transaction logging info
    $cust_info = '';
    $cc_number = substr($myorder["cardnumber"], 0, 4) . str_repeat('X', abs(strlen($myorder["cardnumber"]) - 8)) . substr($myorder["cardnumber"], -4);
    foreach($myorder as $key=>$value) {
      if ($key != 'cardnumber') {
        if ($key == 'cvmvalue') {
          $value = '****';
        }
        if ($key == 'cardexpmonth') {
          $cc_month = $value;
        }
        if ($key == 'cardexpyear') {
          $cc_year = $value;
        }
        if (is_array($value)) $value = print_r($value, true);
        if (!in_array($key, array('keyfile', 'configfile', 'transactionorigin', 'terminaltype', 'host', 'port'))) $cust_info .= ' ' .$key . '=' . $value . ';';
      } else {
        $cust_info .= ' ' .$key . '=' . $cc_number . ';';
      }
    }
    // store last 4 digits of CC number
//    $order->info['cc_number'] = str_repeat('X', (strlen($myorder["cardnumber"]) - 4)) . substr($myorder["cardnumber"], -4);
    // store first and last 4 digits of CC number ... which is the Visa-standards-compliant approach, same as observed by Linkpoint's services
    $order->info['cc_number'] = $cc_number;

    $order->info['cc_type'] = $_POST['cc_type'];
    $order->info['cc_owner'] = $_POST['cc_owner'];
    $order->info['cc_cvv'] = '***';
    $order->info['cc_expires'] = '';// $_POST['cc_expires'];


    $lp_trans_num = $result['r_ordernum'];
    $transaction_tax = $result['r_tax']; // The calculated tax for the order, when the ordertype is calctax.
    $transaction_shipping = $result['r_shipping']; // The calculated shipping charges for the order, when the ordertype is calcshipping.
    $this->response_codes = $result['r_avs']; // AVS Response for transaction

    // these are used to update the order-status-history upon order completion
    $this->transaction_id = $result['r_tdate'] . ' Order Number/Code: ' . $result['r_ordernum'];
    $this->auth_code = $result['r_code']; // The approval code for this transaction.

//  Store Transaction history in Database
    $sql_data_array= array(array('fieldName'=>'lp_trans_num', 'value' => $result['r_ordernum'], 'type'=>'string'), // The order number associated with this transaction.
                           array('fieldName'=>'order_id', 'value' => $result['r_ordernum'], 'type'=>'integer'),
                           array('fieldName'=>'approval_code', 'value' => $result['r_code'], 'type'=>'string'), // The approval code for this transaction.
                           array('fieldName'=>'transaction_response_time', 'value' => $result['r_time'], 'type'=>'string'), // The time+date of the transaction server response.
                           array('fieldName'=>'r_error', 'value' => $result['r_error'], 'type'=>'string'),
                           array('fieldName'=>'customer_id', 'value' => $_SESSION['customer_id'] , 'type'=>'integer'),
                           array('fieldName'=>'avs_response', 'value' => $result['r_avs'], 'type'=>'string'), // AVS Response for transaction
                           array('fieldName'=>'transaction_result', 'value' => $result['r_approved'], 'type'=>'string'), // Transaction result: APPROVED, DECLINED, or FRAUD.
                           array('fieldName'=>'message', 'value' => $result['r_message'] . "\n" . $all_response_info, 'type'=>'string'), // Any message returned by the processor; e.g., CALL VOICE CENTER.
                           array('fieldName'=>'transaction_time', 'value' => $result['r_tdate'], 'type'=>'string'), // A server time-date stamp for this transaction.
                           array('fieldName'=>'transaction_reference_number', 'value' => $result['r_ref'], 'type'=>'string'), // Reference number returned by the CC processor.
                           array('fieldName'=>'fraud_score', 'value' => $result['r_score'], 'type'=>'integer'), // LinkShield fraud risk score.
                           array('fieldName'=>'cc_number', 'value' => $cc_number, 'type'=>'string'),
                           array('fieldName'=>'cust_info', 'value' => $cust_info, 'type'=>'string'),
                           array('fieldName'=>'chargetotal', 'value' => $chargetotal, 'type'=>'string'),
                           array('fieldName'=>'cc_expire', 'value' => $cc_month . '/' . $cc_year, 'type'=>'string'),
                           array('fieldName'=>'ordertype', 'value' => $myorder['ordertype'], 'type'=>'string'), // transaction type: PREAUTH or SALE
                           array('fieldName'=>'date_added', 'value' => 'now()', 'type'=>'noquotestring'));
    if (MODULE_PAYMENT_LINKPOINT_API_STORE_DATA == 'True') {
      $db->perform(TABLE_LINKPOINT_API, $sql_data_array);
    }

  //  Begin check of specific error conditions
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (substr($result['r_error'],0,10) == 'SGS-020005') $messageStack->add_session('checkout_payment', $result['r_error'], 'error');  // Error (Merchant config file is missing, empty or cannot be read)
      if (substr($result['r_error'],0,10) == 'SGS-005000') $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_GENERAL_ERROR . '<br />' . $result['r_error'], 'error'); // The server encountered a database error
      if (substr($result['r_error'],0,10) == 'SGS-000001' || strstr($result['r_error'], 'D:Declined') || strstr($result['r_error'], 'R:Referral')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-005005' || strstr($result['r_error'], 'Duplicate transaction')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DUPLICATE_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-002301') $messageStack->add_session('checkout_payment', 'Subtotal miscalculation. Please notify the storeowner.' . '<br />' . $result['r_error'], 'error');
    }
  //  End specific error conditions

  //  Begin Transaction Status does not equal APPROVED
    if ($result["r_approved"] != "APPROVED") {
      // alert to customer:
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE, 'caution');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }
  //  End Transaction Status does not equal APPROVED

    $avs_meanings = array();
    $avs_meanings['YY'] = ' - Street Address and Zip Code match.';
    $avs_meanings['YN'] = ' - Street Address matches but Zip Code does NOT match.';
    $avs_meanings['YX'] = ' - Street Address matches, but Zip Code comparison unavailable.';
    $avs_meanings['NY'] = ' - Street Address DOES NOT match, but Zip Code matches.';
    $avs_meanings['XY'] = ' - Street Address check not available, but Zip Code matches.';
    $avs_meanings['NN'] = ' - Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.';
    $avs_meanings['NX'] = ' - Street Address DOES NOT MATCH and Zip Code comparison unavailable.';
    $avs_meanings['XN'] = ' - Street Address check not available. Zip Code DOES NOT MATCH.';
    $avs_meanings['XX'] = ' - No validation for address or zip code could be performed (not available from issuing bank).';

    // Possible Fraud order. Allow transaction to process, but notify shop for owner to take appropriate action on order
    if (($result["r_approved"] == "APPROVED") && (substr($result['r_code'], 17, 2) != "YY")  && MODULE_PAYMENT_LINKPOINT_API_FRAUD_ALERT == 'Yes') {
      //DEBUG: $messageStack->add_session('header', 'possible fraud situation--> ' . $result['r_code'], 'caution');
      $message = 'Potential Fraudulent Order - Bad Address - Action Required' . "\n" .
                 'This alert occurs because the "Approval Code" below does not contain the expected YY response.' . "\n" .
                 'Thus, you might want to verify the address with the customer prior to shipping, or be sure to use Registered Mail with Signature Required in case they file a chargeback.' . "\n\n" .
                 'Customer Name: ' . $order->customer['firstname'] . ' ' . $order->customer['lastname'] . "\n\n" .
                 'AVS Result: ' . $result['r_avs'] . $avs_meanings[substr($result['r_avs'],0,2)] . "\n\n" .
                 'Order Number: ' . $lp_trans_num . "\n" .
                 'Transaction Date and Time: ' . $result['r_time'] . "\n" .
                 'Approval Code: ' . $result['r_code'] . "\n" .
                 'Reference Number: ' . $result['r_ref'] . "\n\n" .
                 'Error Message: ' . $result['r_error'] . "\n\n" .
                 'Transaction Result: ' . $result['r_approved'] . "\n\n" .
                 'Message: ' . $result['r_message'] . "\n\n" .
                 'Fraud Score: ' . ($result['r_score'] == '' ? 'Not Enabled' : $result['r_score']) . "\n\n" .
                 'AVS CODE MEANINGS: ' . "\n" .
                 'YY** = Street Address and Zip Code match.' . "\n" .
                 'YN** = Street Address matches but Zip Code does NOT match.' . "\n" .
                 'YX** = Street Address matches, but Zip Code comparison unavailable.' . "\n" .
                 'NY** = Street Address DOES NOT match, but Zip Code matches.' . "\n" .
                 'XY** = Street Address check not available, but Zip Code matches.' . "\n" .
                 'NN** = Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.' . "\n" .
                 'NX** = Street Address DOES NOT MATCH and Zip Code comparison unavailable.' . "\n" .
                 'XN** = Street Address check not available. Zip Code DOES NOT MATCH.' . "\n" .
                 'XX** = Neither validation is available.' . "\n";
      $html_msg['EMAIL_MESSAGE_HTML'] = nl2br($result['r_message']);
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, 'Potential Fraudulent Order - Bad Address - Action Required - ' . $lp_trans_num, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'fraudalert');
    }
  // end fraud alert
  }
471837
def add_page_body
      payment_enabled = !Settings.payment.disabled

      @pdf.stroke_color '999999'

      #===============================
      # Invoice Reference
      #===============================
      @pdf.float do
        original_color = @pdf.fill_color
        @pdf.fill_color "F0F0F0"
        @pdf.fill_rounded_rectangle [310,@pdf.cursor], 230, 50, 5
        @pdf.fill_color = original_color

        @pdf.text_box "Your Reference", at: [310,@pdf.cursor], width: 65, height: 13, align: :center, valign: :center,
                      style: :bold_italic, size: 7

        @pdf.text_box @data[:invoice_reference], at: [310,@pdf.cursor], width: 230, height: 50, align: :center, valign: :center,
                      style: :bold
      end

      #===============================
      # Customer information
      #===============================
      @pdf.text @data[:customer_name], align: :left, inline_format: true

      if @data[:customer_email]
        @pdf.text "<color rgb='999999'>#{@data[:customer_email]}</color>", align: :left, inline_format: true
      end

      if @data[:customer_billing_address]
        @pdf.move_down 5
        @pdf.text "<color rgb='999999'>#{@data[:customer_billing_address]}</color>", align: :left, inline_format: true, style: :italic, size: 9
      end

      #===============================
      # Summary
      #===============================
      @pdf.move_down 40
      @pdf.font_size(20) { @pdf.text 'Summary', style: :bold }
      @pdf.stroke_horizontal_rule
      @pdf.move_down 10

      summary_data_amount = @data[:invoice_price]
      summary_data_amount = @data[:invoice_total_payable_with_tax] if payment_enabled

      summary_data = []
      summary_data << ['Period', 'Total Payable' + (@data[:invoice_tax_pips] > 0 ? "\n<font size='8'><i>(incl. GST)</i></font>" : '')]
      summary_data << ["#{@data[:period_started_at].strftime("%B, %e %Y")} to #{@data[:period_ended_at].strftime("%B, %e %Y")}",money(summary_data_amount)]

      # Draw Table background
      bg_height = @data[:invoice_tax_pips] > 0 ? 58 : 50
      @pdf.float do
        original_color = @pdf.fill_color
        @pdf.fill_color "d1e17c"
        @pdf.fill_rounded_rectangle [0,@pdf.cursor], 540, bg_height, 5
        @pdf.fill_color = original_color
      end

      # Draw Table
      @pdf.table(summary_data) do |t|
        t.header = true
        t.width = 540
        t.column_widths = [435,105]
        t.cell_style = { borders: [] }
        t.row(0).font_style = :bold

        t.cell_style = { padding: [5, 5, 5, 10], inline_format: true }
        t.cells.style do |c|
          if c.column == 1
            c.align = :center
          end
        end
      end

      @pdf.move_down 10
      @pdf.indent(5) do
        @pdf.font_size(8) do
          @pdf.text "<color rgb='999999'> This charge will appear as INV #{@data[:invoice_reference]} on your bank statement.</color>", inline_format: true
          @pdf.text "<color rgb='999999'> Charges are all displayed in #{@data[:invoice_currency_name]} (#{@data[:invoice_currency]})</color>", inline_format: true
          if @data[:invoice_fully_paid]
            @pdf.text "<color rgb='999999'>  No credit card payments required for this invoice</color>", inline_format: true
          else
            @pdf.text "<color rgb='999999'>  Your designated credit card will be charged on #{@data[:period_charge_date].strftime("%B,%e %Y")} at midnight UTC by Maestrano Pty Ltd as service provider to the #{MnoEnterprise.app_name} platform.</color>", inline_format: true
          end
        end
      end

      #===============================
      # Credit Remaining
      # ---
      # Only if greater than zero
      #===============================
      if @data[:customer_current_credit] && @data[:customer_current_credit].positive?
        @pdf.move_down 5
        @pdf.indent(5) do
          @pdf.font_size(8) do
            @pdf.text "<color rgb='999999'>  Note that your credit is shared with any organization you may have created</color>", inline_format: true
          end
        end

        @pdf.move_up 28

        @pdf.float do
          original_color = @pdf.fill_color
          @pdf.fill_color "67BBE9"
          @pdf.fill_rounded_rectangle [445,@pdf.cursor], 95, 50, 5
          @pdf.fill_color = original_color

          @pdf.text_box "Credit Remaining", at: [445,@pdf.cursor], width: 95, height: 23, align: :center, valign: :center,
                        style: :bold, size: 10

          @pdf.text_box money(@data[:customer_current_credit]), at: [445,@pdf.cursor], width: 95, height: 37, align: :center, valign: :bottom
        end

        @pdf.move_down 40
      end

      if payment_enabled
        #===============================
        # Account Situation
        #===============================
        @pdf.move_down 30
        @pdf.font_size(20) { @pdf.text 'Account Situation', style: :bold }
        @pdf.stroke_horizontal_rule
        @pdf.move_down 10

        # Situation Data
        situation_data = []
        # Header
        situation_data << [
          '',
          '',
          'Due Last Month',
          '',
          'Paid (Thank You)',
          '',
          'This Month',
          '',
          'Credit',
          '',
          'Total'
        ]

        #Content
        situation_data << [
          '',
          '',
          money(@data[:invoice_previous_total_due]),
          '-',
          money(@data[:invoice_previous_total_paid]),
          '+',
          money(@data[:invoice_price]),
          '-',
          money(@data[:invoice_credit_paid]),
          '=',
          money(@data[:invoice_total_payable])
        ]

        # Draw background
        @pdf.float do
          original_color = @pdf.fill_color
          @pdf.fill_color "F0F0F0"
          @pdf.fill_rounded_rectangle [0,@pdf.cursor], 540, 50, 5
          @pdf.fill_color = original_color
        end


        # Draw left background
        @pdf.float do
          original_color = @pdf.fill_color
          @pdf.fill_color "E0E0E0"
          @pdf.fill_rounded_rectangle [0,@pdf.cursor], 80, 50, 5
          @pdf.fill_color = original_color
          @pdf.move_down 21
          if @data[:invoice_tax_pips] > 0
            @pdf.text_box 'Excl. GST', at: [12,@pdf.cursor]
          else
            @pdf.text_box 'Details', at: [20,@pdf.cursor]
          end
        end

        # Draw table
        @pdf.table(situation_data) do |t|
          t.header = true
          t.width = 540
          t.column_widths = [75,18,75,18,75,18,75,18,75,18,75]
          t.row(0).font_style = :bold
          t.row(0).size = 8
          t.row(0).height = 22
          t.row(1).height = 25

          t.cell_style = {
            borders: [],
            overflow: :shrink_to_fit,
            align: :center
          }

          # Color the '+','-' and '=' characters
          t.cells.style do |c|
            if c.row == 1 && c.column.odd?
              c.text_color = "a8a8a8"
            end
          end
        end


        #=================================
        # Account Situation - Tax Section
        #=================================
        if @data[:invoice_tax_pips] > 0

          #-----------------
          # GST row
          #-----------------
          @pdf.move_down 8

          table_data = []
          table_data << [
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'GST',
            '+',
            money(@data[:invoice_tax_payable]),
          ]

          # Draw table background
          @pdf.float do
            original_color = @pdf.fill_color
            @pdf.fill_color "F0F0F0"
            @pdf.fill_rounded_rectangle [368,@pdf.cursor], 172, 24, 5
            @pdf.fill_color = original_color
          end

          # Draw left background
          @pdf.float do
            original_color = @pdf.fill_color
            @pdf.fill_color "FAB451"
            @pdf.fill_rounded_rectangle [368,@pdf.cursor], 80, 24, 5
            @pdf.fill_color = original_color
          end

          @pdf.table(table_data) do |t|
            t.header = true
            t.width = 540
            t.column_widths = [75,18,75,18,75,18,75,18,75,18,75]
            t.row(0).height = 25

            t.cell_style = {
              borders: [],
              overflow: :shrink_to_fit,
              align: :center
            }

            # Color the '+','-' and '=' characters
            t.cells.style do |c|
              if c.row == 0 && c.column.odd?
                c.text_color = "a8a8a8"
              end
            end
          end


          #-----------------
          # Total (incl. GST)
          #-----------------
          @pdf.move_down 5

          table_data = []
          table_data << [
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'Total (incl. GST)',
            '=',
            money(@data[:invoice_total_payable_with_tax]),
          ]

          # Draw table background
          @pdf.float do
            original_color = @pdf.fill_color
            @pdf.fill_color "F0F0F0"
            @pdf.fill_rounded_rectangle [368,@pdf.cursor], 172, 24, 5
            @pdf.fill_color = original_color
          end

          # Draw left background
          @pdf.float do
            original_color = @pdf.fill_color
            @pdf.fill_color "DAE173"
            @pdf.fill_rounded_rectangle [368,@pdf.cursor], 80, 24, 5
            @pdf.fill_color = original_color
          end

          @pdf.table(table_data) do |t|
            t.header = true
            t.width = 540
            t.row(0).font_style = :bold
            t.column_widths = [75,18,75,18,75,18,75,18,75,18,75]
            t.row(0).height = 25

            t.cell_style = {
              borders: [],
              overflow: :shrink_to_fit,
              align: :center
            }

            # Color the '+','-' and '=' characters
            t.cells.style do |c|
              if c.row == 0 && c.column.odd?
                c.text_color = "a8a8a8"
              end
            end
          end
        end
      end

      #===============================
      # Details
      #===============================
      @pdf.start_new_page
      @pdf.font_size(20) { @pdf.text 'Details', style: :bold }
      @pdf.stroke_horizontal_rule
      @pdf.move_down 10

      app_details_data = []
      app_details_data << ['Product', 'Type', 'Usage', 'Price' + (@data[:invoice_tax_pips] > 0 ? "\n<font size='8'><i>(excl. GST)</i></font>" : '')]
      app_details_data += @data[:billing_report]

      @pdf.table(app_details_data) do |t|
        t.header = true
        t.width = 540
        t.row_colors = ["FFFFFF", "F0F0F0"]
        t.column_widths = [240,100,100,100]
        t.cell_style = { borders: [:bottom],
                         border_width: 1,
                         border_color: "999999",
                         inline_format: true
        }
        t.row(0).borders = [:bottom]
        t.row(0).border_width = 2
        t.row(0).font_style = :bold
      end
    end
565745
function confirmation() {
    $confirmation = array('title' => '',
                          'fields' => array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_FIRSTNAME,
                                                  'field' => $_POST['paypalwpp_cc_firstname']),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_LASTNAME,
                                                  'field' => $_POST['paypalwpp_cc_lastname']),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_TYPE,
                                                  'field' => $this->cc_card_type),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_NUMBER,
                                                  'field' => substr($_POST['paypalwpp_cc_number'], 0, 4) . str_repeat('X', (strlen($_POST['paypalwpp_cc_number']) - 8)) . substr($_POST['paypalwpp_cc_number'], -4)),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_EXPIRES,
                                                  'field' => strftime('%B, %Y', mktime(0,0,0,$_POST['paypalwpp_cc_expires_month'], 1, '20' . $_POST['paypalwpp_cc_expires_year'])),
                                            (isset($_POST['paypalwpp_cc_issuenumber']) ? array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_ISSUE_NUMBER,
                                                  'field' => $_POST['paypalwpp_cc_issuenumber']) : '')
                                            )));
    // 3D-Secure
    if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && $this->requiresLookup($_POST['paypalwpp_cc_number']) == true) {
          $confirmation['fields'][count($confirmation['fields'])] = array(
              'title' => '',
              'field' => '<div id="' . $this->code.'-cc-securetext"><p>' .
                         '<a href="javascript:void window.open(\'vbv_learn_more.html\',\'vbv_service\',\'width=550,height=450\')">' .
                         zen_image(DIR_WS_IMAGES.'3ds/vbv_learn_more.gif') . '</a>' .
                         '<a href="javascript:void window.open(\'mcs_learn_more.html\',\'mcsc_service\',\'width=550,height=450\')">' .
                         zen_image(DIR_WS_IMAGES.'3ds/mcsc_learn_more.gif') . '</a></p>' .
                         '<p>' . TEXT_3DS_CARD_MAY_BE_ENROLLED . '</p></div>');
    }
    return $confirmation;
  }
575469
def cancel_invoice(self, invoice_id):
        
        return self._create_put_request(
            resource=INVOICES,
            billomat_id=invoice_id,
            command=CANCEL,
        )
821399
public function invoices($includePending = false, $parameters = [])
    {
        $invoices = [];

        $parameters = array_merge(['limit' => 24], $parameters);

        $stripeInvoices = $this->asStripeCustomer()->invoices($parameters);

        // Here we will loop through the Stripe invoices and create our own custom Invoice
        // instances that have more helper methods and are generally more convenient to
        // work with than the plain Stripe objects are. Then, we'll return the array.
        if (! is_null($stripeInvoices)) {
            foreach ($stripeInvoices->data as $invoice) {
                if ($invoice->paid || $includePending) {
                    $invoices[] = new Invoice($this, $invoice);
                }
            }
        }

        return new Collection($invoices);
    }
777278
def create_invoices(invoices)
      b = Builder::XmlMarkup.new
      request_xml = b.Invoices {
        invoices.each do | invoice |
          invoice.to_xml(b)
        end
      }

      response_xml = http_put(@client, "#{@xero_url}/Invoices?SummarizeErrors=false", request_xml, {})

      response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'})
      response.invoices.each_with_index do | response_invoice, index |
        invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id
      end
      response
    end
935412
function selection() {
    global $order;

    for ($i=1; $i<13; $i++) {
      $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B - (%m)',mktime(0,0,0,$i,1,2000)));
    }

    $today = getdate();
    for ($i=$today['year']; $i < $today['year']+10; $i++) {
      $expires_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
    }

    $onFocus = ' onfocus="methodSelect(\'pmt-' . $this->code . '\')"';

    if ($this->gateway_mode == 'offsite') {
      $selection = array('id' => $this->code,
                         'module' => $this->title);
    } else {
      $selection = array('id' => $this->code,
                         'module' => $this->title,
                         'fields' => array(array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_OWNER,
                                                 'field' => zen_draw_input_field('authorizenet_cc_owner', $order->billing['firstname'] . ' ' . $order->billing['lastname'], 'id="'.$this->code.'-cc-owner"' . $onFocus . ' autocomplete="off"'),
                                               'tag' => $this->code.'-cc-owner'),
                                         array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_NUMBER,
                                               'field' => zen_draw_input_field('authorizenet_cc_number', '', 'id="'.$this->code.'-cc-number"' . $onFocus . ' autocomplete="off"'),
                                               'tag' => $this->code.'-cc-number'),
                                         array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_EXPIRES,
                                               'field' => zen_draw_pull_down_menu('authorizenet_cc_expires_month', $expires_month, strftime('%m'), 'id="'.$this->code.'-cc-expires-month"' . $onFocus) . '&nbsp;' . zen_draw_pull_down_menu('authorizenet_cc_expires_year', $expires_year, '', 'id="'.$this->code.'-cc-expires-year"' . $onFocus),
                                               'tag' => $this->code.'-cc-expires-month')));
      if (MODULE_PAYMENT_AUTHORIZENET_USE_CVV == 'True') {
        $selection['fields'][] = array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CVV,
                                       'field' => zen_draw_input_field('authorizenet_cc_cvv', '', 'size="4" maxlength="4"' . ' id="'.$this->code.'-cc-cvv"' . $onFocus . ' autocomplete="off"') . ' ' . '<a href="javascript:popupWindow(\'' . zen_href_link(FILENAME_POPUP_CVV_HELP) . '\')">' . MODULE_PAYMENT_AUTHORIZENET_TEXT_POPUP_CVV_LINK . '</a>',
                                       'tag' => $this->code.'-cc-cvv');
      }
    }
    return $selection;
  }
207975
def show
      @invoice = MnoEnterprise::Invoice.where(slug: params[:id].upcase).reload.first
      authorize! :manage_billing, current_user.organizations.find(@invoice.organization_id)
    
      respond_to do |format|
        if @invoice
          filename = "Invoice - #{@invoice.slug}.pdf"
          pdf_view = MnoEnterprise::InvoicePdf.new(@invoice).render
          format.html { send_data pdf_view, filename: filename, type: "application/pdf", disposition: 'inline'  }
        else
          format.html { redirect_to root_path, :alert => 'Sorry, the page requested could not be displayed' }
        end
      end
    end
851393
def init_cart            
      # Check if the cart ID is defined and that it exists in the database
      create_new_invoice = false
      if session[:cart_id]
        @invoice = Caboose::Invoice.where(:id => session[:cart_id]).first
        create_new_invoice = true if @invoice.nil? || @invoice.status != 'cart'                    
      else                        
        create_new_invoice = true                         
      end

      if create_new_invoice # Create an invoice to associate with the session        
        @invoice = Caboose::Invoice.new        
        @invoice.site_id          = @site ? @site.id : nil
        @invoice.status           = Caboose::Invoice::STATUS_CART
        @invoice.financial_status = Caboose::Invoice::STATUS_PENDING
        @invoice.date_created     = DateTime.now
        @invoice.referring_site   = request.env['HTTP_REFERER']
        @invoice.landing_page     = request.fullpath
        @invoice.landing_page_ref = params[:ref] || nil
        @invoice.payment_terms    = @site.store_config.default_payment_terms
        @invoice.save
        
        InvoiceLog.create(
          :invoice_id     => @invoice.id,          
          :user_id        => logged_in_user.id,
          :date_logged    => DateTime.now.utc,
          :invoice_action => InvoiceLog::ACTION_INVOICE_CREATED                
        )
        
        # Save the cart ID in the session
        session[:cart_id] = @invoice.id
      end                  
    end
302628
def customer_outstanding_invoices(code = nil)
      now = Time.now
      customer_invoices(code).reject do |i| 
        i[:paidTransactionId] || i[:billingDatetime] > now
      end
    end
1155051
public function transformFromOrder(OrderInterface $order, InvoiceInterface $invoice)
    {
        $event = new OrderTransformEvent($order);
        $this->eventDispatcher->dispatch(TransformerEvents::PRE_ORDER_TO_INVOICE_TRANSFORM, $event);

        $invoice->setName($order->getBillingName());
        $invoice->setAddress1($order->getBillingAddress1());
        $invoice->setAddress2($order->getBillingAddress2());
        $invoice->setAddress3($order->getBillingAddress3());
        $invoice->setCity($order->getBillingCity());
        $invoice->setCountry($order->getBillingCountryCode());
        $invoice->setPostcode($order->getBillingPostcode());

        $invoice->setEmail($order->getBillingEmail());
        $invoice->setFax($order->getBillingFax());
        $invoice->setMobile($order->getBillingMobile());
        $invoice->setPhone($order->getBillingPhone());
        $invoice->setReference($order->getReference());

        $invoice->setCurrency($order->getCurrency());
        $invoice->setCustomer($order->getCustomer());
        $invoice->setTotalExcl($order->getTotalExcl());
        $invoice->setTotalInc($order->getTotalInc());

        $invoice->setPaymentMethod($order->getPaymentMethod());

        $invoice->setLocale($order->getLocale());

        foreach ($order->getOrderElements() as $orderElement) {
            $invoiceElement = $this->createInvoiceElementFromOrderElement($orderElement);
            $invoiceElement->setInvoice($invoice);
            $invoice->addInvoiceElement($invoiceElement);
        }

        if ($order->getDeliveryCost() > 0) {
            $this->addDelivery($invoice, $order);
        }

        $invoice->setStatus(InvoiceInterface::STATUS_OPEN);

        $event = new InvoiceTransformEvent($invoice);
        $this->eventDispatcher->dispatch(TransformerEvents::POST_ORDER_TO_INVOICE_TRANSFORM, $event);
    }
211016
private function invoice() {
		$invoiceService = df_o(InvoiceService::class); /** @var InvoiceService $invoiceService */
		/** @var Invoice|DfInvoice $result */
		if (!($result = $invoiceService->prepareInvoice($this->o()))) {
			throw new LE(__('We can\'t save the invoice right now.'));
		}
		if (!$result->getTotalQty()) {
			throw new LE(__('You can\'t create an invoice without products.'));
		}
		df_register('current_invoice', $result);
		/**
		 * 2016-03-26
		 * @used-by \Magento\Sales\Model\Order\Invoice::register()
		 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Invoice.php#L599-L609
		 * Используем именно @see \Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE,
		 * а не @see \Magento\Sales\Model\Order\Invoice::CAPTURE_OFFINE,
		 * чтобы была создана транзакция capture.
		 */
		$result->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
		$result->register();
		return $result;
	}
364816
function _doCapt($oID, $captureType = 'Complete', $amt = 0, $currency = 'USD', $note = '') {
    global $db, $doPayPal, $messageStack;
    $doPayPal = $this->paypal_init();

    //@TODO: Read current order status and determine best status to set this to
    $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID;

    $orig_order_amount = 0;
    $doPayPal = $this->paypal_init();
    $proceedToCapture = false;
    $captureNote = strip_tags(zen_db_input($_POST['captnote']));
    if (isset($_POST['captfullconfirm']) && $_POST['captfullconfirm'] == 'on') {
      $proceedToCapture = true;
    } else {
      $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_CAPTURE_FULL_CONFIRM_ERROR, 'error');
    }
    if (isset($_POST['captfinal']) && $_POST['captfinal'] == 'on') {
      $captureType = 'Complete';
    } else {
      $captureType = 'NotComplete';
    }
    if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_PAYPAL_ENTRY_CAPTURE_BUTTON_TEXT_FULL) {
      $captureAmt = (float)$_POST['captamt'];
      if ($captureAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
        $proceedToCapture = false;
      }
    }
    // look up history on this order from PayPal table
    $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID  AND parent_txn_id = '' ";
    $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
    $zc_ppHist = $db->Execute($sql);
    if ($zc_ppHist->RecordCount() == 0) return false;
    $txnID = $zc_ppHist->fields['txn_id'];
    /**
     * Submit capture request to PayPal
     */
    if ($proceedToCapture) {
      $response = $doPayPal->DoCapture($txnID, $captureAmt, $currency, $captureType, '', $captureNote);
      $error = $this->_errorHandler($response, 'DoCapture');
      $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
      if (!$error) {
        if (isset($response['PNREF'])) {
          if (!isset($response['AMT'])) $response['AMT'] = $captureAmt;
          if (!isset($response['ORDERTIME'])) $response['ORDERTIME'] = date("M-d-Y h:i:s");
        }
        // Success, so save the results
        $sql_data_array = array('orders_id' => (int)$oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'FUNDS COLLECTED. Trans ID: ' . urldecode($response['TRANSACTIONID']) . $response['PNREF']. "\n" . ' Amount: ' . urldecode($response['AMT']) . ' ' . $currency . "\n" . 'Time: ' . urldecode($response['ORDERTIME']) . "\n" . (isset($response['RECEIPTID']) ? 'Receipt ID: ' . urldecode($response['RECEIPTID']) : 'Auth Code: ' . $response['AUTHCODE']) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $captureNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_CAPT_INITIATED, urldecode($response['AMT']), urldecode($response['RECEIPTID'] . $response['AUTHCODE']). $response['PNREF']), 'success');
        return true;
      }
    }
  }