This method adds an address book entry to the database, this allows us to add addresses
that we get back from PayPal that are not in Zen Cart

@param int $customer_id
@param array $address_question_arr
@return int
435053
function addAddressBookEntry($customer_id, $address_question_arr, $make_default = false) {
    global $db;

    // debug
    $this->zcLog('addAddressBookEntry - 1', 'address to add: ' . "\n" . print_r($address_question_arr, true));

    // if address is blank, don't do any matching
    if ($address_question_arr['street_address'] == '') return false;

    // set some defaults
    $country_id = '223';
    $address_format_id = 2; //2 is the American format

    // first get the zone id's from the 2 digit iso codes
    // country first
    $sql = "SELECT countries_id, address_format_id
                FROM " . TABLE_COUNTRIES . "
                WHERE countries_iso_code_2 = :countryCode:
                OR countries_name = :countryName:
                OR countries_iso_code_2 = :countryName:
                OR countries_name = :countryCode:
                LIMIT 1";
    $sql = $db->bindVars($sql, ':countryCode:', $address_question_arr['country']['iso_code_2'], 'string');
    $sql = $db->bindVars($sql, ':countryName:', $address_question_arr['country']['title'], 'string');
    $country = $db->Execute($sql);

    // see if we found a record, if not default to American format
    if (!$country->EOF) {
      $country_id = $country->fields['countries_id'];
      $address_format_id = (int)$country->fields['address_format_id'];
    } else {
      // if defaulting to US, make sure US is valid
      $sql = "SELECT countries_id FROM " . TABLE_COUNTRIES . " WHERE countries_id = :countryId LIMIT 1";
      $sql = $db->bindVars($sql, ':countryId', $country_id, 'integer');
      $result = $db->Execute($sql);
      if ($result->EOF) {
        $this->notify('NOTIFY_HEADER_ADDRESS_BOOK_ADD_ENTRY_INVALID_ATTEMPT');
        $this->zcLog('addAddressBookEntry - 3', 'Failed to add address due to country restrictions');
        return FALSE;
      }
    }

    // see if the country code has a state
    $sql = "SELECT zone_id
                FROM " . TABLE_ZONES . "
                WHERE zone_country_id = :zoneId
                LIMIT 1";
    $sql = $db->bindVars($sql, ':zoneId', $country_id, 'integer');
    $country_zone_check = $db->Execute($sql);
    $check_zone = $country_zone_check->RecordCount();

    // now try and find the zone_id (state/province code)
    // use the country id above
    if ($check_zone) {
      $sql = "SELECT zone_id
                    FROM " . TABLE_ZONES . "
                    WHERE zone_country_id = :zoneId
                    AND (zone_code = :zoneCode
                    OR zone_name = :zoneCode )
                    LIMIT 1";
      $sql = $db->bindVars($sql, ':zoneId', $country_id, 'integer');
      $sql = $db->bindVars($sql, ':zoneCode', $address_question_arr['state'], 'string');
      $zone = $db->Execute($sql);
      if (!$zone->EOF) {
        // grab the id
        $zone_id = $zone->fields['zone_id'];
      } else {
        $zone_id = 0;
      }
    }

    // now run the insert

    // this isn't the best way to get fname/lname but it will get the majority of cases
    list($fname, $lname) = explode(' ', $address_question_arr['name']);

    $sql_data_array= array(array('fieldName'=>'entry_firstname', 'value'=>$fname, 'type'=>'string'),
                           array('fieldName'=>'entry_lastname', 'value'=>$lname, 'type'=>'string'),
                           array('fieldName'=>'entry_street_address', 'value'=>$address_question_arr['street_address'], 'type'=>'string'),
                           array('fieldName'=>'entry_postcode', 'value'=>$address_question_arr['postcode'], 'type'=>'string'),
                           array('fieldName'=>'entry_city', 'value'=>$address_question_arr['city'], 'type'=>'string'),
                           array('fieldName'=>'entry_country_id', 'value'=>$country_id, 'type'=>'integer'));
    if ($address_question_arr['company'] != '' && $address_question_arr['company'] != $address_question_arr['name']) array('fieldName'=>'entry_company', 'value'=>$address_question_arr['company'], 'type'=>'string');
    $sql_data_array[] = array('fieldName'=>'entry_gender', 'value'=>$address_question_arr['payer_gender'], 'type'=>'enum:m|f');
    $sql_data_array[] = array('fieldName'=>'entry_suburb', 'value'=>$address_question_arr['suburb'], 'type'=>'string');
    if ($zone_id > 0) {
      $sql_data_array[] = array('fieldName'=>'entry_zone_id', 'value'=>$zone_id, 'type'=>'integer');
      $sql_data_array[] = array('fieldName'=>'entry_state', 'value'=>'', 'type'=>'string');
    } else {
      $sql_data_array[] = array('fieldName'=>'entry_zone_id', 'value'=>'0', 'type'=>'integer');
      $sql_data_array[] = array('fieldName'=>'entry_state', 'value'=>$address_question_arr['state'], 'type'=>'string');
    }
    $sql_data_array[] = array('fieldName'=>'customers_id', 'value'=>$customer_id, 'type'=>'integer');
    $db->perform(TABLE_ADDRESS_BOOK, $sql_data_array);

    $new_address_book_id = $db->Insert_ID();

    $this->notify('NOTIFY_HEADER_ADDRESS_BOOK_ADD_ENTRY_DONE');

    // make default if set, update
    if ($make_default) {
      $sql_data_array = array();
      $sql_data_array[] = array('fieldName'=>'customers_default_address_id', 'value'=>$new_address_book_id, 'type'=>'integer');
      $where_clause = "customers_id = :customersID";
      $where_clause = $db->bindVars($where_clause, ':customersID', $customer_id, 'integer');
      $db->perform(TABLE_CUSTOMERS, $sql_data_array, 'update', $where_clause);
      $_SESSION['customer_default_address_id'] = $new_address_book_id;
    }

    // set the sendto
    $_SESSION['sendto'] = $new_address_book_id;

    // debug
    $this->zcLog('addAddressBookEntry - 2', 'added address #' . $new_address_book_id. "\n" . 'SESSION[sendto] is now set to ' . $_SESSION['sendto']);

    // return the address_id
    return $new_address_book_id;
  }
