Creating shipping functionality for UPS
432028
def create_shipment(origin, destination, packages, options={})
      @options             = @options.merge(options)
      origin, destination  = upsified_location(origin), upsified_location(destination)
      options              = @options.merge(options)
      options[:test]       = options[:test].nil? ? true : options[:test]
      packages             = Array(packages)
      access_request       = build_access_request
      ship_confirm_request = build_ship_confirm(origin, destination, packages, options)
      response             = commit(:shipconfirm, save_request(access_request.gsub("\n", "") + ship_confirm_request.gsub("\n", "")), options[:test])
      parse_ship_confirm_response(origin, destination, packages, response, options)
    end
817355
private function prepareShipping()
    {
        $shipping = array();
        if(!empty($this->_detailsTransactionByCode->getShipping())){
            $shipping = array(
                'addres' => array(
                    'street'    => $this->_detailsTransactionByCode->getShipping()->getAddress()->getStreet(),
                    'number'    => $this->_detailsTransactionByCode->getShipping()->getAddress()->getNumber(),
                    'complement' => $this->_detailsTransactionByCode->getShipping()->getAddress()->getComplement(),
                    'district'  => $this->_detailsTransactionByCode->getShipping()->getAddress()->getDistrict(),
                    'postalCode' => $this->_detailsTransactionByCode->getShipping()->getAddress()->getPostalCode(),
                    'city'      => $this->_detailsTransactionByCode->getShipping()->getAddress()->getCity(),
                    'state'     => $this->_detailsTransactionByCode->getShipping()->getAddress()->getState(),
                    'country'   => $this->_detailsTransactionByCode->getShipping()->getAddress()->getCountry()
                ),
                'type' => $this->_detailsTransactionByCode->getShipping()->getType()->getType(),
                'cost' => $this->_detailsTransactionByCode->getShipping()->getCost()->getCost()
            );
        }
        return $shipping;
    }
349080
protected function buildShipmentArray(
        array $sender,
        array $destination,
        array $parcel,
        array $options = []
    ) {
        $this->formatPostalCode($sender['address-details']['postal-zip-code']);
        $this->formatPostalCode($destination['address-details']['postal-zip-code']);
        $shipment_info = [
            'requested-shipping-point' => $destination['address-details']['postal-zip-code'],
            'cpc-pickup-indicator' => true,
            'delivery-spec' => [
                'service-code' => $parcel['service_code'],
                'sender' => $sender,
                'destination' => $destination,
                'parcel-characteristics' => $parcel,
                'preferences' => [
                    'show-packing-instructions' => $options['packing_instructions'] ?? true,
                ],
                'notification' => [],
                'settlement-info' => [
                    'contract-id' => '',
                    'intended-method-of-payment' => 'Account',
                ],
            ],
        ];

        if (!empty($options['option_codes'])) {
            $shipment_info['options']['option'] = $this->parseOptionCodes($options);
        }

        return $shipment_info;
    }