640835
public function updateCustomer(int $customerId, $customer) : array
    {
        Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive');

        return (array)$this->master->doRequest(
            'PUT',
            sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/%d', $customerId),
            $customer
        );
    }
154506
public function queryShopWifi($shop_id = null, $pageindex = null, $pagesize = null)
    {
        $data = [];
        is_null($pagesize) || $data['pagesize'] = $pagesize;
        is_null($pageindex) || $data['pageindex'] = $pageindex;
        is_null($shop_id) || $data['shop_id'] = $shop_id;
        $url = 'https://api.weixin.qq.com/bizwifi/device/list?access_token=ACCESS_TOKEN';
        $this->registerApi($url, __FUNCTION__, func_get_args());
        return $this->httpPostForJson($url, $data);
    }
194339
public function addaddress()
    {
        $form = $this->AddressForm();
        $form
            ->Fields()
            ->dataFieldByName("OwnerID")
            ->setValue(Member::currentuserID());

        return $this
            ->owner
            ->customise(array(
                "ClassName" => "AccountPage",
                "Title"     => _t("Checkout.AddAddress", "Add Address"),
                "Form"  => $form
            ))->renderWith(array(
                "UserAccount_addaddress",
                "Users",
                "Page"
            ));
    }
259688
protected function addChange($addressBookId, $objectUri, $operation)
    {
        $stmt = $this->pdo->prepare('INSERT INTO '.$this->addressBookChangesTableName.' (uri, synctoken, addressbookid, operation) SELECT ?, synctoken, ?, ? FROM '.$this->addressBooksTableName.' WHERE id = ?');
        $stmt->execute([
            $objectUri,
            $addressBookId,
            $operation,
            $addressBookId,
        ]);
        $stmt = $this->pdo->prepare('UPDATE '.$this->addressBooksTableName.' SET synctoken = synctoken + 1 WHERE id = ?');
        $stmt->execute([
            $addressBookId,
        ]);
    }
807515
private function isAddressBillingAddress(array $addressData, TdbDataExtranetUser $user)
    {
        if (false === isset($addressData['id'])) {
            return false;
        }
        if ($addressData['id'] !== $user->fieldDefaultBillingAddressId) {
            return false;
        }

        return true;
    }
77223
public function initInstantOrder($customerId)
    {
        if (! $customerId) {
            throw new RecordNotFoundException('customerId not passed');
        }
        
        $this->Customer = TableRegistry::getTableLocator()->get('Customers');
        $instantOrderCustomer = $this->Customer->find('all', [
            'conditions' => [
                'Customers.id_customer' => $customerId
            ],
            'contain' => [
                'AddressCustomers'
            ]
        ])->first();
        if (! empty($instantOrderCustomer)) {
            $this->getRequest()->getSession()->write('Auth.instantOrderCustomer', $instantOrderCustomer);
        } else {
            $this->Flash->error(__d('admin', 'No_member_found_with_id_{0}.', [$customerId]));
        }
        $this->redirect('/');
    }
318973
public function payment($tmp_order, $customer_id, $partialPaymentMethod = null)
    {
        $transaction_id = tep_create_random_value(16);

        $finalAddr = [
            'recipientName'   => $tmp_order->delivery['firstname'] . ' '. $tmp_order->delivery['lastname'],
            'co'              => $tmp_order->delivery['company'],
            'streetAddress'   => $tmp_order->delivery['street_address'],
            'streetAddress2'  => $tmp_order->delivery['suburb'],
            'city'            => $tmp_order->delivery['city'],
            'stateOrProvince' => $tmp_order->delivery['state'],
            'postalCode'        => $tmp_order->delivery['postcode'],
            'countryCode'     => $tmp_order->delivery['country']['iso_code_2']
        ];

        $items = $tmp_order->products;
        $products = [];
        if ($items) {
            $hasExtradata = false;
            $totalTaxes = 0;
            foreach ($items as $item) {
                // $imageUrl = tep_output_string(HTTPS_SERVER . DIR_WS_IMAGES . $item['products_image']);

                $excVat  = floatval($item['final_price']);
                $percent = floatval($item['tax']);
                $taxes   = $excVat * $percent / 100.0;
                $incVat  = $excVat + $taxes;
                $qty     = intval($item['qty']);
                $totalTaxes += $qty * $taxes;

                // Set attributes
                $attributes = '';
                if (isset($item['attributes'])) {
                    foreach ($item['attributes'] as $attribute) {
                        $attributes .= ' ' . $attribute['option'] . ': ' . $attribute['value'];
                    }
                }
                error_log('attributes: '.$attributes, 0);
                
                $products[] = [
                    "id"                 => (string)$item['id'],
                    "quantity"           => $qty,
                    "title"              => $item['name'] . $attributes,
                    "model"              => $item['model'],
                    "priceInCentsIncVat" => round($incVat * 100),
                    "priceInCentsExcVat" => round($excVat * 100),
                    "vatInCents"         => round($taxes * 100),
                    "vatPercentage"      => $percent,
                    // "imageUrl"           => "",
                ];
                $hasExtradata = true;
            }

            // Merge extra data with the order object (serialized)
            $products[0] = array_merge(
                $products[0],
                array('extraData' => serialize($tmp_order))
            );

            // error_log(' products at index 0: '.json_encode($products[0]), 0);
        }

        $shipExcVat  = $tmp_order->info['shipping_cost'];
        $shipTaxes   = floatval($tmp_order->info['tax']) - $totalTaxes;
        $shipIncVat  = $shipExcVat + $shipTaxes;
        $shipPercent = 0;
        if ($shipExcVat > 0) {
            $shipPercent = $shipTaxes * 100.0 / $shipExcVat;
        }

        $products[] = [
            "id"                 => $tmp_order->info['shipping_method'],
            "quantity"           => 1,
            "title"              => 'Handling and Delivery',
            "priceInCentsIncVat" => round($shipIncVat * 100),
            "priceInCentsExcVat" => round($shipExcVat * 100),
            "vatInCents"         => round($shipTaxes * 100),
            "vatPercentage"      => $shipPercent,
            "extraData"          => "",
            // "imageUrl"           => "",
        ];

        $baseExclTax  = $tmp_order->info['subtotal'];
        $taxAmount    = $tmp_order->info['tax'] - $shipTaxes;
        $totalOrdered = $tmp_order->info['total'];

        $order = ["sumInCentsIncVat" => round($totalOrdered * 100),
            "sumInCentsExcVat"       => round(($baseExclTax + $shipExcVat) * 100),
            "vatInCents"             => round(($taxAmount + $shipTaxes) * 100),
            "currency"               => $tmp_order->info['currency'],
            "referenceId"            => $transaction_id,
            "tosUrl"                 => "https://payapi.io/terms"
        ];
                
        $consumer = [
            "email" => $tmp_order->customer['email_address'],
            "consumerId" => (string)$customer_id
        ];
        //Return URLs

        $returnUrls = [
            "success" => $this->getStoreUrl() . "ext/modules/payment/payapi/checkout_success.php",
            "cancel"  => $this->getStoreUrl()  ,
            "failed"  => $this->getStoreUrl()
        ];

        $callbackUrl = $this->getStoreUrl() . "ext/modules/payment/payapi/payapi_callbacks.php";
        // $callbackUrl   = $this->getStoreUrl() . "checkout_process.php";
        $jsonCallbacks = [
            "processing" => $callbackUrl,
            "success"    => $callbackUrl,
            "failed"     => $callbackUrl,
            "chargeback" => $callbackUrl,
        ];

        $res = ["order"       => $order,
            "products"        => $products,
            "consumer"        => $consumer,
            "shippingAddress" => $finalAddr,
            "returnUrls"      => $returnUrls,
            "callbacks"       => $jsonCallbacks
            ];

        // error_log(' res in payment: '.json_encode($res), 0);

        return $res;
    }