52618
def build_checkout_params(self, **kwargs):
        
        params = kwargs or {}
        if self.sender:
            params['senderName'] = self.sender.get('name')
            params['senderAreaCode'] = self.sender.get('area_code')
            params['senderPhone'] = self.sender.get('phone')
            params['senderEmail'] = is_valid_email(self.sender.get('email'))
            params['senderCPF'] = is_valid_cpf(self.sender.get('cpf'))
            params['senderCNPJ'] = is_valid_cnpj(self.sender.get('cnpj'))
            params['senderBornDate'] = self.sender.get('born_date')
            params['senderHash'] = self.sender.get('hash')

        if self.config.USE_SHIPPING:
            if self.shipping:
                params['shippingType'] = self.shipping.get('type')
                params['shippingAddressStreet'] = self.shipping.get('street')
                params['shippingAddressNumber'] = self.shipping.get('number')
                params['shippingAddressComplement'] = self.shipping.get(
                    'complement')
                params['shippingAddressDistrict'] = self.shipping.get(
                    'district')
                params['shippingAddressPostalCode'] = self.shipping.get(
                    'postal_code')
                params['shippingAddressCity'] = self.shipping.get('city')
                params['shippingAddressState'] = self.shipping.get('state')
                params['shippingAddressCountry'] = self.shipping.get('country',
                                                                     'BRA')
                if self.shipping.get('cost'):
                    params['shippingCost'] = self.shipping.get('cost')
        else:
            params['shippingAddressRequired'] = 'false'

        if self.extra_amount:
            params['extraAmount'] = self.extra_amount

        params['reference'] = self.reference
        params['receiverEmail'] = self.data['email']

        if self.redirect_url:
            params['redirectURL'] = self.redirect_url

        if self.notification_url:
            params['notificationURL'] = self.notification_url

        if self.abandon_url:
            params['abandonURL'] = self.abandon_url

        for i, item in enumerate(self.items, 1):
            params['itemId%s' % i] = item.get('id')
            params['itemDescription%s' % i] = item.get('description')
            params['itemAmount%s' % i] = item.get('amount')
            params['itemQuantity%s' % i] = item.get('quantity')
            params['itemWeight%s' % i] = item.get('weight')
            params['itemShippingCost%s' % i] = item.get('shipping_cost')

        if self.payment:

            params['paymentMethod'] = self.payment.get('method')
            params['paymentMode'] = self.payment.get('mode')

        if self.credit_card:
            params['billingAddressCountry'] = 'BRA'

            credit_card_keys_map = [
                ('creditCardToken', 'credit_card_token'),
                ('installmentQuantity', 'installment_quantity'),
                ('installmentValue', 'installment_value'),
                ('noInterestInstallmentQuantity',
                 'no_interest_installment_quantity'),
                ('creditCardHolderName', 'card_holder_name'),
                ('creditCardHolderCPF', 'card_holder_cpf'),
                ('creditCardHolderBirthDate', 'card_holder_birth_date'),
                ('creditCardHolderAreaCode', 'card_holder_area_code'),
                ('creditCardHolderPhone', 'card_holder_phone'),
                ('billingAddressStreet', 'billing_address_street'),
                ('billingAddressNumber', 'billing_address_number'),
                ('billingAddressComplement', 'billing_address_complement'),
                ('billingAddressDistrict', 'billing_address_district'),
                ('billingAddressPostalCode', 'billing_address_postal_code'),
                ('billingAddressCity', 'billing_address_city'),
                ('billingAddressState', 'billing_address_state'),
            ]

            for key_to_set, key_to_get in credit_card_keys_map:
                params[key_to_set] = self.credit_card.get(key_to_get)

        if self.pre_approval:

            params['preApprovalCharge'] = self.pre_approval.get('charge')
            params['preApprovalName'] = self.pre_approval.get('name')
            params['preApprovalDetails'] = self.pre_approval.get('details')
            params['preApprovalAmountPerPayment'] = self.pre_approval.get(
                'amount_per_payment')
            params['preApprovalMaxAmountPerPayment'] = self.pre_approval.get(
                'max_amount_per_payment')
            params['preApprovalPeriod'] = self.pre_approval.get('period')
            params['preApprovalMaxPaymentsPerPeriod'] = self.pre_approval.get(
                'max_payments_per_period')
            params['preApprovalMaxAmountPerPeriod'] = self.pre_approval.get(
                'max_amount_per_period')
            params['preApprovalInitialDate'] = self.pre_approval.get(
                'initial_date')
            params['preApprovalFinalDate'] = self.pre_approval.get(
                'final_date')
            params['preApprovalMaxTotalAmount'] = self.pre_approval.get(
                'max_total_amount')

        self.data.update(params)
        self.clean_none_params()
815276
def create_shipment(origin, destination, package, line_items = [], options = {})
      request_body = build_shipment_request(origin, destination, package, line_items, options)
      response = ssl_post(create_shipment_url(options), request_body, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE))
      parse_shipment_response(response)
    rescue ActiveUtils::ResponseError, ActiveShipping::ResponseError => e
      error_response(e.response.body, CPPWSShippingResponse)
    rescue MissingCustomerNumberError
      CPPWSShippingResponse.new(false, "Missing Customer Number", {}, :carrier => @@name)
    end