330136
function get3DSecureLookupResponse($lookup_data_array) {
    // Set some defaults
    if (!isset($lookup_data_array['order_desc']) || $lookup_data_array['order_desc'] == '') $lookup_data_array['order_desc'] = 'Zen Cart(R) Transaction';
    if (!isset($lookup_data_array['order_number']) || $lookup_data_array['order_number'] == '') $lookup_data_array['order_number'] = zen_session_id();
    // format the card expiration
    $lookup_data_array['cc3d_exp_year'] = (strlen($lookup_data_array['cc3d_exp_year']) == 2 ? '20' : '') . $lookup_data_array['cc3d_exp_year'];
    // get the ISO 4217 currency
    $iso_currency = $this->getISOCurrency($lookup_data_array['currency']);
    // format the transaction amounts
    $raw_amount = $this->formatRawAmount($lookup_data_array['txn_amount'], $iso_currency);
    // determine the appropriate product code for submission
    $prodCode = FALSE;
    if (isset($_SESSION['cart'])) {
      if ($_SESSION['cart']->get_cart_type == 'virtual') {
        $prodCode = 'DIG';
      } else {
        $prodCode = 'PHY';
      }
    }

    // DEBUG ONLY: $this->zcLog(__FILE__ . '->' . __LINE__, 'session details: ' . print_r(array_merge($_POST, $_SESSION), true));

    // Build the XML cmpi_lookup message
    $data = '<CardinalMPI>';
    $data .= '<MsgType>cmpi_lookup</MsgType>';
    $data .= '<Version>1.7</Version>';
    $data .= '<ProcessorId>' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR) . '</ProcessorId>';
    $data .= '<MerchantId><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]></MerchantId>';
    $data .= '<TransactionPwd><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]></TransactionPwd>';
    $data .= '<TransactionType>CC</TransactionType>';
    $data .= '<TransactionMode>S</TransactionMode>';
    $data .= '<OrderNumber>' . $this->escapeXML($lookup_data_array['order_number']) . '</OrderNumber>';
    $data .= '<OrderDescription>' . $this->escapeXML($lookup_data_array['order_desc']) . '</OrderDescription>';
    $data .= '<Amount>' . $this->escapeXML($raw_amount) . '</Amount>';
    $data .= '<CurrencyCode>' . $this->escapeXML($iso_currency) . '</CurrencyCode>';
    $data .= '<CardNumber>' . $this->escapeXML($lookup_data_array['cc3d_card_number']) . '</CardNumber>';
    $data .= '<Cvv>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</Cvv>';
    $data .= '<CardCode>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</CardCode>';
    $data .= '<CardExpMonth>' . $this->escapeXML($lookup_data_array['cc3d_exp_month']) . '</CardExpMonth>';
    $data .= '<CardExpYear>' . $this->escapeXML($lookup_data_array['cc3d_exp_year']) . '</CardExpYear>';
    $data .= '<UserAgent>' . $this->escapeXML($_SERVER["HTTP_USER_AGENT"]) . '</UserAgent>';
    $ipAddress = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $data .= '<IPAddress>' . $this->escapeXML($ipAddress) . '</IPAddress>';
    $data .= '<BrowserHeader>' . $this->escapeXML($_SERVER["HTTP_ACCEPT"]) . '</BrowserHeader>';
    $data .= '<OrderChannel>' . $this->escapeXML('MARK') . '</OrderChannel>';
    if (isset($lookup_data_array['merchantData'])) $data .= '<MerchantData>' . $this->escapeXML($lookup_data_array['merchantData']) . '</MerchantData>';
    if ($prodCode !== FALSE && $prodCode != '') $data .= '<ProductCode>' . $this->escapeXML($prodCode) . '</ProductCode>';
    $data .= '</CardinalMPI>';
    $debugData = str_replace(array('[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]', '[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]', $this->escapeXML($lookup_data_array['cc3d_card_number']), $this->escapeXML($lookup_data_array['cc3d_checkcode'])), '********', $data);

    if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
      $this->zcLog('Cardinal Lookup 1', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup request (' . MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL . ') - ' . $debugData);
    }

    $responseString = $this->send3DSecureHttp(MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL, $data, $debugData);

    if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
      $this->zcLog('Cardinal Lookup 2', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup response - ' . $responseString);
    }

    // parse the XML
    $parser = new CardinalXMLParser;
    $parser->deserializeXml($responseString);

    $errorNo = $parser->deserializedResponse['ErrorNo'];
    $errorDesc = $parser->deserializedResponse['ErrorDesc'];
    $enrolled = $parser->deserializedResponse['Enrolled'];

    if ($errorNo != 0) {
      $this->zcLog('Cardinal Lookup 3', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc);
      $errorText = 'Cardinal Lookup 3' . '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc;
      $errorText .= "\n\n" . 'There are 3 steps to configuring your Cardinal 3D-Secure service properly: ' . "\n1-Login to the Cardinal Merchant Admin URL supplied in your welcome package (NOT the test URL), and accept the license agreement.\n2-Set a transaction password.\n3-Copy your Cardinal Merchant ID and Cardinal Transaction Password into your ZC PayPal module.\n\nFor specific help, please contact implement@cardinalcommerce.com to sort out your account configuration issues.";
      $errorText .= "\n\nProblem observed while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication. THEIR PURCHASE WAS NOT SUCCESSFUL. Please resolve this matter to enable future checkouts.';
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, substr($errorDesc, 0, 75) . ' (' . $errorNo . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
    }

    // default the continue flag to 'N'
    $continue_flag = 'N';

    // determine whether the transaction should continue or fail based upon
    // the enrollment lookup results
    if (strcasecmp(MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ, 'No') == 0) {
      $continue_flag = 'Y';
    } else if (strcmp($errorNo, '0') == 0) {
      if (strcasecmp($enrolled, 'Y') == 0) {
        $continue_flag = 'Y';
      } else if (strcasecmp($enrolled, 'N') == 0) {
        $cardType = $this->determineCardType($this->cc_card_number);
        if (strcasecmp($cardType, 'VISA') == 0 || strcasecmp($cardType, 'JCB') == 0) {
          $continue_flag = 'Y';
        }
      }
    } else if ($errorNo == 1001) { // merchant has an account configuration problem to fix
      $errorText = CENTINEL_ERROR_CODE_1001 . ' - ' . CENTINEL_ERROR_CODE_1001_DESC;
      $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_1001_DESC . ' (' . CENTINEL_ERROR_CODE_1001 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
      $continue_flag = 'Y';
    }

    if (strcasecmp('Y', $continue_flag) == 0) {
      // For validation/security purposes, mark the session that the lookup result was acceptable.
      $_SESSION['3Dsecure_enroll_lookup_attempted'] = 'Y';
    } else {
      // For validation/security purposes, mark the session that the lookup result was not acceptable.
      unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
    }

    $result = array('continue_flag' => $continue_flag,
                    'enrolled' => $enrolled,
                    'transaction_id' => $parser->deserializedResponse['TransactionId'],
                    'error_no' => $errorNo,
                    'error_desc' => $errorDesc,
                    'acs_url' => $parser->deserializedResponse['ACSUrl'],
                    'spa_hidden_fields' => $parser->deserializedResponse['SPAHiddenFields'],
                    'payload' => $parser->deserializedResponse['Payload'],
                    'cc3d_card_number' => $parser->deserializedResponse['CardNumber'],
                    'cc3d_checkcode' => $parser->deserializedResponse['CardCode'],
                    'cc3d_exp_month' => $parser->deserializedResponse['CardExpMonth'],
                    'cc3d_exp_year' => $parser->deserializedResponse['CardExpYear'],
                    'EciFlag' => $parser->deserializedResponse['EciFlag'],
                    'cc3d_merchantdata' => $parser->deserializedResponse['MerchantData']);
    return $result;
  }
154934
def add_userid_for_address(self, address: Address, user_id: str):
        
        self._address_to_userids[address].add(user_id)
1006204
public function integratedAddress($payment_id = null)
    {
        $params = ['payment_id' => $payment_id];
        $body = [
            'method' => 'make_integrated_address',
            'params' => $params
        ];
        return $this->_request($body);
    }
715982
public function exists($customerId, array $addressToCheck)
    {
        unset($addressToCheck['email']);
        if (empty($addressToCheck['company'])) {
            // company would be cast to an empty string, which does not match NULL in the database
            unset($addressToCheck['company']);
        }
        $addressCollection = $this->addressFactory->create()
                                                  ->getCollection()
                                                  ->addFieldToFilter('parent_id', $customerId);

        foreach ($addressToCheck as $addressField => $fieldValue) {
            $addressCollection->addFieldToFilter(
                $addressField,
                $fieldValue
            );
        }

        return $addressCollection->count() > 0;
    }
250882
private function setAddress($quoteAddress, $address)
    {
        $address = $this->cartHelper->handleSpecialAddressCases($address);

        $region = $this->regionModel->loadByName(@$address->region, @$address->country_code);

        $addressData = [
            'firstname'    => @$address->first_name,
            'lastname'     => @$address->last_name,
            'street'       => trim(@$address->street_address1 . "\n" . @$address->street_address2),
            'city'         => @$address->locality,
            'country_id'   => @$address->country_code,
            'region'       => @$address->region,
            'postcode'     => @$address->postal_code,
            'telephone'    => @$address->phone_number,
            'region_id'    => $region ? $region->getId() : null,
            'company'      => @$address->company,
        ];

        if ($this->cartHelper->validateEmail(@$address->email_address)) {
            $addressData['email'] = $address->email_address;
        }

        // discard empty address fields
        foreach ($addressData as $key => $value) {
            if (empty($value)) {
                unset($addressData[$key]);
            }
        }

        $quoteAddress->setShouldIgnoreValidation(true);
        $quoteAddress->addData($addressData)->save();
    }