590196
function before_process() {
    global $response, $db, $order, $messageStack;
    $order->info['cc_type']    = $_POST['cc_type'];
    $order->info['cc_owner']   = $_POST['cc_owner'];
    $order->info['cc_number']  = str_pad(substr($_POST['cc_number'], -4), strlen($_POST['cc_number']), "X", STR_PAD_LEFT);
    $order->info['cc_expires'] = '';  // $_POST['cc_expires'];
    $order->info['cc_cvv']     = '***';
    $sessID = zen_session_id();

    // DATA PREPARATION SECTION
    unset($submit_data);  // Cleans out any previous data stored in the variable

    // Create a string that contains a listing of products ordered for the description field
    $description = '';
    for ($i=0; $i<sizeof($order->products); $i++) {
      $description .= $order->products[$i]['name'] . ' (qty: ' . $order->products[$i]['qty'] . ') + ';
    }
    // Remove the last "\n" from the string
    $description = substr($description, 0, -2);

    // Create a variable that holds the order time
    $order_time = date("F j, Y, g:i a");

    // Calculate the next expected order id (adapted from code written by Eric Stamper - 01/30/2004 Released under GPL)
    $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 authorize.net
    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6, 'chars');


    // Populate an array that contains all of the data to be sent to Authorize.net
    $submit_data = array(
                         'x_login' => trim(MODULE_PAYMENT_AUTHORIZENET_AIM_LOGIN),
                         'x_tran_key' => trim(MODULE_PAYMENT_AUTHORIZENET_AIM_TXNKEY),
                         'x_relay_response' => 'FALSE', // AIM uses direct response, not relay response
                         'x_delim_data' => 'TRUE',
                         'x_delim_char' => $this->delimiter,  // The default delimiter is a comma
                         'x_encap_char' => $this->encapChar,  // The divider to encapsulate response fields
                         'x_version' => '3.1',  // 3.1 is required to use CVV codes
                         'x_type' => MODULE_PAYMENT_AUTHORIZENET_AIM_AUTHORIZATION_TYPE == 'Authorize' ? 'AUTH_ONLY': 'AUTH_CAPTURE',
                         'x_method' => 'CC',
                         'x_amount' => number_format($order->info['total'], 2),
                         'x_currency_code' => $order->info['currency'],
                         'x_card_num' => $_POST['cc_number'],
                         'x_exp_date' => $_POST['cc_expires'],
                         'x_card_code' => $_POST['cc_cvv'],
                         'x_email_customer' => MODULE_PAYMENT_AUTHORIZENET_AIM_EMAIL_CUSTOMER == 'True' ? 'TRUE': 'FALSE',
                         'x_email_merchant' => MODULE_PAYMENT_AUTHORIZENET_AIM_EMAIL_MERCHANT == 'True' ? 'TRUE': 'FALSE',
                         'x_cust_id' => $_SESSION['customer_id'],
                         'x_invoice_num' => (MODULE_PAYMENT_AUTHORIZENET_AIM_TESTMODE == 'Test' ? 'TEST-' : '') . $new_order_id,
                         'x_first_name' => $order->billing['firstname'],
                         'x_last_name' => $order->billing['lastname'],
                         'x_company' => $order->billing['company'],
                         'x_address' => $order->billing['street_address'],
                         'x_city' => $order->billing['city'],
                         'x_state' => $order->billing['state'],
                         'x_zip' => $order->billing['postcode'],
                         'x_country' => $order->billing['country']['title'],
                         'x_phone' => $order->customer['telephone'],
                         'x_email' => $order->customer['email_address'],
                         'x_ship_to_first_name' => $order->delivery['firstname'],
                         'x_ship_to_last_name' => $order->delivery['lastname'],
                         'x_ship_to_address' => $order->delivery['street_address'],
                         'x_ship_to_city' => $order->delivery['city'],
                         'x_ship_to_state' => $order->delivery['state'],
                         'x_ship_to_zip' => $order->delivery['postcode'],
                         'x_ship_to_country' => $order->delivery['country']['title'],
                         'x_description' => $description,
                         'x_recurring_billing' => 'NO',
                         'x_customer_ip' => zen_get_ip_address(),
                         'x_po_num' => date('M-d-Y h:i:s'), //$order->info['po_number'],
                         'x_freight' => number_format((float)$order->info['shipping_cost'],2),
                         'x_tax_exempt' => 'FALSE', /* 'TRUE' or 'FALSE' */
                         'x_tax' => number_format((float)$order->info['tax'],2),
                         'x_duty' => '0',
                         'x_allow_partial_Auth' => 'FALSE', // unable to accept partial authorizations at this time

                         // Additional Merchant-defined variables go here
                         'Date' => $order_time,
                         'IP' => zen_get_ip_address(),
                         'Session' => $sessID );
    // force conversion to USD
    if ($order->info['currency'] != 'USD') {
      global $currencies;
      $submit_data['x_amount'] = number_format($order->info['total'] * $currencies->get_value('USD'), 2);
      $submit_data['x_currency_code'] = 'USD';
      unset($submit_data['x_tax'], $submit_data['x_freight']);
    }

    unset($response);
    $response = $this->_sendRequest($submit_data);
    $response_code = $response[0];
    $response_text = $response[3];
    $this->auth_code = $response[4];
    $this->transaction_id = $response[6];
    $this->avs_response= $response[5];
    $this->ccv_response= $response[38];
    $response_msg_to_customer = $response_text . ($this->commError == '' ? '' : ' Communications Error - Please notify webmaster.');

    $response['Expected-MD5-Hash'] = $this->calc_md5_response($response[6], $response[9]);
    $response['HashMatchStatus'] = ($response[37] == $response['Expected-MD5-Hash']) ? 'PASS' : 'FAIL';

    if ($response[0] == '3' && $response[2] == '103') $response['ErrorDetails'] = 'Invalid Transaction Key in AIM configuration.';
    if ($response[0] == '2' && $response[2] == '44') $response['ErrorDetails'] = 'Declined due to CVV refusal by issuing bank.';
    if ($response[0] == '2' && $response[2] == '45') $response['ErrorDetails'] = 'Declined due to AVS/CVV filters.';
    if ($response[0] == '2' && $response[2] == '65') $response['ErrorDetails'] = 'Declined due to custom CVV filters.';
    if ($response[0] == '3' && $response[2] == '66') $response['ErrorDetails'] = 'Transaction did not meet security guideline requirements.';
    if ($response[0] == '3' && $response[2] == '128') $response['ErrorDetails'] = 'Refused by customers bank.';
    if ($response[0] == '2' && $response[2] == '250') $response['ErrorDetails'] = 'Transaction submitted from a blocked IP address.';
    if ($response[0] == '2' && $response[2] == '251') $response['ErrorDetails'] = 'Declined by Fraud Detection Suite filter.';
    if ($response[0] == '4' && in_array($response[2], array('193', '252', '253'))) {
      $this->order_status = 1;
      $this->transaction_id .= ' ***NOTE: Held for review by merchant.';
      $response['ErrorDetails'] = 'Transaction held for review by merchant or fraud detection suite.';
    }

    $this->_debugActions($response, $order_time, $sessID);

    // If the MD5 hash doesn't match, then this transaction's authenticity cannot be verified.
    // Thus, order will be placed in Pending status
    if ($response['HashMatchStatus'] != 'PASS' && defined('MODULE_PAYMENT_AUTHORIZENET_AIM_MD5HASH') && MODULE_PAYMENT_AUTHORIZENET_AIM_MD5HASH != '') {
      $this->order_status = 1;
      $messageStack->add_session('header', MODULE_PAYMENT_AUTHORIZENET_AIM_TEXT_AUTHENTICITY_WARNING, 'caution');
    }

    // If the response code is not 1 (approved) then redirect back to the payment page with the appropriate error message
    if ($response_code != '1') {
      $messageStack->add_session('checkout_payment', $response_msg_to_customer . ' - ' . MODULE_PAYMENT_AUTHORIZENET_AIM_TEXT_DECLINED_MESSAGE, 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }
    if ($response[88] != '') {
      $_SESSION['payment_method_messages'] = $response[88];
    }
  }