1197138
public function delete($customerOrId = null, $addressId = null)
    {
        $this->_validateId($addressId);
        $customerId = $this->_determineCustomerId($customerOrId);
        $path = $this->_config->merchantPath() . '/customers/' . $customerId . '/addresses/' . $addressId;
        $this->_http->delete($path);
        return new Result\Successful();
    }
478273
function user_login($email_address, $redirect = true) {
    global $db, $order, $messageStack;
    global $session_started;
    if ($session_started == false) {
      zen_redirect(zen_href_link(FILENAME_COOKIE_USAGE));
    }
    $sql = "SELECT * FROM " . TABLE_CUSTOMERS . "
            WHERE customers_email_address = :custEmail ";
    $sql = $db->bindVars($sql, ':custEmail', $email_address, 'string');
    $check_customer = $db->Execute($sql);

    if ($check_customer->EOF) {
      $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_BAD_LOGIN, true);
    }
    if (SESSION_RECREATE == 'True') {
      zen_session_recreate();
    }
    $sql = "SELECT entry_country_id, entry_zone_id
            FROM " . TABLE_ADDRESS_BOOK . "
            WHERE customers_id = :custID
            AND address_book_id = :addrID ";
    $sql = $db->bindVars($sql, ':custID', $check_customer->fields['customers_id'], 'integer');
    $sql = $db->bindVars($sql, ':addrID', $check_customer->fields['customers_default_address_id'], 'integer');
    $check_country = $db->Execute($sql);
    $_SESSION['customer_id'] = (int)$check_customer->fields['customers_id'];
    $_SESSION['customer_default_address_id'] = $check_customer->fields['customers_default_address_id'];
    $_SESSION['customer_first_name'] = $check_customer->fields['customers_firstname'];
    $_SESSION['customer_country_id'] = $check_country->fields['entry_country_id'];
    $_SESSION['customer_zone_id'] = $check_country->fields['entry_zone_id'];
    $order->customer['id'] = $_SESSION['customer_id'];
    $sql = "UPDATE " . TABLE_CUSTOMERS_INFO . "
            SET customers_info_date_of_last_logon = now(),
                customers_info_number_of_logons = customers_info_number_of_logons+1
            WHERE customers_info_id = :custID ";
    $sql = $db->bindVars($sql, ':custID', $_SESSION['customer_id'], 'integer');
    $db->Execute($sql);

    // bof: contents merge notice
    // save current cart contents count if required
        if (SHOW_SHOPPING_CART_COMBINED > 0) {
          $zc_check_basket_before = $_SESSION['cart']->count_contents();
        }

        // bof: not require part of contents merge notice
        // restore cart contents
        $_SESSION['cart']->restore_contents();
        // eof: not require part of contents merge notice

        // check current cart contents count if required
        if (SHOW_SHOPPING_CART_COMBINED > 0 && $zc_check_basket_before > 0) {
          $zc_check_basket_after = $_SESSION['cart']->count_contents();
          if (($zc_check_basket_before != $zc_check_basket_after) && $_SESSION['cart']->count_contents() > 0 && SHOW_SHOPPING_CART_COMBINED > 0) {
            if (SHOW_SHOPPING_CART_COMBINED == 2) {
              // warning only do not send to cart
              $messageStack->add_session('header', WARNING_SHOPPING_CART_COMBINED, 'caution');
            }
            if (SHOW_SHOPPING_CART_COMBINED == 1) {
              // show warning and send to shopping cart for review
              $messageStack->add_session('shopping_cart', WARNING_SHOPPING_CART_COMBINED, 'caution');
              zen_redirect(zen_href_link(FILENAME_SHOPPING_CART, '', 'NONSSL'));
            }
          }
        }
    // eof: contents merge notice
    if ($redirect) {
      $this->terminateEC();
    }
    return true;
  }
166182
public function addCredits($customerId, $amount)
    {
        $requestData = new AddCredits\RequestData($customerId, $amount);
        $request = new AddCredits\Request($requestData);

        return $this->sendRequest($request, AddCredits\ApiResponse::class);
    }
1303590
public function updateCustomer($customer_id)
    {
        $data = [
            "email" => request()->email,
            "first_name" => request()->fname,
            "last_name" => request()->lname,
            "phone" => request()->phone,
            "metadata" => request()->additional_info /* key => value pairs array */

        ];

        $this->setRequestOptions();
        return $this->setHttpResponse('/customer/'. $customer_id, 'PUT', $data)->getResponse();
    }