1053393
function perweightunit() {
    global $order, $db;

    $this->code = 'perweightunit';
    $this->title = MODULE_SHIPPING_PERWEIGHTUNIT_TEXT_TITLE;
    $this->description = MODULE_SHIPPING_PERWEIGHTUNIT_TEXT_DESCRIPTION;
    $this->sort_order = MODULE_SHIPPING_PERWEIGHTUNIT_SORT_ORDER;
    $this->icon = '';
    $this->tax_class = MODULE_SHIPPING_PERWEIGHTUNIT_TAX_CLASS;
    $this->tax_basis = MODULE_SHIPPING_PERWEIGHTUNIT_TAX_BASIS;

    // disable only when entire cart is free shipping
    if (zen_get_shipping_enabled($this->code)) {
      $this->enabled = ((MODULE_SHIPPING_PERWEIGHTUNIT_STATUS == 'True') ? true : false);
    }

    if ($this->enabled) {
      // check MODULE_SHIPPING_PERWEIGHTUNIT_HANDLING_METHOD is in
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_PERWEIGHTUNIT_HANDLING_METHOD'");
      if ($check_query->EOF) {
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Handling Per Order or Per Box', 'MODULE_SHIPPING_PERWEIGHTUNIT_HANDLING_METHOD', 'Order', 'Do you want to charge Handling Fee Per Order or Per Box?', '6', '0', 'zen_cfg_select_option(array(\'Order\', \'Box\'), ', now())");
      }
    }

    if ( ($this->enabled == true) && ((int)MODULE_SHIPPING_PERWEIGHTUNIT_ZONE > 0) ) {
      $check_flag = false;
      $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . "
                             where geo_zone_id = '" . MODULE_SHIPPING_PERWEIGHTUNIT_ZONE . "'
                             and zone_country_id = '" . $order->delivery['country']['id'] . "'
                             order by zone_id");
      while (!$check->EOF) {
        if ($check->fields['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check->fields['zone_id'] == $order->delivery['zone_id']) {
          $check_flag = true;
          break;
        }
        $check->MoveNext();
      }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }
1169565
public function cmdGetShipping()
    {
        $result = $this->getListShipping();
        $this->outputFormat($result);
        $this->outputFormatTableShipping($result);
        $this->output();
    }
670577
function flat() {
      global $order, $db;

      $this->code = 'flat';
      $this->title = MODULE_SHIPPING_FLAT_TEXT_TITLE;
      $this->description = MODULE_SHIPPING_FLAT_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_SHIPPING_FLAT_SORT_ORDER;
      $this->icon = '';
      $this->tax_class = MODULE_SHIPPING_FLAT_TAX_CLASS;
      $this->tax_basis = MODULE_SHIPPING_FLAT_TAX_BASIS;

      // disable only when entire cart is free shipping
      if (zen_get_shipping_enabled($this->code)) {
        $this->enabled = ((MODULE_SHIPPING_FLAT_STATUS == 'True') ? true : false);
      }

      if ( ($this->enabled == true) && ((int)MODULE_SHIPPING_FLAT_ZONE > 0) ) {
        $check_flag = false;
        $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_SHIPPING_FLAT_ZONE . "' and zone_country_id = '" . $order->delivery['country']['id'] . "' order by zone_id");
        while (!$check->EOF) {
          if ($check->fields['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check->fields['zone_id'] == $order->delivery['zone_id']) {
            $check_flag = true;
            break;
          }
          $check->MoveNext();
        }

        if ($check_flag == false) {
          $this->enabled = false;
        }
      }
    }
601452
def ship(opts)
      opts = opts.merge(:sale_id => self.sale_id)
      Twocheckout::API.request(:post, 'sales/mark_shipped', opts)
    end
912152
public function run()
    {
        $this->_addShipmentsToOrder();
        $this->_addOrderAmountToOrderReference($this->currencyCode);
        $this->_confirmOrderReference();
        $this->_performAuthAndCaptureForOrderShipments();
        $this->_closeOrderReference();
        print HTML_LB.HTML_LB."Split Shipment Checkout Sample is Complete";
    }
437105
private function generateShippingOptions(array $shipping_options) {
      $response = [];
      $option_index = 1;

      foreach ($shipping_options as $option => $prices) {
        array_push($response, ['id' => strval($option_index), 'title' => $option, 'prices' => []]);

        // Register prices for the specific shipping option
        foreach ($prices as $service => $price) {
          if ($price < 0) {
            throw new Exception('Invalid negative price passed to "answerShippingQuery"');
          }

          $formatted_price = intval($price * 100);

          // Selects the most recent shipping option pushed into the array.
          array_push($response[$option_index - 1]['prices'], [
            'label' => $service, 'amount' => $formatted_price
          ]);
        }

        $option_index++;
      }

      return json_encode($response);
    }
60428
function before_process() {
    global $order, $doPayPal, $messageStack;
    $options = array();
    $optionsShip = array();
    $optionsNVP = array();

    $options = $this->getLineItemDetails($this->selectCurrency($order->info['currency']));
    if (defined('MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT') && MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT == 'Instant Only') $options['ALLOWEDPAYMENTMETHOD'] = 'InstantPaymentOnly';

    //$this->zcLog('before_process - 1', 'Have line-item details:' . "\n" . print_r($options, true));

    // Initializing DESC field: using for comments related to tax-included pricing, populated by getLineItemDetails()
    $options['DESC'] = '';

    $doPayPal = $this->paypal_init();
    $this->zcLog('before_process - EC-1', 'Beginning EC mode');
     /****************************************
      * Do EC checkout
      ****************************************/
      // do not allow blank address to be sent to PayPal
      if ($_SESSION['paypal_ec_payer_info']['ship_street_1'] != '' && strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE') {
        $options = array_merge($options,
                 array('SHIPTONAME'   => $_SESSION['paypal_ec_payer_info']['ship_name'],
                       'SHIPTOSTREET' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
                       'SHIPTOSTREET2'=> $_SESSION['paypal_ec_payer_info']['ship_street_2'],
                       'SHIPTOCITY'   => $_SESSION['paypal_ec_payer_info']['ship_city'],
                       'SHIPTOSTATE'  => $_SESSION['paypal_ec_payer_info']['ship_state'],
                       'SHIPTOZIP'    => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
                       'SHIPTOCOUNTRYCODE'=> $_SESSION['paypal_ec_payer_info']['ship_country_code'],
                       ));
        $this->zcLog('before_process - EC-2', 'address overrides added:' . "\n" . print_r($options, true));
      }

      $this->zcLog('before_process - EC-3', 'address info added:' . "\n" . print_r($options, true));

      $options['BUTTONSOURCE'] = $this->buttonSourceEC;

      // If the customer has changed their shipping address,
      // override the shipping address in PayPal with the shipping
      // address that is selected in Zen Cart.
      if ($order->delivery['street_address'] != '' && $order->delivery['street_address'] != $_SESSION['paypal_ec_payer_info']['ship_street_1'] && $_SESSION['paypal_ec_payer_info']['ship_street_1'] != '') {
        $_GET['markflow'] = 2;
        if (($address_arr = $this->getOverrideAddress()) !== false) {
          // set the override var
          $options['ADDROVERRIDE'] = 1;
          // set the address info
          $options['SHIPTONAME']    = $address_arr['entry_firstname'] . ' ' . $address_arr['entry_lastname'];
          $options['SHIPTOSTREET']  = $address_arr['entry_street_address'];
          if ($address_arr['entry_suburb'] != '') $options['SHIPTOSTREET2'] = $address_arr['entry_suburb'];
          $options['SHIPTOCITY']    = $address_arr['entry_city'];
          $options['SHIPTOZIP']     = $address_arr['entry_postcode'];
          $options['SHIPTOSTATE']   = $address_arr['zone_code'];
          $options['SHIPTOCOUNTRYCODE'] = $address_arr['countries_iso_code_2'];
        }
      }
      // if these optional parameters are blank, remove them from transaction
      if (isset($options['SHIPTOSTREET2']) && trim($options['SHIPTOSTREET2']) == '') unset($options['SHIPTOSTREET2']);
      if (isset($options['SHIPTOPHONENUM']) && trim($options['SHIPTOPHONENUM']) == '') unset($options['SHIPTOPHONENUM']);

      // if State is not supplied, repeat the city so that it's not blank, otherwise PayPal croaks
      if ((!isset($options['SHIPTOSTATE']) || trim($options['SHIPTOSTATE']) == '') && $options['SHIPTOCITY'] != '') $options['SHIPTOSTATE'] = $options['SHIPTOCITY'];

      // FMF support
      $options['RETURNFMFDETAILS'] = (MODULE_PAYMENT_PAYPALWPP_EC_RETURN_FMF_DETAILS == 'Yes') ? 1 : 0;

      // Add note to track that this was an EC transaction (used in properly handling update IPNs related to EC transactions):
      $options['CUSTOM'] = 'EC-' . (int)$_SESSION['customer_id'] . '-' . time();

      // send the store name as transaction identifier, to help distinguish payments between multiple stores:
      $options['INVNUM'] = (int)$_SESSION['customer_id'] . '-' . time() . '-[' . substr(preg_replace('/[^a-zA-Z0-9_]/', '', STORE_NAME), 0, 30) . ']';  // (cannot send actual invoice number because it's not assigned until after payment is completed)

      $options['CURRENCY'] = $this->selectCurrency($order->info['currency']);
//      $order->info['total'] = zen_round($order->info['total'], 2);
      $order_amount = $this->calc_order_amount($order->info['total'], $options['CURRENCY'], FALSE);

      // debug output
      $this->zcLog('before_process - EC-4', 'info being submitted:' . "\n" . $_SESSION['paypal_ec_token'] . ' ' . $_SESSION['paypal_ec_payer_id'] . ' ' . number_format($order_amount, 2) .  "\n" . print_r($options, true));

      if (isset($options['DESC']) && $options['DESC'] == '') unset($options['DESC']);

      if (!isset($options['AMT'])) $options['AMT'] = number_format($order_amount, 2, '.', '');
      $response = $doPayPal->DoExpressCheckoutPayment($_SESSION['paypal_ec_token'],
                                                      $_SESSION['paypal_ec_payer_id'],
                                                      $options);

      $this->zcLog('before_process - EC-5', 'resultset:' . "\n" . urldecode(print_r($response, true)));

      // CHECK RESPONSE -- if error, actions are taken in the errorHandler
      $errorHandlerMessage = $this->_errorHandler($response, 'DoExpressCheckoutPayment');

      if ($this->fmfResponse != '') {
        $this->order_status = $this->order_pending_status;
      }

      // SUCCESS
      $this->payment_type = MODULE_PAYMENT_PAYPALWPP_EC_TEXT_TYPE;
      $this->responsedata = $response;
      if ($response['PAYMENTTYPE'] != '') $this->payment_type .=  ' (' . urldecode($response['PAYMENTTYPE']) . ')';

      $this->transaction_id = trim($response['PNREF'] . ' ' . $response['TRANSACTIONID']);
      if (empty($response['PENDINGREASON']) ||
          $response['PENDINGREASON'] == 'none' ||
          $response['PENDINGREASON'] == 'completed' ||
          $response['PAYMENTSTATUS'] == 'Completed') {
        $this->payment_status = 'Completed';
        if ($this->order_status > 0) $order->info['order_status'] = $this->order_status;
      } else {
        if ($response['PAYMENTSTATUS'] == 'Pending')
        {
          if ($response['L_ERRORCODE0'] == 11610 && $response['PENDINGREASON'] == '') $response['PENDINGREASON'] = 'Pending FMF Review by Storeowner';
        }
        $this->payment_status = 'Pending (' . $response['PENDINGREASON'] . ')';
        $order->info['order_status'] = $this->order_pending_status;
      }
      $this->avs = 'N/A';
      $this->cvv2 = 'N/A';
      $this->correlationid = $response['CORRELATIONID'];
      $this->transactiontype = $response['TRANSACTIONTYPE'];
      $this->payment_time = urldecode($response['ORDERTIME']);
      $this->feeamt = urldecode($response['FEEAMT']);
      $this->taxamt = urldecode($response['TAXAMT']);
      $this->pendingreason = $response['PENDINGREASON'];
      $this->reasoncode = $response['REASONCODE'];
      $this->numitems = sizeof($order->products);
      $this->amt = urldecode($response['AMT'] . ' ' . $response['CURRENCYCODE']);
      $this->auth_code = (isset($this->response['AUTHCODE'])) ? $this->response['AUTHCODE'] : $this->response['TOKEN'];
  }
962708
public function deliver()
    {
        $this->checkAuth();
        $this->checkCartNotEmpty();

        $message = false;

        $orderDelivery = $this->createForm(FrontForm::ORDER_DELIVER);

        try {
            $form = $this->validateForm($orderDelivery, "post");

            $deliveryAddressId = $form->get("delivery-address")->getData();
            $deliveryModuleId = $form->get("delivery-module")->getData();
            $deliveryAddress = AddressQuery::create()->findPk($deliveryAddressId);
            $deliveryModule = ModuleQuery::create()->findPk($deliveryModuleId);

            /* check that the delivery address belongs to the current customer */
            if ($deliveryAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
                throw new \Exception(
                    $this->getTranslator()->trans(
                        "Delivery address does not belong to the current customer",
                        [],
                        Front::MESSAGE_DOMAIN
                    )
                );
            }

            /* check that the delivery module fetches the delivery address area */
            if (null === AreaDeliveryModuleQuery::create()->findByCountryAndModule(
                $deliveryAddress->getCountry(),
                $deliveryModule
            )) {
                throw new \Exception(
                    $this->getTranslator()->trans(
                        "Delivery module cannot be use with selected delivery address",
                        [],
                        Front::MESSAGE_DOMAIN
                    )
                );
            }

            /* get postage amount */
            $moduleInstance = $deliveryModule->getDeliveryModuleInstance($this->container);

            $cart = $this->getSession()->getSessionCart($this->getDispatcher());
            $deliveryPostageEvent = new DeliveryPostageEvent($moduleInstance, $cart, $deliveryAddress);

            $this->getDispatcher()->dispatch(
                TheliaEvents::MODULE_DELIVERY_GET_POSTAGE,
                $deliveryPostageEvent
            );

            if (!$deliveryPostageEvent->isValidModule() || null === $deliveryPostageEvent->getPostage()) {
                throw new DeliveryException(
                    $this->getTranslator()->trans('The delivery module is not valid.', [], Front::MESSAGE_DOMAIN)
                );
            }

            $postage = $deliveryPostageEvent->getPostage();

            $orderEvent = $this->getOrderEvent();
            $orderEvent->setDeliveryAddress($deliveryAddressId);
            $orderEvent->setDeliveryModule($deliveryModuleId);
            $orderEvent->setPostage($postage->getAmount());
            $orderEvent->setPostageTax($postage->getAmountTax());
            $orderEvent->setPostageTaxRuleTitle($postage->getTaxRuleTitle());

            $this->getDispatcher()->dispatch(TheliaEvents::ORDER_SET_DELIVERY_ADDRESS, $orderEvent);
            $this->getDispatcher()->dispatch(TheliaEvents::ORDER_SET_DELIVERY_MODULE, $orderEvent);
            $this->getDispatcher()->dispatch(TheliaEvents::ORDER_SET_POSTAGE, $orderEvent);

            return $this->generateRedirectFromRoute("order.invoice");

        } catch (FormValidationException $e) {
            $message = $this->getTranslator()->trans(
                "Please check your input: %s",
                ['%s' => $e->getMessage()],
                Front::MESSAGE_DOMAIN
            );
        } catch (PropelException $e) {
            $this->getParserContext()->setGeneralError($e->getMessage());
        } catch (\Exception $e) {
            $message = $this->getTranslator()->trans(
                "Sorry, an error occured: %s",
                ['%s' => $e->getMessage()],
                Front::MESSAGE_DOMAIN
            );
        }

        if ($message !== false) {
            Tlog::getInstance()->error(
                sprintf("Error during order delivery process : %s. Exception was %s", $message, $e->getMessage())
            );

            $orderDelivery->setErrorMessage($message);

            $this->getParserContext()
                ->addForm($orderDelivery)
                ->setGeneralError($message)
            ;
        }
    }
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
  }
392741
private static function init() {
		self::setInit(true);

		// Initiates Products
		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_NATIONAL_PACKAGE);
		$obj->setName('DHL Paket');
		$obj->setMinLength(15);
		$obj->setMaxLength(200);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(200);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(200);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'preferredNeighbourEnabled',
			'preferredLocationEnabled',
			'visualCheckOfAgeEnabled',
			'personalHandover',
			'namedPersonOnly',
			'identCheckEnabled',
			'preferredDayEnabled',
			'preferredTimeEnabled',
			'disableNeighbourDelivery',
			'goGreen',
			'additionalInsuranceEnabled',
			'bulkyGoods',
			'cashOnDeliveryEnabled',
			'individualSenderRequiredmentsEnabled',
			'packagingReturn',
			'noticeNonDeliverability'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_NATIONAL_PACKAGE_PRIO);
		$obj->setName('DHL Paket PRIO');
		$obj->setMinLength(15);
		$obj->setMaxLength(200);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(200);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(200);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'preferredNeighbourEnabled',
			'preferredLocationEnabled',
			'visualCheckOfAgeEnabled',
			'namedPersonOnly',
			'identCheckEnabled',
			'preferredDayEnabled',
			'preferredTimeEnabled',
			'disableNeighbourDelivery',
			'goGreen',
			'additionalInsuranceEnabled',
			'cashOnDeliveryEnabled',
			'individualSenderRequiredmentsEnabled',
			'packagingReturn',
			'noticeNonDeliverability'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_SAME_DAY_PACKAGE);
		$obj->setName('DHL Paket Taggleich');
		$obj->setMinLength(15);
		$obj->setMaxLength(200);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(200);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(200);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'preferredNeighbourEnabled',
			'preferredLocationEnabled',
			'visualCheckOfAgeEnabled',
			'namedPersonOnly',
			'identCheckEnabled',
			'preferredDayEnabled',
			'preferredTimeEnabled',
			'disableNeighbourDelivery',
			'goGreen',
			'additionalInsuranceEnabled',
			'bulkyGoods',
			'cashOnDeliveryEnabled',
			'individualSenderRequiredmentsEnabled',
			'packagingReturn',
			'noticeNonDeliverability',
			'returnImmediatlyIfShipmentFailed'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_INTERNATIONAL_PACKAGE);
		$obj->setName('DHL Paket International');
		$obj->setMinLength(15);
		$obj->setMaxLength(120);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(60);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(60);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'endorsementEnabled',
			'returnReceipt',
			'goGreen',
			'additionalInsuranceEnabled',
			'bulkyGoods',
			'cashOnDeliveryEnabled',
			'premium'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_EUROPA_PACKAGE);
		$obj->setName('DHL Europapaket');
		$obj->setMinLength(15);
		$obj->setMaxLength(120);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(60);
		$obj->setMinHeight(3.5);
		$obj->setMaxHeight(60);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'goGreen',
			'additionalInsuranceEnabled'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_PACKED_CONNECT);
		$obj->setName('DHL Paket Connect');
		$obj->setMinLength(15);
		$obj->setMaxLength(120);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(60);
		$obj->setMinHeight(3.5);
		$obj->setMaxHeight(60);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'goGreen',
			'additionalInsuranceEnabled',
			'bulkyGoods'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_SAME_DAY_MESSENGER);
		$obj->setName('DHL Kurier Taggleich');
		$obj->setMinLength(15);
		$obj->setMaxLength(200);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(200);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(200);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'preferredNeighbourEnabled',
			'visualCheckOfAgeEnabled',
			'endorsementEnabled',
			'goGreen',
			'dayOfDeliveryEnabled',
			'deliveryTimeframeEnabled',
			'shipmentHandlingEnabled',
			'perishables',
			'individualSenderRequiredmentsEnabled'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_WISH_TIME_MESSENGER);
		$obj->setName('DHL Kurier Wunschzeit');
		$obj->setMinLength(15);
		$obj->setMaxLength(200);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(200);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(200);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'preferredNeighbourEnabled',
			'visualCheckOfAgeEnabled',
			'endorsementEnabled',
			'goGreen',
			'dayOfDeliveryEnabled',
			'deliveryTimeframeEnabled',
			'shipmentHandlingEnabled',
			'perishables',
			'individualSenderRequiredmentsEnabled'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_AUSTRIA_PACKAGE);
		$obj->setName('DHL Paket Austria');
		$obj->setAustria(true);
		$obj->setMinLength(15);
		$obj->setMaxLength(120);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(60);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(60);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'additionalInsuranceEnabled',
			'bulkyGoods',
			'cashOnDeliveryEnabled'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_CONNECT_PACKAGE);
		$obj->setName('DHL Paket Connect');
		$obj->setAustria(true);
		$obj->setMinLength(15);
		$obj->setMaxLength(120);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(60);
		$obj->setMinHeight(3.5);
		$obj->setMaxHeight(60);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'additionalInsuranceEnabled',
			'bulkyGoods',
			'cashOnDeliveryEnabled'
		));
		self::addProduct($obj);

		$obj = new Product(ShipmentDetails::PRODUCT_TYPE_AUSTRIA_INTERNATIONAL_PACKAGE);
		$obj->setName('DHL Paket International');
		$obj->setAustria(true);
		$obj->setMinLength(15);
		$obj->setMaxLength(120);
		$obj->setMinWidth(11);
		$obj->setMaxWidth(60);
		$obj->setMinHeight(1);
		$obj->setMaxHeight(60);
		$obj->setMaxWeight(31.5);
		$obj->setServices(array(
			'additionalInsuranceEnabled',
			'bulkyGoods',
			'cashOnDeliveryEnabled'
		));
		self::addProduct($obj);
	}
1345526
def _process_ups(ups):  # pragma: no cover
    """"""
    if len(ups) == 0:
        return
    elif len(ups) == 1:
        return ups[0]
    elif len(ups) == 2:
        up = ups[0]
        up.update(ups[1])
        return up
    else:
        raise NotImplementedError()