Ejemplo n.º 1
0
 public function postProcess()
 {
     if (Tools::isSubmit($this->table . 'Orderby') || Tools::isSubmit($this->table . 'Orderway')) {
         $this->filter = true;
     }
     if (!isset($this->table)) {
         return false;
     }
     if (!Tools::getValue('id_' . $this->table)) {
         if (Validate::isStateIsoCode(Tools::getValue('iso_code')) && State::getIdByIso(Tools::getValue('iso_code'), Tools::getValue('id_country'))) {
             $this->errors[] = Tools::displayError('This ISO code already exists. You cannot create two states with the same ISO code.');
         }
     } else {
         if (Validate::isStateIsoCode(Tools::getValue('iso_code'))) {
             $id_state = State::getIdByIso(Tools::getValue('iso_code'), Tools::getValue('id_country'));
             if ($id_state && $id_state != Tools::getValue('id_' . $this->table)) {
                 $this->errors[] = Tools::displayError('This ISO code already exists. You cannot create two states with the same ISO code.');
             }
         }
     }
     /* Delete object */
     if (isset($_GET['delete' . $this->table])) {
         // set token
         $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
         if ($this->tabAccess['delete'] === '1') {
             if (Validate::isLoadedObject($object = $this->loadObject()) && isset($this->fieldImageSettings)) {
                 if (!$object->isUsed()) {
                     // check if request at least one object with noZeroObject
                     if (isset($object->noZeroObject) && count($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) {
                         $this->errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                     } else {
                         if ($this->deleted) {
                             $object->deleted = 1;
                             if ($object->update()) {
                                 Tools::redirectAdmin(self::$currentIndex . '&conf=1&token=' . $token);
                             }
                         } else {
                             if ($object->delete()) {
                                 Tools::redirectAdmin(self::$currentIndex . '&conf=1&token=' . $token);
                             }
                         }
                         $this->errors[] = Tools::displayError('An error occurred during deletion.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('This state was used in at least one address. It cannot be removed.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while deleting the object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } else {
         parent::postProcess();
     }
 }
 public function postProcess()
 {
     if (Tools::isSubmit($this->table . 'Orderby') || Tools::isSubmit($this->table . 'Orderway')) {
         $this->filter = true;
     }
     // Idiot-proof controls
     if (!Tools::getValue('id_' . $this->table)) {
         if (Validate::isStateIsoCode(Tools::getValue('iso_code')) && State::getIdByIso(Tools::getValue('iso_code'), Tools::getValue('id_country'))) {
             $this->errors[] = Tools::displayError('This ISO code already exists. You cannot create two states with the same ISO code.');
         }
     } elseif (Validate::isStateIsoCode(Tools::getValue('iso_code'))) {
         $id_state = State::getIdByIso(Tools::getValue('iso_code'), Tools::getValue('id_country'));
         if ($id_state && $id_state != Tools::getValue('id_' . $this->table)) {
             $this->errors[] = Tools::displayError('This ISO code already exists. You cannot create two states with the same ISO code.');
         }
     }
     /* Delete state */
     if (Tools::isSubmit('delete' . $this->table)) {
         if ($this->tabAccess['delete'] === '1') {
             if (Validate::isLoadedObject($object = $this->loadObject())) {
                 /** @var State $object */
                 if (!$object->isUsed()) {
                     if ($object->delete()) {
                         Tools::redirectAdmin(self::$currentIndex . '&conf=1&token=' . (Tools::getValue('token') ? Tools::getValue('token') : $this->token));
                     }
                     $this->errors[] = Tools::displayError('An error occurred during deletion.');
                 } else {
                     $this->errors[] = Tools::displayError('This state was used in at least one address. It cannot be removed.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while deleting the object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     }
     if (!count($this->errors)) {
         parent::postProcess();
     }
 }
 /**
  * When the customer is back from PayPal after filling his/her credit card info or credentials, this function is preparing the order
  * PayPal is providing us with the customer info (E-mail address, billing address) and we are trying to find a matching customer in the Shop database.
  * If no customer is found, we create a new one and we simulate a logged customer session.
  * Eventually it will redirect the customer to the "Shipping" step/page of the order process
  */
 private function _expressCheckout()
 {
     /* We need to double-check that the token provided by PayPal is the one expected */
     $result = $this->paypal_usa->postToPayPal('GetExpressCheckoutDetails', '&TOKEN=' . urlencode(Tools::getValue('token')));
     if ((strtoupper($result['ACK']) == 'SUCCESS' || strtoupper($result['ACK']) == 'SUCCESSWITHWARNING') && $result['TOKEN'] == Tools::getValue('token') && $result['PAYERID'] == Tools::getValue('PayerID')) {
         /* Checks if a customer already exists for this e-mail address */
         if (Validate::isEmail($result['EMAIL'])) {
             $customer = new Customer();
             $customer->getByEmail($result['EMAIL']);
         }
         /* If the customer does not exist yet, create a new one */
         if (!Validate::isLoadedObject($customer)) {
             $customer = new Customer();
             $customer->email = $result['EMAIL'];
             $customer->firstname = $result['FIRSTNAME'];
             $customer->lastname = $result['LASTNAME'];
             $customer->passwd = Tools::encrypt(Tools::passwdGen());
             $customer->add();
         }
         /* Look for an existing PayPal address for this customer */
         $addresses = $customer->getAddresses((int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($addresses as $address) {
             if ($address['alias'] == 'PayPal') {
                 $id_address = (int) $address['id_address'];
                 break;
             }
         }
         /* Create or update a PayPal address for this customer */
         $address = new Address(isset($id_address) ? (int) $id_address : 0);
         $address->id_customer = (int) $customer->id;
         $address->id_country = (int) Country::getByIso($result['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE']);
         $address->id_state = (int) State::getIdByIso($result['PAYMENTREQUEST_0_SHIPTOSTATE'], (int) $address->id_country);
         $address->alias = 'PayPal';
         $address->lastname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], 0, strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '));
         $address->firstname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '), strlen($result['PAYMENTREQUEST_0_SHIPTONAME']) - strlen($address->lastname));
         $address->address1 = $result['PAYMENTREQUEST_0_SHIPTOSTREET'];
         if ($result['PAYMENTREQUEST_0_SHIPTOSTREET2'] != '') {
             $address->address2 = $result['PAYMENTREQUEST_0_SHIPTOSTREET2'];
         }
         $address->city = $result['PAYMENTREQUEST_0_SHIPTOCITY'];
         $address->postcode = $result['PAYMENTREQUEST_0_SHIPTOZIP'];
         $address->save();
         /* Update the cart billing and delivery addresses */
         $this->context->cart->id_address_delivery = (int) $address->id;
         $this->context->cart->id_address_invoice = (int) $address->id;
         $this->context->cart->update();
         /* Update the customer cookie to simulate a logged-in session */
         $this->context->cookie->id_customer = (int) $customer->id;
         $this->context->cookie->customer_lastname = $customer->lastname;
         $this->context->cookie->customer_firstname = $customer->firstname;
         $this->context->cookie->passwd = $customer->passwd;
         $this->context->cookie->email = $customer->email;
         $this->context->cookie->is_guest = $customer->isGuest();
         $this->context->cookie->logged = 1;
         /* Save the Payer ID and Checkout token for later use (during the payment step/page) */
         $this->context->cookie->paypal_express_checkout_token = $result['TOKEN'];
         $this->context->cookie->paypal_express_checkout_payer_id = $result['PAYERID'];
         if (_PS_VERSION_ < '1.5') {
             Module::hookExec('authentication');
         } else {
             Hook::exec('authentication');
         }
         /* Redirect the use to the "Shipping" step/page of the order process */
         Tools::redirectLink($this->context->link->getPageLink('order.php', false, null, array('step' => '3')));
         exit;
     } else {
         foreach ($result as $key => $val) {
             $result[$key] = urldecode($val);
         }
         $this->context->smarty->assign('paypal_usa_errors', $result);
         $this->setTemplate('express-checkout-messages.tpl');
     }
 }
Ejemplo n.º 4
0
 /**
  * Create or Updates Prestashop address
  * @return Address Address object
  */
 protected function createAddress($addressInformations, $address = null)
 {
     $country = $this->getCountryByCode($addressInformations->country->alpha2Code);
     if (!$country->active) {
         $this->addError(sprintf($this->module->l('This country is not active : %s'), $addressInformations->country->alpha2Code), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY);
         return false;
     }
     if (!isset($addressInformations->friendlyName)) {
         $friendlyName = $this->module->l('My address');
     } else {
         $friendlyName = $addressInformations->friendlyName;
     }
     if (PowaTagAPI::apiLog()) {
         PowaTagLogs::initAPILog('Create address', PowaTagLogs::IN_PROGRESS, $addressInformations->lastName . ' ' . $addressInformations->firstName . ' : ' . $friendlyName);
     }
     $address = $address != null ? $address : Address::initialize();
     $address->id_customer = (int) $this->customer->id;
     $address->id_country = (int) $country->id;
     $address->alias = $friendlyName;
     $address->lastname = $addressInformations->lastName;
     $address->firstname = $addressInformations->firstName;
     $address->address1 = $addressInformations->line1;
     $address->address2 = $addressInformations->line2;
     $address->postcode = $addressInformations->postCode;
     $address->city = $addressInformations->city;
     $address->phone = isset($addressInformations->phone) ? $addressInformations->phone : '0000000000';
     $address->id_state = isset($addressInformations->state) ? (int) State::getIdByIso($addressInformations->state, (int) $country->id) : 0;
     if (!$address->save()) {
         $this->addError($this->module->l('Impossible to save address'), PowaTagErrorType::$INTERNAL_ERROR);
         if (PowaTagAPI::apiLog()) {
             PowaTagLogs::initAPILog('Create address', PowaTagLogs::ERROR, $this->error['message']);
         }
         return false;
     }
     if (PowaTagAPI::apiLog()) {
         PowaTagLogs::initAPILog('Create address', PowaTagLogs::SUCCESS, 'Address ID : ' . $address->id);
     }
     return $address;
 }
Ejemplo n.º 5
0
/**
 * Set customer address (when not logged in)
 * Used to create user address with PayPal account information
 */
function setCustomerAddress($ppec, $customer, $id = null)
{
    $address = new Address($id);
    $address->id_country = Country::getByIso($ppec->result['COUNTRYCODE']);
    $address->alias = 'Paypal_Address';
    $address->lastname = $customer->lastname;
    $address->firstname = $customer->firstname;
    $address->address1 = $ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET'];
    if (isset($ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET2'])) {
        $address->address2 = $ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET2'];
    }
    $address->city = $ppec->result['PAYMENTREQUEST_0_SHIPTOCITY'];
    $address->id_state = (int) State::getIdByIso($ppec->result['SHIPTOSTATE'], $address->id_country);
    $address->postcode = $ppec->result['SHIPTOZIP'];
    $address->id_customer = $customer->id;
    return $address;
}
Ejemplo n.º 6
0
 private static function createStates()
 {
     $ps_state_iso_code_max_length = 7;
     if (version_compare(_PS_VERSION_, '1.5', '<')) {
         $ps_state_iso_code_max_length = 4;
     }
     foreach (SeurLib::$baleares_states as $iso_code => $state_name) {
         if (Tools::strlen($iso_code) > $ps_state_iso_code_max_length) {
             $tmpArray = explode('-', $iso_code);
             $iso_code = $tmpArray[0];
             if (count($tmpArray) > 0) {
                 $iso_code = 'E' . $tmpArray[1];
             }
         }
         $exists_id = State::getIdByIso($iso_code);
         if (isset($exists_id) && !empty($exists_id)) {
             $state = new State($exists_id);
             $state->active = true;
             $state->id_zone = self::$baleares->id;
             if (!$state->update()) {
                 return false;
             }
         } else {
             $state = new State();
             $state->name = $state_name;
             $state->id_country = self::$spain->id;
             $state->id_zone = self::$baleares->id;
             $state->iso_code = $iso_code;
             $state->active = true;
             if (!$state->save()) {
                 return false;
             }
         }
     }
     foreach (SeurLib::$canarias_states as $iso_code => $state_name) {
         if (Tools::strlen($iso_code) > $ps_state_iso_code_max_length) {
             $tmpArray = explode('-', $iso_code);
             $iso_code = $tmpArray[0];
             if (count($tmpArray) > 0) {
                 $iso_code = 'E' . $tmpArray[1];
             }
         }
         $exists_id = State::getIdByIso($iso_code);
         if (isset($exists_id) && !empty($exists_id)) {
             $state = new State($exists_id);
             $state->active = true;
             $state->id_zone = self::$canarias->id;
             if (!$state->update()) {
                 return false;
             }
         } else {
             $state = new State();
             $state->name = $state_name;
             $state->id_country = self::$spain->id;
             $state->id_zone = self::$canarias->id;
             $state->iso_code = $iso_code;
             $state->active = true;
             if (!$state->save()) {
                 return false;
             }
         }
     }
     foreach (SeurLib::$ceuta_melilla_states as $iso_code => $state_name) {
         if (Tools::strlen($iso_code) > $ps_state_iso_code_max_length) {
             $tmpArray = explode('-', $iso_code);
             $iso_code = $tmpArray[0];
             if (count($tmpArray) > 0) {
                 $iso_code = 'E' . $tmpArray[1];
             }
         }
         $exists_id = State::getIdByIso($iso_code);
         if (isset($exists_id) && !empty($exists_id)) {
             $state = new State($exists_id);
             $state->id_zone = self::$ceuta_melilla->id;
             $state->active = true;
             if (!$state->update()) {
                 return false;
             }
         } else {
             $state = new State();
             $state->name = $state_name;
             $state->id_country = self::$spain->id;
             $state->id_zone = self::$ceuta_melilla->id;
             $state->iso_code = $iso_code;
             $state->active = true;
             if (!$state->save()) {
                 return false;
             }
         }
     }
     foreach (SeurLib::$spain_states as $iso_code => $state_name) {
         if (Tools::strlen($iso_code) > $ps_state_iso_code_max_length) {
             $tmpArray = explode('-', $iso_code);
             $iso_code = $tmpArray[0];
             if (count($tmpArray) > 0) {
                 $iso_code = 'E' . $tmpArray[1];
             }
         }
         $exists_id = State::getIdByIso($iso_code);
         if (isset($exists_id) && !empty($exists_id)) {
             $state = new State($exists_id);
             $state->active = true;
             if (Tools::strtoupper($state_name) == Tools::strtoupper(SeurLib::getMerchantField('state'))) {
                 $state->id_zone = self::$provincia->id;
             } else {
                 $state->id_zone = self::$peninsula->id;
             }
             if (!$state->update()) {
                 return false;
             }
         } else {
             $state = new State();
             $state->name = $state_name;
             $state->id_country = self::$spain->id;
             if (Tools::strtoupper($state_name) == Tools::strtoupper(SeurLib::getMerchantField('state'))) {
                 $state->id_zone = self::$provincia->id;
             } else {
                 $state->id_zone = self::$peninsula->id;
             }
             $state->iso_code = $iso_code;
             $state->active = true;
             if (!$state->save()) {
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 7
0
    public function getContent()
    {
        $buffer = '';
        if (Tools::isSubmit('SubmitAvalaraTaxSettings')) {
            Configuration::updateValue('AVALARATAX_ACCOUNT_NUMBER', Tools::getValue('avalaratax_account_number'));
            Configuration::updateValue('AVALARATAX_LICENSE_KEY', Tools::getValue('avalaratax_license_key'));
            Configuration::updateValue('AVALARATAX_URL', Tools::getValue('avalaratax_url'));
            Configuration::updateValue('AVALARATAX_COMPANY_CODE', Tools::getValue('avalaratax_company_code'));
            $buffer .= $this->_displayConfirmation();
        } elseif (Tools::isSubmit('SubmitAvalaraTaxOptions')) {
            Configuration::updateValue('AVALARATAX_ADDRESS_VALIDATION', Tools::getValue('avalaratax_address_validation'));
            Configuration::updateValue('AVALARATAX_TAX_CALCULATION', Tools::getValue('avalaratax_tax_calculation'));
            Configuration::updateValue('AVALARATAX_TIMEOUT', (int) Tools::getValue('avalaratax_timeout'));
            Configuration::updateValue('AVALARATAX_ADDRESS_NORMALIZATION', Tools::getValue('avalaratax_address_normalization'));
            Configuration::updateValue('AVALARATAX_TAX_OUTSIDE', Tools::getValue('avalaratax_tax_outside'));
            Configuration::updateValue('AVALARA_CACHE_MAX_LIMIT', Tools::getValue('avalara_cache_max_limit') < 1 ? 1 : Tools::getValue('avalara_cache_max_limit') > 23 ? 23 : Tools::getValue('avalara_cache_max_limit'));
            $buffer .= $this->_displayConfirmation();
        } elseif (Tools::isSubmit('SubmitAvalaraTestConnection')) {
            $connectionTestResult = $this->_testConnection();
        } elseif (Tools::isSubmit('SubmitAvalaraAddressOptions')) {
            /* Validate address*/
            $address = new Address();
            $address->address1 = Tools::getValue('avalaratax_address_line1');
            $address->address2 = Tools::getValue('avalaratax_address_line2');
            $address->city = Tools::getValue('avalaratax_city');
            $address->id_state = State::getIdByIso(Tools::getValue('avalaratax_state'));
            $address->id_country = Tools::getValue('avalaratax_country');
            $address->postcode = Tools::getValue('avalaratax_zip_code');
            $normalizedAddress = $this->validateAddress($address);
            if (isset($normalizedAddress['ResultCode']) && $normalizedAddress['ResultCode'] == 'Success') {
                $buffer .= $this->_displayConfirmation($this->l('The address you submitted has been validated.'));
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE1', $normalizedAddress['Normalized']['Line1']);
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE2', $normalizedAddress['Normalized']['Line2']);
                Configuration::updateValue('AVALARATAX_CITY', $normalizedAddress['Normalized']['City']);
                Configuration::updateValue('AVALARATAX_STATE', $normalizedAddress['Normalized']['Region']);
                Configuration::updateValue('AVALARATAX_COUNTRY', $normalizedAddress['Normalized']['Country']);
                Configuration::updateValue('AVALARATAX_ZIP_CODE', $normalizedAddress['Normalized']['PostalCode']);
            } else {
                $message = $this->l('The following error was generated while validating your address:');
                if (isset($normalizedAddress['Exception']['FaultString'])) {
                    $message .= '<br /> - ' . Tools::safeOutput($normalizedAddress['Exception']['FaultString']);
                }
                if (isset($normalizedAddress['Messages']['Summary'])) {
                    foreach ($normalizedAddress['Messages']['Summary'] as $summary) {
                        $message .= '<br /> - ' . Tools::safeOutput($summary);
                    }
                }
                $buffer .= $this->_displayConfirmation($message, 'error');
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE1', Tools::getValue('avalaratax_address_line1'));
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE2', Tools::getValue('avalaratax_address_line2'));
                Configuration::updateValue('AVALARATAX_CITY', Tools::getValue('avalaratax_city'));
                Configuration::updateValue('AVALARATAX_STATE', Tools::getValue('avalaratax_state'));
                Configuration::updateValue('AVALARATAX_ZIP_CODE', Tools::getValue('avalaratax_zip_code'));
            }
        } elseif (Tools::isSubmit('SubmitAvalaraTaxClearCache')) {
            Db::getInstance()->Execute('TRUNCATE TABLE `' . _DB_PREFIX_ . 'avalara_product_cache`');
            Db::getInstance()->Execute('TRUNCATE TABLE `' . _DB_PREFIX_ . 'avalara_carrier_cache`');
            $buffer .= $this->_displayConfirmation('Cache cleared!');
        }
        $confValues = Configuration::getMultiple(array('AVALARATAX_ACCOUNT_NUMBER', 'AVALARATAX_LICENSE_KEY', 'AVALARATAX_URL', 'AVALARATAX_COMPANY_CODE', 'AVALARATAX_ADDRESS_VALIDATION', 'AVALARATAX_TAX_CALCULATION', 'AVALARATAX_TIMEOUT', 'AVALARATAX_ADDRESS_NORMALIZATION', 'AVALARATAX_TAX_OUTSIDE', 'AVALARATAX_COMMIT_ID', 'AVALARATAX_CANCEL_ID', 'AVALARATAX_REFUND_ID', 'AVALARATAX_POST_ID', 'AVALARA_CACHE_MAX_LIMIT', 'AVALARATAX_ADDRESS_LINE1', 'AVALARATAX_ADDRESS_LINE2', 'AVALARATAX_CITY', 'AVALARATAX_STATE', 'AVALARATAX_ZIP_CODE', 'AVALARATAX_COUNTRY'));
        $stateList = array();
        $stateList[] = array('id' => '0', 'name' => $this->l('Choose your state (if applicable)'), 'iso_code' => '--');
        foreach (State::getStates((int) $this->context->cookie->id_lang) as $state) {
            $stateList[] = array('id' => $state['id_state'], 'name' => $state['name'], 'iso_code' => $state['iso_code']);
        }
        $countryList = array();
        $countryList[] = array('id' => '0', 'name' => $this->l('Choose your country'), 'iso_code' => '--');
        foreach (Country::getCountries((int) $this->context->cookie->id_lang, false, null, false) as $country) {
            $countryList[] = array('id' => $country['id_country'], 'name' => $country['name'], 'iso_code' => $country['iso_code']);
        }
        $buffer .= '<style type="text/css">
			fieldset.avalaratax_fieldset td.avalaratax_column { padding: 0 18px; text-align: right; vertical-align: top;}
			fieldset.avalaratax_fieldset input[type=text] { width: 250px; }
			fieldset.avalaratax_fieldset input.avalaratax_button { margin-top: 10px; }
			fieldset.avalaratax_fieldset div#test_connection { margin-left: 18px; border: 1px solid #DFD5C3; padding: 5px; font-size: 11px; margin-bottom: 10px; width: 90%; }
			fieldset.avalaratax_fieldset a { color: #0000CC; font-weight: bold; text-decoration: underline; }
			.avalara-pagination {display: inline-block; float: right; }
			.avalara-pagination ul {list-style: none; display: inline-block; margin: 0; padding: 0;}
			.avalara-pagination ul li {margin-left: 10px; display: inline-block;}
			.clear {clear: both; margin: 0 auto;}
			.current-page {border: 1px solid #000; padding: 3px;}
			.orders-table {border-collapse:collapse;}
			.orders-table tr { vertical-align: top;}
			.orders-table tr td { border-top: 1px solid #000;}
		</style>
		<script type="text/javascript">
			$(function() {
				/* Add video */
				$(\'<div style="left: 567px; top: 11px; position: relative; width: 361px; height: 0px"><iframe width="360" height="215" src="http://www.youtube.com/embed/tm1tENVdcQ8" frameborder="0" allowfullscreen></iframe></div>\').prependTo(\'#content form:eq(0)\');
			});
		</script>

		<h2>' . Tools::safeOutput($this->displayName) . '</h2>
		<div class="hint clear" style="display:block;">
				<a style="float: right;" target="_blank" href="http://www.prestashop.com/en/industry-partners/management/avalara"><img alt="" src="../modules/avalaratax/avalaratax_logo.png"></a>
				<div style="width: 700px; margin: 0 auto; text-align: center"><h3 style="color: red">' . $this->l('This module is intended to work ONLY in United States of America and Canada') . '</h3></div>
				<h3>' . $this->l('How to configure Avalara Tax Module:') . '</h3>
				- ' . $this->l('Fill the Account Number, License Key, and Company Code fields with those provided by Avalara.') . ' <br />
				- ' . $this->l('Specify your origin address. This is FROM where you are shipping the products (It has to be a ') . '<b>' . $this->l('VALID UNITED STATES ADDRESS') . '</b>)<br /><br />
				<h3>' . $this->l('Module goal:') . '</h3>
				' . $this->l('This cloud-based service is the fastest, easiest, most accurate and affordable way to calculate sales and use tax; manage exemption certificates; file returns; and remit payments across North America and beyond.') . '<br /><br />
				<h3>' . $this->l('What modifications does the module do on my store?') . '</h3>
				- ' . $this->l('Tax.php, AddressController.php, and AuthController.php will be overriden.') . '<br />
				- ' . $this->l('[Payment Tab -> Taxes] and [Payment Tab -> Tax Rules] configurations will be overriden for the US.') . '<br />
				- ' . $this->l('On product details (product in edit mode) an optional "Tax Code" field will be added allowing you to specify a valid tax code for each of your products.') . '<br />
		</div>
		<br />
		<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '" method="post">
			<fieldset class="width2 avalaratax_fieldset">
				<legend><img src="../img/admin/cog.gif" alt="" />' . $this->l('Configuration') . '</legend>
				<h3>' . $this->l('AvaTax Credentials') . '</h3>';
        if (isset($connectionTestResult)) {
            $buffer .= '<div id="test_connection" style="background: ' . Tools::safeOutput($connectionTestResult[1]) . ';">' . $connectionTestResult[0] . '</div>';
        }
        $buffer .= '<table border="0" cellspacing="5">
					<tr>
						<td class="avalaratax_column">' . $this->l('Account Number') . '</td>
						<td><input type="text" name="avalaratax_account_number" value="' . (isset($confValues['AVALARATAX_ACCOUNT_NUMBER']) ? Tools::safeOutput($confValues['AVALARATAX_ACCOUNT_NUMBER']) : '') . '" /></td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('License Key') . '</td>
						<td><input type="text" name="avalaratax_license_key" value="' . (isset($confValues['AVALARATAX_LICENSE_KEY']) ? Tools::safeOutput($confValues['AVALARATAX_LICENSE_KEY']) : '') . '" /></td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('URL') . '</td>
						<td><input type="text" name="avalaratax_url" value="' . (isset($confValues['AVALARATAX_URL']) ? Tools::safeOutput($confValues['AVALARATAX_URL']) : '') . '" /></td>
					</tr>
					<tr>
						<td class="avalaratax_column" style="vertical-align: top; padding-top: 3px;">' . $this->l('Company Code') . '</td>
						<td><input type="text" name="avalaratax_company_code" value="' . (isset($confValues['AVALARATAX_COMPANY_CODE']) ? Tools::safeOutput($confValues['AVALARATAX_COMPANY_CODE']) : '') . '" /><br />
						<span style="color: #7F7F7F; font-size: 10px;">' . $this->l('Located in the top-right corner of your AvaTax Admin Console') . '</span></td>
					</tr>
				</table>
				<center><input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxSettings" value="' . $this->l('Save Settings') . '" /></center>
				<hr size="1" style="margin: 14px auto;" noshade />
				<center><img src="../img/admin/exchangesrate.gif" alt="" /> <input type="submit" id="avalaratax_test_connection" class="button avalaratax_button" name="SubmitAvalaraTestConnection" value="' . $this->l('Click here to Test Connection') . '" style="margin-top: 0;" /></center>
			</fieldset>
		</form>
		<br />
		<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '" method="post">
			<fieldset class="width2 avalaratax_fieldset">
				<legend><img src="../img/admin/cog.gif" alt="" />' . $this->l('Options') . '</legend>
				<table border="0">
					<tr>
						<td class="avalaratax_column">' . $this->l('Enable address validation') . '</td>
						<td><input type="checkbox" name="avalaratax_address_validation" value="1"' . (isset($confValues['AVALARATAX_ADDRESS_VALIDATION']) && $confValues['AVALARATAX_ADDRESS_VALIDATION'] ? ' checked="checked"' : '') . ' /></td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Enable tax calculation') . '</td>
						<td><input type="checkbox" name="avalaratax_tax_calculation" value="1" ' . (isset($confValues['AVALARATAX_TAX_CALCULATION']) && $confValues['AVALARATAX_TAX_CALCULATION'] ? ' checked="checked"' : '') . ' /></td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Enable address normalization in uppercase') . '</td>
						<td><input type="checkbox" name="avalaratax_address_normalization" value="1" ' . (isset($confValues['AVALARATAX_ADDRESS_NORMALIZATION']) && $confValues['AVALARATAX_ADDRESS_NORMALIZATION'] ? ' checked="checked"' : '') . ' /></td>
					</tr>
<tr>
						<td class="avalaratax_column">' . $this->l('Enable tax calculation outside of your state') . '</td>
						<td><input type="checkbox" name="avalaratax_tax_outside" value="1" ' . (isset($confValues['AVALARATAX_TAX_OUTSIDE']) && $confValues['AVALARATAX_TAX_OUTSIDE'] ? ' checked="checked"' : '') . ' /></td>
</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Request timeout') . '</td>
						<td><input type="text" name="avalaratax_timeout" value="' . (isset($confValues['AVALARATAX_TIMEOUT']) ? Tools::safeOutput($confValues['AVALARATAX_TIMEOUT']) : '') . '" style="width: 50px;" /> <span style="font-size: 11px;">' . $this->l('seconds') . '</span></td>
					</tr>
					<tr style="display: none;">

						<td class="avalaratax_column">' . $this->l('Refresh tax rate cache every: ') . '</td>
						<td><input type="text" name="avalara_cache_max_limit" value="' . (isset($confValues['AVALARA_CACHE_MAX_LIMIT']) ? Tools::safeOutput($confValues['AVALARA_CACHE_MAX_LIMIT']) : '') . '" style="width: 50px;" /> <span style="font-size: 11px;">' . $this->l('minutes') . '</span></td>
					</tr>

				</table>
				<center><input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxOptions" value="' . $this->l('Save Settings') . '" />
				<input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxClearCache" value="' . $this->l('Clear Cache') . '" style="display: none"/>
				</center>
				<h3 style="margin: 10px 0px 0px; padding-top: 3px;border-top: 1px solid #000;">' . $this->l('Default Post/Commit/Cancel/Refund Options') . '</h3>
				<span style="font-style: italic; font-size: 11px; color: #888;">' . $this->l('When an order\'s status is updated, the following options will be used to update Avalara\'s records.') . '</span><br /><br />';
        // Check if the order status exist
        $orderStatusList = array();
        foreach (Db::getInstance()->ExecuteS('SELECT `id_order_state`, `name` FROM `' . _DB_PREFIX_ . 'order_state_lang` WHERE `id_lang` = ' . (int) $this->context->cookie->id_lang) as $v) {
            $orderStatusList[$v['id_order_state']] = Tools::safeOutput($v['name']);
        }
        $buffer .= '<table>
					<th style="text-align: right; padding-right: 65px; border: 1px solid #000;">' . $this->l('Action') . '</th>
					<th style="text-align: left; border: 1px solid #000; padding: 0px 15px;">' . $this->l('Order status in your store') . '</th>
					<tr>
						<td class="avalaratax_column">' . $this->l('Post order to Avalara') . ':</td>
						<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_POST_ID')]) ? Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_POST_ID')]) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
						</td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Commit order to Avalara') . ':</td>
						<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_COMMIT_ID')]) ? Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_COMMIT_ID')]) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
						</td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Delete order from Avalara') . ':</td>
						<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_CANCEL_ID')]) ? Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_CANCEL_ID')]) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
						</td>
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Void order in Avalara') . ':</td>
						<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_REFUND_ID')]) ? Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_REFUND_ID')]) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
						</td>
					</tr>
				</table>
				<div class="clear"></div>
			</fieldset>
		</form>
		<br />
		<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '" method="post">
			<fieldset class="width2 avalaratax_fieldset">
				<legend><img src="../img/admin/delivery.gif" alt="" />' . $this->l('Default Origin Address') . '</legend>
				<table border="0">
					<tr>
						<td class="avalaratax_column">' . $this->l('Address Line 1') . '</td>
						<td><input type="text" name="avalaratax_address_line1" value="' . (isset($confValues['AVALARATAX_ADDRESS_LINE1']) ? Tools::safeOutput($confValues['AVALARATAX_ADDRESS_LINE1']) : '') . '" /><br />
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Address Line 2') . '</td>
						<td><input type="text" name="avalaratax_address_line2" value="' . (isset($confValues['AVALARATAX_ADDRESS_LINE2']) ? Tools::safeOutput($confValues['AVALARATAX_ADDRESS_LINE2']) : '') . '" /><br />
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('City') . '</td>
						<td><input type="text" name="avalaratax_city" value="' . (isset($confValues['AVALARATAX_CITY']) ? Tools::safeOutput($confValues['AVALARATAX_CITY']) : '') . '" /><br />
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('State') . '</td>
						<td>
							<select name="avalaratax_state" id="avalaratax_state">';
        foreach ($stateList as $state) {
            $buffer .= '<option value="' . substr(strtoupper($state['iso_code']), 0, 2) . '" ' . ($state['iso_code'] == $confValues['AVALARATAX_STATE'] ? ' selected="selected"' : '') . '>' . Tools::safeOutput($state['name']) . '</option>';
        }
        $buffer .= '</select>
						</td>
						<br />
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Zip Code') . '</td>
						<td><input type="text" name="avalaratax_zip_code" value="' . (isset($confValues['AVALARATAX_ZIP_CODE']) ? Tools::safeOutput($confValues['AVALARATAX_ZIP_CODE']) : '') . '" /><br />
					</tr>
					<tr>
						<td class="avalaratax_column">' . $this->l('Country') . '</td>
						<td>
							<select name="avalaratax_country" id="avalaratax_country">';
        foreach ($countryList as $country) {
            $buffer .= '<option value="' . substr(strtoupper($country['iso_code']), 0, 2) . '" ' . ($country['iso_code'] == $confValues['AVALARATAX_COUNTRY'] ? ' selected="selected"' : '') . '>' . Tools::safeOutput($country['name']) . '</option>';
        }
        return $buffer . '</select>
						</td>
					</tr>
				</table>
				<center><input type="submit" class="button avalaratax_button" name="SubmitAvalaraAddressOptions" value="' . $this->l('Save Settings') . '" /></center>
			</fieldset>
		</form>
		<br />
		<fieldset class="width2 avalaratax_fieldset">
		<legend><img src="../img/admin/statsettings.gif" alt="" />' . $this->l('AvaTax Admin Console') . '</legend>
			<p><a href="https://admin-avatax.avalara.net/" target="_blank">' . $this->l('Log-in to AvaTax Admin Console') . '</a></p>
		</fieldset><br />';
    }
Ejemplo n.º 8
0
    public function validation()
    {
        if (!$this->active || !Configuration::get('GOINTERPAY_STORE') || !Configuration::get('GOINTERPAY_SECRET')) {
            return false;
        }
        if (!isset($_GET['orderId'])) {
            return false;
        }
        include_once _PS_MODULE_DIR_ . 'gointerpay/Rest.php';
        $rest = new Rest(Configuration::get('GOINTERPAY_STORE'), Configuration::get('GOINTERPAY_SECRET'));
        $result = $rest->orderDetail(Tools::safeOutput(Tools::getValue('orderId')));
        $cart = new Cart((int) $result['cartId']);
        $original_total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
        /* Check the currency code */
        $id_currency_new = (int) Currency::getIdByIsoCode($result['foreignCurrencyCode']);
        if ($id_currency_new) {
            $cart->id_currency = (int) $id_currency_new;
            $cart->save();
        } else {
            die('Sorry, we were not able to accept orders in the following currency: ' . Tools::safeOutput($result['foreignCurrencyCode']));
        }
        $name = explode(" ", $result['delivery_address']['name']);
        $lastname = " - ";
        if (isset($name[1])) {
            $lastname = $name[1];
        }
        /* Update the delivery and billing address */
        $delivery_address = new Address((int) $cart->id_address_delivery);
        $delivery_address->firstname = $name[0];
        $delivery_address->lastname = $lastname;
        $delivery_address->company = $result['delivery_address']['company'];
        $delivery_address->phone = $result['delivery_address']['phone'];
        $delivery_address->phone_mobile = $result['delivery_address']['altPhone'];
        $delivery_address->id_country = (int) Country::getByIso($result['delivery_address']['countryCode']);
        $delivery_address->id_state = (int) State::getIdByIso($result['delivery_address']['state'], (int) $delivery_address->id_country);
        $delivery_address->address1 = $result['delivery_address']['address1'];
        $delivery_address->address2 = $result['delivery_address']['address2'];
        $delivery_address->city = $result['delivery_address']['city'];
        $delivery_address->postcode = $result['delivery_address']['zip'];
        $delivery_address->save();
        /* If no billing address specified, use the delivery address */
        if ($result['invoice_address']['address1'] != '' || $result['invoice_address']['city'] != '') {
            $invoice_name = explode(" ", $result['invoice_address']['name']);
            $invoice_lastname = " - ";
            if (isset($invoice_name[1])) {
                $invoice_lastname = $invoice_name[1];
            }
            $invoice_address = new Address((int) $cart->id_address_invoice);
            $invoice_address->firstname = $invoice_name[0];
            $invoice_address->lastname = $invoice_lastname;
            $invoice_address->company = $result['invoice_address']['company'];
            $invoice_address->phone = $result['invoice_address']['phone'];
            $invoice_address->phone_mobile = $result['invoice_address']['altPhone'];
            $invoice_address->id_country = (int) Country::getByIso($result['invoice_address']['countryCode']);
            $invoice_address->id_state = (int) State::getIdByIso($result['invoice_address']['state'], (int) $invoice_address->id_country);
            $invoice_address->address1 = $result['invoice_address']['address1'];
            $invoice_address->address2 = $result['invoice_address']['address2'];
            $invoice_address->city = $result['invoice_address']['city'];
            $invoice_address->postcode = $result['invoice_address']['zip'];
            if ($cart->id_address_delivery == $cart->id_address_invoice) {
                $invoice_address->add();
                $cart->id_address_invoice = (int) $invoice_address->id;
                $cart->save();
            } else {
                $invoice_address->save();
            }
        }
        /* Store the Order ID and Shipping cost */
        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'gointerpay_order_id` (`id_cart`, `orderId`, `shipping`, `shipping_orig`, `taxes`, `total`, `products`, `status`)
		VALUES (\'' . (int) $cart->id . '\', \'' . pSQL(Tools::getValue('orderId')) . '\', \'' . (double) $result['shippingTotal'] . '\', \'' . (double) $result['shippingTotalForeign'] . '\', \'' . (double) $result['quotedDutyTaxes'] . '\', \'' . (double) $result['grandTotal'] . '\', \'' . (double) $result['itemsTotal'] . '\', \'Init\')');
        /* Add the duties and taxes */
        Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'specific_price` WHERE id_customer = ' . (int) $cart->id_customer . ' AND id_product = ' . (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'));
        $specific_price = new SpecificPrice();
        $specific_price->id_product = (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES');
        $specific_price->id_shop = 0;
        $specific_price->id_country = 0;
        $specific_price->id_group = 0;
        $specific_price->id_cart = (int) $cart->id;
        $specific_price->id_product_attribute = 0;
        $specific_price->id_currency = $cart->id_currency;
        $specific_price->id_customer = $cart->id_customer;
        $specific_price->price = (double) $result['quotedDutyTaxesForeign'];
        $specific_price->from_quantity = 1;
        $specific_price->reduction = 0;
        $specific_price->reduction_type = 'percentage';
        $specific_price->from = date('Y-m-d H:i:s');
        $specific_price->to = strftime('%Y-%m-%d %H:%M:%S', time() + 10);
        $specific_price->add();
        if (Validate::isLoadedObject($specific_price)) {
            $cart->updateQty(1, (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'));
        }
        $result['status'] = 'Pending';
        $total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
        $message = '
		Total paid on Interpay: ' . (double) $result['grandTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Duties and taxes on Interpay: ' . (double) $result['quotedDutyTaxesForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Shipping on Interpay: ' . (double) $result['shippingTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Currency: ' . $result['foreignCurrencyCode'];
        if ($result['status'] == 'Pending') {
            $this->context->cart->id = (int) $result['cartId'];
            Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Pending\' WHERE `id_cart` = ' . (int) $cart->id);
            $order_status = Configuration::get('GOINTERPAY_PAYMENT_PENDING');
            $price_difference = abs($original_total - ((double) $result['grandTotalForeign'] - (double) $result['quotedDutyTaxesForeign'] - (double) $result['shippingTotalForeign'])) * 100 / $original_total;
            if ($price_difference > 1) {
                /* Uncomment this line if you would like to decline orders with a too high price difference */
                // $order_status = Configuration::get('PS_OS_ERROR');
                /*$message .= '
                		
                		Warning: The difference between the price paid and the price to pay was higher than 1% ('.number_format($price_difference, 2, '.', '').'%)
                		However, the payment was processed by Interpay, you should get in touch with the customer and Interpay to resolve that matter.';*/
            }
            $this->validateOrder((int) $cart->id, (int) $order_status, $total, $this->displayName, $message, array(), NULL, false, $cart->secure_key);
            Tools::redirectLink(__PS_BASE_URI__ . 'history.php');
        } else {
            die('Order was not found or cannot be validated at this time, please contact us.');
        }
    }
Ejemplo n.º 9
0
 /**
  * @param $address
  * @param $customer
  * @return int
  * @throws ShopgateLibraryException
  */
 public function createAddress(ShopgateAddress $address, $customer)
 {
     /** @var AddressCore | Address $addressModel */
     $addressItem = new Address();
     $addressItem->id_customer = $customer->id;
     $addressItem->lastname = $address->getLastName();
     $addressItem->firstname = $address->getFirstName();
     if ($address->getCompany()) {
         $addressItem->company = $address->getCompany();
     }
     $addressItem->address1 = $address->getStreet1();
     if ($address->getStreet2()) {
         $addressItem->address2 = $address->getStreet2();
     }
     $addressItem->city = $address->getCity();
     $addressItem->postcode = $address->getZipcode();
     if (!Validate::isLanguageIsoCode($address->getCountry())) {
         $customer->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, 'invalid country code: ' . $address->getCountry(), true);
     }
     $addressItem->id_country = Country::getByIso($address->getCountry());
     /**
      * prepare states
      */
     $stateParts = explode('-', $address->getState());
     if (count($stateParts) == 2) {
         $address->setState($stateParts[1]);
     }
     if ($address->getState() && !Validate::isStateIsoCode($address->getState())) {
         $customer->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, 'invalid state code: ' . $address->getState(), true);
     } else {
         $addressItem->id_state = State::getIdByIso($address->getState());
     }
     $addressItem->alias = $address->getIsDeliveryAddress() ? $this->getModule()->l('Default delivery address') : $this->getModule()->l('Default');
     $addressItem->alias = $address->getIsInvoiceAddress() ? $this->getModule()->l('Default invoice address') : $this->getModule()->l('Default');
     $addressItem->phone = $address->getPhone();
     $addressItem->phone_mobile = $address->getMobile();
     $shopgateCustomFieldsHelper = new ShopgateCustomFieldsHelper();
     $shopgateCustomFieldsHelper->saveCustomFields($addressItem, $address->getCustomFields());
     $validateMessage = $addressItem->validateFields(false, true);
     if ($validateMessage !== true) {
         $customer->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, $validateMessage, true);
     }
     $addressItem->save();
     return $addressItem->id;
 }
Ejemplo n.º 10
0
 private function validateCSVRegions($csv_data, $csv_data_count)
 {
     $wrong_regions = '';
     $wrong_regions_country = '';
     for ($i = 0; $i < $csv_data_count; $i++) {
         if ($this->validateCSVCountry($csv_data[$i][DpdGroupCSV::COLUMN_COUNTRY]) && $csv_data[$i][DpdGroupCSV::COLUMN_REGION] !== '*') {
             $id_state = (int) State::getIdByIso($csv_data[$i][DpdGroupCSV::COLUMN_REGION]);
             if ($csv_data[$i][DpdGroupCSV::COLUMN_COUNTRY] === '*') {
                 $wrong_regions .= $i + self::DEFAULT_FIRST_LINE_INDEX . ', ';
             } else {
                 $id_country = (int) Country::getByIso($csv_data[$i][DpdGroupCSV::COLUMN_COUNTRY]);
                 $state = new State((int) $id_state);
                 if ($state->id_country != $id_country) {
                     $wrong_regions_country .= $i + self::DEFAULT_FIRST_LINE_INDEX . ', ';
                 }
             }
         }
     }
     $this->removeLastSymbolsFromString($wrong_regions);
     $this->removeLastSymbolsFromString($wrong_regions_country);
     return empty($wrong_regions) && empty($wrong_regions_country) ? true : array($wrong_regions, $wrong_regions_country);
 }
Ejemplo n.º 11
0
 /**
  * Check Shiptotmyid status for an specific order.
  */
 public function checkOrderStatus($id_order, $result = null)
 {
     $shipto_order = ShiptomyidOrder::getByIdOrder($id_order);
     if (!Validate::isLoadedObject($shipto_order)) {
         ShiptomyidLog::addLog('invalid shiptomyid_order object', $id_order);
         return false;
     }
     if ($result === null) {
         $result = $this->api->getOrder($shipto_order->id_shiptomyid);
     }
     if (isset($result['ExternalOrder'])) {
         if ($result['ExternalOrder']['is_order_accepted'] == 'true') {
             $result_data = $result['ExternalOrder'];
             $id_country = (int) Country::getByIso($result_data['countryCode']);
             $id_state = (int) State::getIdByIso($result_data['stateCode']);
             if (!$id_state) {
                 $id_state = (int) StateCore::getIdByName($result_data['stateName']);
             }
             $data = array('firstname' => $result_data['receiver_first_name'], 'lastname' => $result_data['receiver_last_name'], 'address1' => $result_data['address_1'], 'postcode' => $result_data['zipcode'], 'city' => $result_data['city'], 'id_country' => $id_country, 'id_state' => $id_state, 'phone' => $result_data['phoneNumber']);
             $shipto_order->setDeliveryAddress($data);
             $order_state = new OrderState(self::$os_ready);
             if (Validate::isLoadedObject($order_state)) {
                 ShiptomyidOrder::changeOrderStatus($id_order, self::$os_ready);
                 ShiptomyidOrder::addMessageToOrder($id_order, $this->l('Order is ready to delivery.') . '<br/><pre>' . print_r($data, true) . '</pre>');
             }
         } elseif ($result['ExternalOrder']['is_order_rejected'] == 'true') {
             $result_data = $result['ExternalOrder'];
             $order_state = new OrderState(self::$os_cancel);
             if (Validate::isLoadedObject($order_state)) {
                 ShiptomyidOrder::changeOrderStatus($id_order, self::$os_cancel);
                 ShiptomyidOrder::addMessageToOrder($id_order, $this->l('Order is rejected : ') . $result_data['receiver_rejected_note']);
             }
         }
     } elseif (isset($result['Error'])) {
         ShiptomyidLog::addLog('Check order status error in cron task : ' . $result['Error']['message'] . ' [' . $result['Error']['status'] . ']', $id_order);
         return false;
     }
     return true;
 }
Ejemplo n.º 12
0
 /**
  * @param $isoCode
  * @return mixed
  * @throws ShopgateLibraryException
  */
 protected function getStateIdByIsoCode($isoCode)
 {
     $stateId = null;
     if ($isoCode) {
         $stateParts = explode('-', $isoCode);
         if (is_array($stateParts)) {
             if (count($stateParts) == 2) {
                 $stateId = State::getIdByIso($stateParts[1], $this->_getCountryIdByIsoCode($stateParts[0]));
             } else {
                 $stateId = State::getIdByIso($stateParts[0]);
             }
         }
         if ($stateId) {
             return $stateId;
         } else {
             $this->_addException(ShopgateLibraryException::UNKNOWN_ERROR_CODE, ' invalid or empty iso code #' . $isoCode);
         }
     }
 }
Ejemplo n.º 13
0
 public function init()
 {
     self::$amz_payments = new AmzPayments();
     $this->isLogged = (bool) $this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer);
     parent::init();
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     $this->display_column_left = false;
     $this->display_column_right = false;
     $this->service = self::$amz_payments->getService();
     $this->nbProducts = $this->context->cart->nbProducts();
     if (Configuration::get('PS_CATALOG_MODE')) {
         $this->errors[] = Tools::displayError('This store has not accepted your new order.');
     }
     if ($this->nbProducts) {
         if (CartRule::isFeatureActive()) {
             if (Tools::isSubmit('submitAddDiscount')) {
                 if (!($code = trim(Tools::getValue('discount_name')))) {
                     $this->errors[] = Tools::displayError('You must enter a voucher code.');
                 } elseif (!Validate::isCleanHtml($code)) {
                     $this->errors[] = Tools::displayError('The voucher code is invalid.');
                 } else {
                     if (($cart_rule = new CartRule(CartRule::getIdByCode($code))) && Validate::isLoadedObject($cart_rule)) {
                         if ($error = $cart_rule->checkValidity($this->context, false, true)) {
                             $this->errors[] = $error;
                         } else {
                             $this->context->cart->addCartRule($cart_rule->id);
                             if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                                 Tools::redirect('index.php?controller=order-opc&addingCartRule=1');
                             }
                             Tools::redirect('index.php?controller=order&addingCartRule=1');
                         }
                     } else {
                         $this->errors[] = Tools::displayError('This voucher does not exists.');
                     }
                 }
                 $this->context->smarty->assign(array('errors' => $this->errors, 'discount_name' => Tools::safeOutput($code)));
             } elseif (($id_cart_rule = (int) Tools::getValue('deleteDiscount')) && Validate::isUnsignedId($id_cart_rule)) {
                 $this->context->cart->removeCartRule($id_cart_rule);
                 Tools::redirect('index.php?controller=order-opc');
             }
         }
         if ($this->context->cart->isVirtualCart()) {
             $this->setNoCarrier();
         }
     } else {
         Tools::redirect('index.php?controller=order-opc');
     }
     $this->context->smarty->assign('back', Tools::safeOutput(Tools::getValue('back')));
     if ($this->nbProducts) {
         $this->context->smarty->assign('virtual_cart', $this->context->cart->isVirtualCart());
     }
     $this->context->smarty->assign('is_multi_address_delivery', $this->context->cart->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1);
     $this->context->smarty->assign('open_multishipping_fancybox', (int) Tools::getValue('multi-shipping') == 1);
     if ($this->context->cart->nbProducts()) {
         if (Tools::isSubmit('ajax')) {
             if (Tools::isSubmit('method')) {
                 switch (Tools::getValue('method')) {
                     case 'setsession':
                         $this->context->cookie->amazon_id = Tools::getValue('amazon_id');
                         $this->context->cookie->amz_access_token = AmzPayments::prepareCookieValueForPrestaShopUse(Tools::getValue('access_token'));
                         $this->context->cookie->amz_access_token_set_time = time();
                         if (!$this->context->customer->isLogged() && self::$amz_payments->lpa_mode != 'pay') {
                             $d = self::$amz_payments->requestTokenInfo(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                             if ($d->aud != self::$amz_payments->client_id) {
                                 error_log('auth error LPA');
                                 die('error');
                             }
                             $d = self::$amz_payments->requestProfile(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                             $customer_userid = $d->user_id;
                             $customer_name = $d->name;
                             $customer_email = $d->email;
                             if ($customers_local_id = AmazonPaymentsCustomerHelper::findByAmazonCustomerId($customer_userid)) {
                                 Hook::exec('actionBeforeAuthentication');
                                 $customer = new Customer();
                                 $authentication = AmazonPaymentsCustomerHelper::getByCustomerID($customers_local_id, true, $customer);
                                 if (isset($authentication->active) && !$authentication->active) {
                                     exit;
                                 } elseif (!$authentication || !$customer->id) {
                                     exit;
                                 } else {
                                     $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                                     $this->context->cookie->id_customer = (int) $customer->id;
                                     $this->context->cookie->customer_lastname = $customer->lastname;
                                     $this->context->cookie->customer_firstname = $customer->firstname;
                                     $this->context->cookie->logged = 1;
                                     $customer->logged = 1;
                                     $this->context->cookie->is_guest = $customer->isGuest();
                                     $this->context->cookie->passwd = $customer->passwd;
                                     $this->context->cookie->email = $customer->email;
                                     // Add customer to the context
                                     $this->context->customer = $customer;
                                     if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                                         $this->context->cart = new Cart($id_cart);
                                     } else {
                                         $id_carrier = (int) $this->context->cart->id_carrier;
                                         $this->context->cart->id_carrier = 0;
                                         $this->context->cart->setDeliveryOption(null);
                                         $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                                         $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                                     }
                                     $this->context->cart->id_customer = (int) $customer->id;
                                     $this->context->cart->secure_key = $customer->secure_key;
                                     if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                                         $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ',');
                                         $this->context->cart->setDeliveryOption($delivery_option);
                                     }
                                     $this->context->cart->save();
                                     $this->context->cookie->id_cart = (int) $this->context->cart->id;
                                     $this->context->cookie->write();
                                     $this->context->cart->autosetProductAddress();
                                     Hook::exec('actionAuthentication');
                                     // Login information have changed, so we check if the cart rules still apply
                                     CartRule::autoRemoveFromCart($this->context);
                                     CartRule::autoAddToCart($this->context);
                                 }
                             }
                         }
                         exit;
                     case 'updateMessage':
                         if (Tools::isSubmit('message')) {
                             $txt_message = urldecode(Tools::getValue('message'));
                             $this->_updateMessage($txt_message);
                             if (count($this->errors)) {
                                 die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             die(true);
                         }
                         break;
                     case 'updateCarrierAndGetPayments':
                         if ((Tools::isSubmit('delivery_option') || Tools::isSubmit('id_carrier')) && Tools::isSubmit('recyclable') && Tools::isSubmit('gift') && Tools::isSubmit('gift_message')) {
                             $this->_assignWrappingAndTOS();
                             if ($this->_processCarrier()) {
                                 $carriers = $this->context->cart->simulateCarriersOutput();
                                 $return = array_merge(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'carrier_data' => $this->_getCarrierList(), 'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array('carriers' => $carriers))), $this->getFormatedSummaryDetail());
                                 Cart::addExtraCarriers($return);
                                 die(Tools::jsonEncode($return));
                             } else {
                                 $this->errors[] = Tools::displayError('An error occurred while updating the cart.');
                             }
                             if (count($this->errors)) {
                                 die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             exit;
                         }
                         break;
                     case 'updateTOSStatusAndGetPayments':
                         if (Tools::isSubmit('checked')) {
                             $this->context->cookie->checkedTOS = (int) Tools::getValue('checked');
                             die(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods())));
                         }
                         break;
                     case 'getCarrierList':
                         die(Tools::jsonEncode($this->_getCarrierList()));
                     case 'getAddressBlockAndCarriersAndPayments':
                         if ($this->context->customer->isLogged()) {
                             if (!Customer::getAddressesTotalById($this->context->customer->id)) {
                                 die(Tools::jsonEncode(array('no_address' => 1)));
                             }
                             if (file_exists(_PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php')) {
                                 include_once _PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php';
                                 $block_user_info = new BlockUserInfo();
                             }
                             $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                             $this->_processAddressFormat();
                             $this->_assignAddress();
                             $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                             $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
                             $return = array_merge(array('order_opc_adress' => $this->context->smarty->fetch(_PS_THEME_DIR_ . 'order-address.tpl'), 'block_user_info' => isset($block_user_info) ? $block_user_info->hookTop(array()) : '', 'carrier_data' => $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'no_address' => 0, 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency)))), $this->getFormatedSummaryDetail());
                             die(Tools::jsonEncode($return));
                         }
                         die(Tools::displayError());
                     case 'makeFreeOrder':
                         if (($id_order = $this->_checkFreeOrder()) && $id_order) {
                             $order = new Order((int) $id_order);
                             $email = $this->context->customer->email;
                             if ($this->context->customer->is_guest) {
                                 $this->context->customer->logout();
                             }
                             die('freeorder:' . $order->reference . ':' . $email);
                         }
                         exit;
                     case 'updateAddressesSelected':
                         $get_order_reference_details_request = new OffAmazonPaymentsService_Model_GetOrderReferenceDetailsRequest();
                         $get_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                         $get_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                         if (isset($this->context->cookie->amz_access_token)) {
                             $get_order_reference_details_request->setAddressConsentToken(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                         }
                         $reference_details_result_wrapper = $this->service->getOrderReferenceDetails($get_order_reference_details_request);
                         $physical_destination = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getDestination()->getPhysicalDestination();
                         $iso_code = (string) $physical_destination->GetCountryCode();
                         $city = (string) $physical_destination->GetCity();
                         $postcode = (string) $physical_destination->GetPostalCode();
                         $state = (string) $physical_destination->GetStateOrRegion();
                         $address_delivery = AmazonPaymentsAddressHelper::findByAmazonOrderReferenceIdOrNew(Tools::getValue('amazonOrderReferenceId'));
                         $address_delivery->id_country = Country::getByIso($iso_code);
                         $address_delivery->alias = 'Amazon Payments Delivery';
                         $address_delivery->lastname = 'amzLastname';
                         $address_delivery->firstname = 'amzFirstname';
                         $address_delivery->address1 = 'amzAddress1';
                         $address_delivery->city = $city;
                         $address_delivery->postcode = $postcode;
                         if ($state != '') {
                             $state_id = State::getIdByIso($state, Country::getByIso($iso_code));
                             if (!$state_id) {
                                 $state_id = State::getIdByName($state);
                             }
                             if ($state_id) {
                                 $address_delivery->id_state = $state_id;
                             }
                         }
                         $address_delivery->save();
                         AmazonPaymentsAddressHelper::saveAddressAmazonReference($address_delivery, Tools::getValue('amazonOrderReferenceId'));
                         $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                         $old_delivery_address_id = $this->context->cart->id_address_delivery;
                         $this->context->cart->id_address_delivery = $address_delivery->id;
                         $this->context->cart->id_address_invoice = $address_delivery->id;
                         $this->context->cart->setNoMultishipping();
                         $this->context->cart->updateAddressId($old_delivery_address_id, $address_delivery->id);
                         if (!$this->context->cart->update()) {
                             $this->errors[] = Tools::displayError('An error occurred while updating your cart.');
                         }
                         $infos = Address::getCountryAndState((int) $this->context->cart->id_address_delivery);
                         if (isset($infos['id_country']) && $infos['id_country']) {
                             $country = new Country((int) $infos['id_country']);
                             $this->context->country = $country;
                         }
                         $cart_rules = $this->context->cart->getCartRules();
                         CartRule::autoRemoveFromCart($this->context);
                         CartRule::autoAddToCart($this->context);
                         if ((int) Tools::getValue('allow_refresh')) {
                             $cart_rules2 = $this->context->cart->getCartRules();
                             if (count($cart_rules2) != count($cart_rules)) {
                                 $this->ajax_refresh = true;
                             } else {
                                 $rule_list = array();
                                 foreach ($cart_rules2 as $rule) {
                                     $rule_list[] = $rule['id_cart_rule'];
                                 }
                                 foreach ($cart_rules as $rule) {
                                     if (!in_array($rule['id_cart_rule'], $rule_list)) {
                                         $this->ajax_refresh = true;
                                         break;
                                     }
                                 }
                             }
                         }
                         if (!$this->context->cart->isMultiAddressDelivery()) {
                             $this->context->cart->setNoMultishipping();
                         }
                         if (!count($this->errors)) {
                             $result = $this->_getCarrierList();
                             if (isset($result['hasError'])) {
                                 unset($result['hasError']);
                             }
                             if (isset($result['errors'])) {
                                 unset($result['errors']);
                             }
                             $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                             $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
                             $result = array_merge($result, array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency))), 'carrier_data' => $this->_getCarrierList(), 'refresh' => (bool) $this->ajax_refresh), $this->getFormatedSummaryDetail());
                             die(Tools::jsonEncode($result));
                         }
                         if (count($this->errors)) {
                             die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
                         }
                         break;
                     case 'multishipping':
                         $this->_assignSummaryInformations();
                         $this->context->smarty->assign('product_list', $this->context->cart->getProducts());
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping-products.tpl');
                         $this->display();
                         die;
                     case 'cartReload':
                         $this->_assignSummaryInformations();
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->context->smarty->assign('opc', true);
                         $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl');
                         $this->display();
                         die;
                     case 'noMultiAddressDelivery':
                         $this->context->cart->setNoMultishipping();
                         die;
                     case 'executeOrder':
                         $customer = new Customer((int) $this->context->cart->id_customer);
                         if (!Validate::isLoadedObject($customer)) {
                             $customer->is_guest = true;
                             $customer->lastname = 'AmazonPayments';
                             $customer->firstname = 'AmazonPayments';
                             $customer->email = 'amazon' . time() . '@localshop.xyz';
                             $customer->passwd = Tools::substr(md5(time()), 0, 10);
                             $customer->save();
                         }
                         if (Tools::getValue('confirm')) {
                             $total = $this->context->cart->getOrderTotal(true, Cart::BOTH);
                             $currency_order = new Currency((int) $this->context->cart->id_currency);
                             $currency_code = $currency_order->iso_code;
                             if (!AmazonTransactions::isAlreadyConfirmedOrder(Tools::getValue('amazonOrderReferenceId'))) {
                                 $set_order_reference_details_request = new OffAmazonPaymentsService_Model_SetOrderReferenceDetailsRequest();
                                 $set_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                                 $set_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 $set_order_reference_details_request->setOrderReferenceAttributes(new OffAmazonPaymentsService_Model_OrderReferenceAttributes());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->setOrderTotal(new OffAmazonPaymentsService_Model_OrderTotal());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getOrderTotal()->setCurrencyCode($currency_code);
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getOrderTotal()->setAmount($total);
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->setPlatformId(self::$amz_payments->getPfId());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->setSellerOrderAttributes(new OffAmazonPaymentsService_Model_SellerOrderAttributes());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getSellerOrderAttributes()->setSellerOrderId(self::$amz_payments->createUniqueOrderId((int) $this->context->cart->id));
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getSellerOrderAttributes()->setStoreName(Configuration::get('PS_SHOP_NAME'));
                                 $this->service->setOrderReferenceDetails($set_order_reference_details_request);
                                 $confirm_order_reference_request = new OffAmazonPaymentsService_Model_ConfirmOrderReferenceRequest();
                                 $confirm_order_reference_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 $confirm_order_reference_request->setSellerId(self::$amz_payments->merchant_id);
                                 $this->service->confirmOrderReference($confirm_order_reference_request);
                                 $get_order_reference_details_request = new OffAmazonPaymentsService_Model_GetOrderReferenceDetailsRequest();
                                 $get_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                                 $get_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 if (isset($this->context->cookie->amz_access_token)) {
                                     $get_order_reference_details_request->setAddressConsentToken(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                                 }
                                 $reference_details_result_wrapper = $this->service->getOrderReferenceDetails($get_order_reference_details_request);
                                 $sql_arr = array('amz_tx_time' => pSQL(time()), 'amz_tx_type' => 'order_ref', 'amz_tx_status' => pSQL($reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getOrderReferenceStatus()->getState()), 'amz_tx_order_reference' => pSQL(Tools::getValue('amazonOrderReferenceId')), 'amz_tx_expiration' => pSQL(strtotime($reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getExpirationTimestamp())), 'amz_tx_reference' => pSQL(Tools::getValue('amazonOrderReferenceId')), 'amz_tx_amz_id' => pSQL(Tools::getValue('amazonOrderReferenceId')), 'amz_tx_last_change' => pSQL(time()), 'amz_tx_amount' => pSQL($reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getOrderTotal()->getAmount()));
                                 Db::getInstance()->insert('amz_transactions', $sql_arr);
                             } else {
                                 $get_order_reference_details_request = new OffAmazonPaymentsService_Model_GetOrderReferenceDetailsRequest();
                                 $get_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                                 $get_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 if (isset($this->context->cookie->amz_access_token)) {
                                     $get_order_reference_details_request->setAddressConsentToken(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                                 }
                                 $reference_details_result_wrapper = $this->service->getOrderReferenceDetails($get_order_reference_details_request);
                             }
                             $physical_destination = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getDestination()->getPhysicalDestination();
                             $iso_code = (string) $physical_destination->GetCountryCode();
                             $city = (string) $physical_destination->GetCity();
                             $postcode = (string) $physical_destination->GetPostalCode();
                             $state = (string) $physical_destination->GetStateOrRegion();
                             $names_array = explode(' ', (string) $physical_destination->getName(), 2);
                             $regex = '/[^a-zA-ZäöüÄÖÜßÂâÀÁáàÇçÈÉËëéèÎîÏïÙÛùúòóûêôíÍŸÿªñÑ\\s]/u';
                             $names_array[0] = preg_replace($regex, '', $names_array[0]);
                             $names_array[1] = preg_replace($regex, '', $names_array[1]);
                             if ($customer->is_guest) {
                                 $customer->lastname = $names_array[1];
                                 $customer->firstname = $names_array[0];
                                 $customer->email = (string) $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getBuyer()->getEmail();
                                 $customer->save();
                                 $this->context->cart->id_customer = $customer->id;
                                 $this->context->cart->save();
                             }
                             $s_company_name = '';
                             if ((string) $physical_destination->getAddressLine3() != '') {
                                 $s_street = Tools::substr($physical_destination->getAddressLine3(), 0, Tools::strrpos($physical_destination->getAddressLine3(), ' '));
                                 $s_street_nr = Tools::substr($physical_destination->getAddressLine3(), Tools::strrpos($physical_destination->getAddressLine3(), ' ') + 1);
                                 $s_company_name = trim($physical_destination->getAddressLine1() . $physical_destination->getAddressLine2());
                             } else {
                                 if ((string) $physical_destination->getAddressLine2() != '') {
                                     $s_street = Tools::substr($physical_destination->getAddressLine2(), 0, Tools::strrpos($physical_destination->getAddressLine2(), ' '));
                                     $s_street_nr = Tools::substr($physical_destination->getAddressLine2(), Tools::strrpos($physical_destination->getAddressLine2(), ' ') + 1);
                                     $s_company_name = trim($physical_destination->getAddressLine1());
                                 } else {
                                     $s_street = Tools::substr($physical_destination->getAddressLine1(), 0, Tools::strrpos($physical_destination->getAddressLine1(), ' '));
                                     $s_street_nr = Tools::substr($physical_destination->getAddressLine1(), Tools::strrpos($physical_destination->getAddressLine1(), ' ') + 1);
                                 }
                             }
                             $phone = '';
                             if ((string) $physical_destination->getPhone() != '' && ValidateCore::isPhoneNumber((string) $physical_destination->getPhone())) {
                                 $phone = (string) $physical_destination->getPhone();
                             }
                             $address_delivery = AmazonPaymentsAddressHelper::findByAmazonOrderReferenceIdOrNew(Tools::getValue('amazonOrderReferenceId'));
                             $address_delivery->lastname = $names_array[1];
                             $address_delivery->firstname = $names_array[0];
                             if ($s_company_name != '') {
                                 $address_delivery->company = $s_company_name;
                             }
                             $address_delivery->address1 = (string) $s_street . ' ' . (string) $s_street_nr;
                             $address_delivery->postcode = (string) $physical_destination->getPostalCode();
                             $address_delivery->id_country = Country::getByIso((string) $physical_destination->getCountryCode());
                             if ($phone != '') {
                                 $address_delivery->phone = $phone;
                             }
                             if ($state != '') {
                                 $state_id = State::getIdByIso($state, Country::getByIso((string) $physical_destination->getCountryCode()));
                                 if (!$state_id) {
                                     $state_id = State::getIdByName($state);
                                 }
                                 if ($state_id) {
                                     $address_delivery->id_state = $state_id;
                                 }
                             }
                             $address_delivery->save();
                             AmazonPaymentsAddressHelper::saveAddressAmazonReference($address_delivery, Tools::getValue('amazonOrderReferenceId'));
                             $this->context->cart->id_address_delivery = $address_delivery->id;
                             $billing_address_object = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getBillingAddress();
                             if (method_exists($billing_address_object, 'getPhysicalAddress')) {
                                 $amz_billing_address = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getBillingAddress()->getPhysicalAddress();
                                 $iso_code = (string) $amz_billing_address->GetCountryCode();
                                 $city = (string) $amz_billing_address->GetCity();
                                 $postcode = (string) $amz_billing_address->GetPostalCode();
                                 $state = (string) $amz_billing_address->GetStateOrRegion();
                                 $invoice_names_array = explode(' ', (string) $amz_billing_address->getName(), 2);
                                 $regex = '/[^a-zA-ZäöüÄÖÜßÂâÀÁáàÇçÈÉËëéèÎîÏïÙÛùúòóûêôíÍŸÿªñÑ\\s]/u';
                                 $invoice_names_array[0] = preg_replace($regex, '', $invoice_names_array[0]);
                                 $invoice_names_array[1] = preg_replace($regex, '', $invoice_names_array[1]);
                                 $s_company_name = '';
                                 if ((string) $amz_billing_address->getAddressLine3() != '') {
                                     $s_street = Tools::substr($amz_billing_address->getAddressLine3(), 0, Tools::strrpos($amz_billing_address->getAddressLine3(), ' '));
                                     $s_street_nr = Tools::substr($amz_billing_address->getAddressLine3(), Tools::strrpos($amz_billing_address->getAddressLine3(), ' ') + 1);
                                     $s_company_name = trim($amz_billing_address->getAddressLine1() . $amz_billing_address->getAddressLine2());
                                 } else {
                                     if ((string) $amz_billing_address->getAddressLine2() != '') {
                                         $s_street = Tools::substr($amz_billing_address->getAddressLine2(), 0, Tools::strrpos($amz_billing_address->getAddressLine2(), ' '));
                                         $s_street_nr = Tools::substr($amz_billing_address->getAddressLine2(), Tools::strrpos($amz_billing_address->getAddressLine2(), ' ') + 1);
                                         $s_company_name = trim($amz_billing_address->getAddressLine1());
                                     } else {
                                         $s_street = Tools::substr($amz_billing_address->getAddressLine1(), 0, Tools::strrpos($amz_billing_address->getAddressLine1(), ' '));
                                         $s_street_nr = Tools::substr($amz_billing_address->getAddressLine1(), Tools::strrpos($amz_billing_address->getAddressLine1(), ' ') + 1);
                                     }
                                 }
                                 $phone = '';
                                 if ((string) $amz_billing_address->getPhone() != '' && ValidateCore::isPhoneNumber((string) $amz_billing_address->getPhone())) {
                                     $phone = (string) $amz_billing_address->getPhone();
                                 }
                                 $address_invoice = AmazonPaymentsAddressHelper::findByAmazonOrderReferenceIdOrNew(Tools::getValue('amazonOrderReferenceId') . '-inv');
                                 $address_invoice->alias = 'Amazon Payments Invoice';
                                 $address_invoice->lastname = $invoice_names_array[1];
                                 $address_invoice->firstname = $invoice_names_array[0];
                                 if ($s_company_name != '') {
                                     $address_invoice->company = $s_company_name;
                                 }
                                 $address_invoice->address1 = (string) $s_street . ' ' . (string) $s_street_nr;
                                 $address_invoice->postcode = (string) $amz_billing_address->getPostalCode();
                                 $address_invoice->city = $city;
                                 $address_invoice->id_country = Country::getByIso((string) $amz_billing_address->getCountryCode());
                                 if ($phone != '') {
                                     $address_invoice->phone = $phone;
                                 }
                                 if ($state != '') {
                                     $state_id = State::getIdByIso($state, Country::getByIso((string) $amz_billing_address->getCountryCode()));
                                     if (!$state_id) {
                                         $state_id = State::getIdByName($state);
                                     }
                                     if ($state_id) {
                                         $address_invoice->id_state = $state_id;
                                     }
                                 }
                                 $address_invoice->save();
                                 AmazonPaymentsAddressHelper::saveAddressAmazonReference($address_invoice, Tools::getValue('amazonOrderReferenceId') . '-inv');
                                 $this->context->cart->id_address_invoice = $address_invoice->id;
                             } else {
                                 $this->context->cart->id_address_invoice = $address_delivery->id;
                                 $address_invoice = $address_delivery;
                             }
                             $this->context->cart->save();
                             if (self::$amz_payments->authorization_mode == 'fast_auth') {
                                 $authorization_reference_id = Tools::getValue('amazonOrderReferenceId');
                                 if (isset($this->context->cookie->setHadErrorNowWallet) && $this->context->cookie->setHadErrorNowWallet == 1) {
                                     $confirm_order_ref_req_model = new OffAmazonPaymentsService_Model_ConfirmOrderReferenceRequest();
                                     $confirm_order_ref_req_model->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                     $confirm_order_ref_req_model->setSellerId(self::$amz_payments->merchant_id);
                                     try {
                                         $this->service->confirmOrderReference($confirm_order_ref_req_model);
                                     } catch (OffAmazonPaymentsService_Exception $e) {
                                         echo 'ERROR: ' . $e->getMessage();
                                     }
                                     unset($this->context->cookie->setHadErrorNowWallet);
                                 }
                                 $authorization_response_wrapper = AmazonTransactions::fastAuth(self::$amz_payments, $this->service, $authorization_reference_id, $total, $currency_code);
                                 if (is_object($authorization_response_wrapper)) {
                                     $details = $authorization_response_wrapper->getAuthorizeResult()->getAuthorizationDetails();
                                     $status = $details->getAuthorizationStatus()->getState();
                                     if ($status == 'Declined') {
                                         $reason = $details->getAuthorizationStatus()->getReasonCode();
                                         if ($reason == 'InvalidPaymentMethod') {
                                             $this->context->cookie->setHadErrorNowWallet = 1;
                                             die(Tools::jsonEncode(array('hasError' => true, 'errors' => array(Tools::displayError(self::$amz_payments->l('Your selected payment method is currently not available. Please select another one.'))))));
                                         } else {
                                             die(Tools::jsonEncode(array('hasError' => true, 'redirection' => 'index.php?controller=order', 'errors' => array(Tools::displayError(self::$amz_payments->l('Your selected payment method has been declined. Please chose another one.'))))));
                                         }
                                     }
                                     $amazon_authorization_id = $authorization_response_wrapper->getAuthorizeResult()->getAuthorizationDetails()->getAmazonAuthorizationId();
                                     /*
                                     if (self::$amz_payments->capture_mode == 'after_auth') {
                                         $amazon_capture_response = AmazonTransactions::capture(self::$amz_payments, $this->service, $amazon_authorization_id, $total, $currency_code);
                                         if (is_object($amazon_capture_response)) {
                                             $amazon_capture_id = $amazon_capture_response->getCaptureResult()
                                                 ->getCaptureDetails()
                                                 ->getAmazonCaptureId();
                                             $amazon_capture_reference_id = $amazon_capture_response->getCaptureResult()
                                                 ->getCaptureDetails()
                                                 ->getCaptureReferenceId();
                                         }
                                     }
                                     */
                                 }
                             }
                             if ($this->context->cart->secure_key == '') {
                                 $this->context->cart->secure_key = $customer->secure_key;
                                 $this->context->cart->save();
                             }
                             $new_order_status_id = (int) Configuration::get('PS_OS_PREPARATION');
                             if ((int) Configuration::get('AMZ_ORDER_STATUS_ID') > 0) {
                                 $new_order_status_id = Configuration::get('AMZ_ORDER_STATUS_ID');
                             }
                             $this->module->validateOrder((int) $this->context->cart->id, $new_order_status_id, $total, $this->module->displayName, null, array(), null, false, $customer->secure_key);
                             if (self::$amz_payments->authorization_mode == 'after_checkout') {
                                 $authorization_reference_id = Tools::getValue('amazonOrderReferenceId');
                                 $authorization_response_wrapper = AmazonTransactions::authorize(self::$amz_payments, $this->service, $authorization_reference_id, $total, $currency_code);
                                 $amazon_authorization_id = @$authorization_response_wrapper->getAuthorizeResult()->getAuthorizationDetails()->getAmazonAuthorizationId();
                                 /*
                                 if (self::$amz_payments->capture_mode == 'after_auth' && isset($amazon_authorization_id) && $amazon_authorization_id !== false && $amazon_authorization_id != null) {
                                     $amazon_capture_response = AmazonTransactions::capture(self::$amz_payments, $this->service, $amazon_authorization_id, $total, $currency_code);
                                     if (is_object($amazon_capture_response)) {
                                         $amazon_capture_id = $amazon_capture_response->getCaptureResult()
                                             ->getCaptureDetails()
                                             ->getAmazonCaptureId();
                                         $amazon_capture_reference_id = $amazon_capture_response->getCaptureResult()
                                             ->getCaptureDetails()
                                             ->getCaptureReferenceId();
                                     }
                                 }
                                 */
                             }
                             self::$amz_payments->setAmazonReferenceIdForOrderId(Tools::getValue('amazonOrderReferenceId'), $this->module->currentOrder);
                             self::$amz_payments->setAmazonReferenceIdForOrderTransactionId(Tools::getValue('amazonOrderReferenceId'), $this->module->currentOrder);
                             if (isset($authorization_reference_id)) {
                                 self::$amz_payments->setAmazonAuthorizationReferenceIdForOrderId($authorization_reference_id, $this->module->currentOrder);
                             }
                             if (isset($amazon_authorization_id)) {
                                 self::$amz_payments->setAmazonAuthorizationIdForOrderId($amazon_authorization_id, $this->module->currentOrder);
                             }
                             /*
                             if (isset($amazon_capture_reference_id)) {
                                 self::$amz_payments->setAmazonCaptureReferenceIdForOrderId($amazon_capture_reference_id, $this->module->currentOrder);
                             }
                             if (isset($amazon_capture_id)) {
                                 self::$amz_payments->setAmazonCaptureIdForOrderId($amazon_capture_id, $this->module->currentOrder);
                             }
                             */
                             if (isset($this->context->cookie->amzSetStatusAuthorized)) {
                                 $tmpOrderRefs = Tools::unSerialize($this->context->cookie->amzSetStatusAuthorized);
                                 if (is_array($tmpOrderRefs)) {
                                     foreach ($tmpOrderRefs as $order_ref) {
                                         AmazonTransactions::setOrderStatusAuthorized($order_ref);
                                     }
                                 }
                                 unset($this->context->cookie->amzSetStatusAuthorized);
                             }
                             if (isset($this->context->cookie->amzSetStatusCaptured)) {
                                 $tmpOrderRefs = Tools::unSerialize($this->context->cookie->amzSetStatusCaptured);
                                 if (is_array($tmpOrderRefs)) {
                                     foreach ($tmpOrderRefs as $order_ref) {
                                         AmazonTransactions::setOrderStatusCaptured($order_ref);
                                     }
                                 }
                                 unset($this->context->cookie->amzSetStatusCaptured);
                             }
                             if (Tools::getValue('connect_amz_account') == '1') {
                                 $this->context->cookie->amz_connect_order = $this->module->currentOrder;
                                 $this->context->cookie->amz_payments_address_id = $address_delivery->id;
                                 $this->context->cookie->amz_payments_invoice_address_id = $address_invoice->id;
                                 $login_redirect = $this->context->link->getModuleLink('amzpayments', 'process_login');
                                 $login_redirect = str_replace('http://', 'https://', $login_redirect);
                                 $login_redirect .= '?fromCheckout=1&access_token=' . $this->context->cookie->amz_access_token;
                                 die(Tools::jsonEncode(array('orderSucceed' => true, 'redirection' => $login_redirect)));
                             }
                             if (!$customer->is_guest) {
                                 if (!AmzPayments::addressAlreadyExists($address_delivery, $customer)) {
                                     $address_delivery->id_customer = $customer->id;
                                     $address_delivery->save();
                                 }
                                 if (!AmzPayments::addressAlreadyExists($address_invoice, $customer)) {
                                     $address_invoice->id_customer = $customer->id;
                                     $address_invoice->save();
                                 }
                             } else {
                                 if ($registered_customer = AmazonPaymentsCustomerHelper::findByEmailAddress($customer->email)) {
                                     if (!AmzPayments::addressAlreadyExists($address_delivery, $registered_customer)) {
                                         $address_delivery->id_customer = $registered_customer->id;
                                         $address_delivery->save();
                                     }
                                     if (!AmzPayments::addressAlreadyExists($address_invoice, $registered_customer)) {
                                         $address_invoice->id_customer = $registered_customer->id;
                                         $address_invoice->save();
                                     }
                                 }
                                 $this->context->cookie->show_success_amz_message = true;
                             }
                             die(Tools::jsonEncode(array('orderSucceed' => true, 'redirection' => __PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . (int) $this->context->cart->id . '&id_module=' . $this->module->id . '&id_order=' . $this->module->currentOrder . '&key=' . $customer->secure_key)));
                         }
                         die;
                     default:
                         throw new PrestaShopException('Unknown method "' . Tools::getValue('method') . '"');
                 }
             } else {
                 throw new PrestaShopException('Method is not defined');
             }
         }
     } elseif (Tools::isSubmit('ajax')) {
         throw new PrestaShopException('Method is not defined');
     }
 }
Ejemplo n.º 14
0
    public function getContent()
    {
        $buffer = '';
        if (version_compare(_PS_VERSION_, '1.5', '>')) {
            $this->context->controller->addJQueryPlugin('fancybox');
        } else {
            $buffer .= '<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/jquery/jquery.fancybox-1.3.4.js"></script>
		  	<link type="text/css" rel="stylesheet" href="' . __PS_BASE_URI__ . 'css/jquery.fancybox-1.3.4.css" />';
        }
        if (Tools::isSubmit('SubmitAvalaraTaxSettings')) {
            Configuration::updateValue('AVALARATAX_ACCOUNT_NUMBER', Tools::getValue('avalaratax_account_number'));
            Configuration::updateValue('AVALARATAX_LICENSE_KEY', Tools::getValue('avalaratax_license_key'));
            Configuration::updateValue('AVALARATAX_URL', Tools::getValue('avalaratax_url'));
            Configuration::updateValue('AVALARATAX_COMPANY_CODE', Tools::getValue('avalaratax_company_code'));
            $buffer .= $this->_displayConfirmation();
        } elseif (Tools::isSubmit('SubmitAvalaraTaxOptions')) {
            Configuration::updateValue('AVALARATAX_ADDRESS_VALIDATION', Tools::getValue('avalaratax_address_validation'));
            Configuration::updateValue('AVALARATAX_TAX_CALCULATION', Tools::getValue('avalaratax_tax_calculation'));
            Configuration::updateValue('AVALARATAX_TIMEOUT', (int) Tools::getValue('avalaratax_timeout'));
            Configuration::updateValue('AVALARATAX_ADDRESS_NORMALIZATION', Tools::getValue('avalaratax_address_normalization'));
            Configuration::updateValue('AVALARATAX_TAX_OUTSIDE', Tools::getValue('avalaratax_tax_outside'));
            Configuration::updateValue('AVALARA_CACHE_MAX_LIMIT', Tools::getValue('avalara_cache_max_limit') < 1 ? 1 : Tools::getValue('avalara_cache_max_limit') > 23 ? 23 : Tools::getValue('avalara_cache_max_limit'));
            $buffer .= $this->_displayConfirmation();
        } elseif (Tools::isSubmit('SubmitAvalaraTestConnection')) {
            $connectionTestResult = $this->_testConnection();
        } elseif (Tools::isSubmit('SubmitAvalaraAddressOptions')) {
            /* Validate address*/
            $address = new Address();
            $address->address1 = Tools::getValue('avalaratax_address_line1');
            $address->address2 = Tools::getValue('avalaratax_address_line2');
            $address->city = Tools::getValue('avalaratax_city');
            $address->id_state = State::getIdByIso(Tools::getValue('avalaratax_state'));
            $address->id_country = Tools::getValue('avalaratax_country');
            $address->postcode = Tools::getValue('avalaratax_zip_code');
            $normalizedAddress = $this->validateAddress($address);
            if (isset($normalizedAddress['ResultCode']) && $normalizedAddress['ResultCode'] == 'Success') {
                $buffer .= $this->_displayConfirmation($this->l('The address you submitted has been validated.'));
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE1', $normalizedAddress['Normalized']['Line1']);
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE2', $normalizedAddress['Normalized']['Line2']);
                Configuration::updateValue('AVALARATAX_CITY', $normalizedAddress['Normalized']['City']);
                Configuration::updateValue('AVALARATAX_STATE', $normalizedAddress['Normalized']['Region']);
                Configuration::updateValue('AVALARATAX_COUNTRY', $normalizedAddress['Normalized']['Country']);
                Configuration::updateValue('AVALARATAX_ZIP_CODE', $normalizedAddress['Normalized']['PostalCode']);
            } else {
                $message = $this->l('The following error was generated while validating your address:');
                if (isset($normalizedAddress['Exception']['FaultString'])) {
                    $message .= '<br /> - ' . Tools::safeOutput($normalizedAddress['Exception']['FaultString']);
                }
                if (isset($normalizedAddress['Messages']['Summary'])) {
                    foreach ($normalizedAddress['Messages']['Summary'] as $summary) {
                        $message .= '<br /> - ' . Tools::safeOutput($summary);
                    }
                }
                $buffer .= $this->_displayConfirmation($message, 'error');
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE1', Tools::getValue('avalaratax_address_line1'));
                Configuration::updateValue('AVALARATAX_ADDRESS_LINE2', Tools::getValue('avalaratax_address_line2'));
                Configuration::updateValue('AVALARATAX_CITY', Tools::getValue('avalaratax_city'));
                Configuration::updateValue('AVALARATAX_STATE', Tools::getValue('avalaratax_state'));
                Configuration::updateValue('AVALARATAX_ZIP_CODE', Tools::getValue('avalaratax_zip_code'));
            }
        } elseif (Tools::isSubmit('SubmitAvalaraTaxClearCache')) {
            Db::getInstance()->Execute('TRUNCATE TABLE `' . _DB_PREFIX_ . 'avalara_product_cache`');
            Db::getInstance()->Execute('TRUNCATE TABLE `' . _DB_PREFIX_ . 'avalara_carrier_cache`');
            $buffer .= $this->_displayConfirmation('Cache cleared!');
        }
        $confValues = Configuration::getMultiple(array('AVALARATAX_ACCOUNT_NUMBER', 'AVALARATAX_LICENSE_KEY', 'AVALARATAX_URL', 'AVALARATAX_COMPANY_CODE', 'AVALARATAX_ADDRESS_VALIDATION', 'AVALARATAX_TAX_CALCULATION', 'AVALARATAX_TIMEOUT', 'AVALARATAX_ADDRESS_NORMALIZATION', 'AVALARATAX_TAX_OUTSIDE', 'AVALARATAX_COMMIT_ID', 'AVALARATAX_CANCEL_ID', 'AVALARATAX_REFUND_ID', 'AVALARATAX_POST_ID', 'AVALARA_CACHE_MAX_LIMIT', 'AVALARATAX_ADDRESS_LINE1', 'AVALARATAX_ADDRESS_LINE2', 'AVALARATAX_CITY', 'AVALARATAX_STATE', 'AVALARATAX_ZIP_CODE', 'AVALARATAX_COUNTRY'));
        $stateList = array();
        $stateList[] = array('id' => '0', 'name' => $this->l('Choose your state (if applicable)'), 'iso_code' => '--');
        foreach (State::getStates((int) $this->context->cookie->id_lang) as $state) {
            $stateList[] = array('id' => $state['id_state'], 'name' => $state['name'], 'iso_code' => $state['iso_code']);
        }
        $countryList = array();
        $countryList[] = array('id' => '0', 'name' => $this->l('Choose your country'), 'iso_code' => '--');
        foreach (Country::getCountries((int) $this->context->cookie->id_lang, false, null, false) as $country) {
            $countryList[] = array('id' => $country['id_country'], 'name' => $country['name'], 'iso_code' => $country['iso_code']);
        }
        $buffer .= '<link href="' . $this->_path . 'css/avalara.css" rel="stylesheet" type="text/css">
		<script type="text/javascript">
			/* Fancybox */
			$(\'a.avalara-video-btn\').live(\'click\', function(){
			    $.fancybox({
			        \'type\' : \'iframe\',
			        \'href\' : this.href.replace(new RegExp("watch\\?v=", "i"), \'embed\') + \'?rel=0&autoplay=1\',
			        \'swf\': {\'allowfullscreen\':\'true\', \'wmode\':\'transparent\'},
			        \'overlayShow\' : true,
			        \'centerOnScroll\' : true,
			        \'speedIn\' : 100,
			        \'speedOut\' : 50,
			        \'width\' : 853,
			        \'height\' : 480
			    });
			    return false;
			});
		</script>
		<script type="text/javascript">
			$(document).ready(function(){
			    var height1 = 0;
			    var height = 0;
			     $(\'.field-height1\').each(function(){
				if (height1 < $(this).height())
				    height1 = $(this).height();
			    });
			    
			    $(\'.field-height\').each(function(){
				if (height < $(this).height())
				    height = $(this).height();
			    });
			
				$(\'.field-height1\').css({\'height\' : $(\'.field-height1\').css(\'height\', height1+\'px\')});
			    $(\'.field-height\').css({\'height\' : $(\'.field-height\').css(\'height\', height+\'px\')});

updateAvalaraTaxState($(\'#avalaratax_country\').val());

    $(\'#avalaratax_country\').change(function(){
updateAvalaraTaxState($(this).val());
    });


			});
function updateAvalaraTaxState(iso_code)
{

var default_state = "' . $confValues['AVALARATAX_STATE'] . '";

$(\'#avalaratax_state\').html(\'\');
	$.ajax({
	    type : \'GET\',
	    url : \'../modules/avalaratax/states.php?country_iso_code=\'+iso_code,
	    dataType: \'JSON\',
	    success: function(data)
	    {
		if (data != 0)
		{
		    $.each(data[iso_code], function(i, item){
if (default_state == item.state_iso_code)
			$(\'#avalaratax_state\').append(\'<option  selected="selected" value="\'+item.state_iso_code+\'">\'+item.name+\'</option>\');
else
			$(\'#avalaratax_state\').append(\'<option  value="\'+item.state_iso_code+\'">\'+item.name+\'</option>\');
			$(\'#avalaratax_state\').show();
			$(\'#avalaratax_label_state\').show();
		    });
		}
		else
		{
		    $(\'#avalaratax_state\').hide();
		    $(\'#avalaratax_label_state\').hide();
		}
	    }
	});

}

		</script>
		<div class="avalara-wrap">
			<p class="avalara-intro"><a href="http://www.avalara.com/e-commerce/prestashop" class="avalara-logo" target="_blank"><img src="' . $this->_path . 'img/avalara_logo.png" alt="Avalara" border="0" /></a><a href="http://www.avalara.com/e-commerce/prestashop" class="avalara-link" target="_blank">' . $this->l('Create an account') . '</a>' . $this->l('Avalara and PrestaShop have partnered to provide the easiest way for you to accurately calculate and fill sales tax.') . '</p>
			<div class="clear"></div>
			<div class="avalara-content">
				<div class="avalara-video">
					<h3>' . $this->l('No one likes dealing with sales tax.') . '</h3>
					<p>' . $this->l('Sales tax isn\'t core to your business and should be automated. You may be doing it wrong, exposing your business to unnecessary audit risks, and don\'t even know it.') . '</p>
					<a href="http://www.youtube.com/embed/tm1tENVdcQ8" class="avalara-video-btn"><img src="' . $this->_path . 'img/avalara-video-screen.jpg" alt="Avalara Video" /><img src="' . $this->_path . 'img/btn-video.png" alt="" class="video-icon" /></a>
				</div>
				<h3>' . $this->l('Doing sales tax right is simple with Avalara.') . '</h3>
				<p>' . $this->l('We do all of the research and automate the process for you, ensuring that the system is up-to-date with the most recent sales tax and VAT rates and rules in every state and country, so you don’t have to.  As a cloud-based service, AvaTax eliminates ongoing maintenance and support.  It provides you with a complete solution to manage your sales tax needs.') . '</p>
				<img src="' . $this->_path . 'img/avatax_badge.png" alt="AvaTax Certified" class="avatax-badge" />
				<ul>
					<li>' . $this->l('Address Validation included') . '</li>
					<li>' . $this->l('Rooftop Accurate Calculations') . '</li>
					<li>' . $this->l('Product and Service Taxability Rules') . '</li>
					<li>' . $this->l('Exemption Certificate Management') . '</li>
					<li>' . $this->l('Out-of-the-Box Sales Tax Reporting') . '</li>
				</ul>
				<a href="http://www.avalara.com/e-commerce/prestashop" class="avalara-link" target="_blank">' . $this->l('Create an account') . '</a>
			</div>
			<fieldset class="field-height1 right-fieldset">
			<legend><img src="' . $this->_path . 'img/icon-console.gif" alt="" />' . $this->l('AvaTax Admin Console') . '</legend>
				<p><a href="https://admin-avatax.avalara.net/" target="_blank">' . $this->l('Log-in to AvaTax Admin Console') . '</a></p>
				<a href="https://admin-avatax.avalara.net/" target="_blank"><img src="' . $this->_path . 'img/avatax-logo.png" alt="AvaTax" class="avatax-logo" /></a>
			</fieldset>
			<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '" method="post" class="left-form">
				<fieldset class="field-height1">
					<legend><img src="' . $this->_path . 'img/icon-config.gif" alt="" />' . $this->l('Configuration') . '</legend>
					<h4>' . $this->l('AvaTax Credentials') . '</h4>';
        if (isset($connectionTestResult)) {
            $buffer .= '<div id="test_connection" style="background: ' . Tools::safeOutput($connectionTestResult[1]) . ';">' . $connectionTestResult[0] . '</div>';
        }
        $buffer .= '<label>' . $this->l('Account Number') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_account_number" value="' . (isset($confValues['AVALARATAX_ACCOUNT_NUMBER']) ? Tools::safeOutput($confValues['AVALARATAX_ACCOUNT_NUMBER']) : '') . '" />
					</div>
					<label>' . $this->l('License Key') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_license_key" value="' . (isset($confValues['AVALARATAX_LICENSE_KEY']) ? Tools::safeOutput($confValues['AVALARATAX_LICENSE_KEY']) : '') . '" />
					</div>
					<label>' . $this->l('URL') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_url" value="' . (isset($confValues['AVALARATAX_URL']) ? Tools::safeOutput($confValues['AVALARATAX_URL']) : '') . '" />
					</div>
					<label>' . $this->l('Company Code') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_company_code" value="' . (isset($confValues['AVALARATAX_COMPANY_CODE']) ? Tools::safeOutput($confValues['AVALARATAX_COMPANY_CODE']) : '') . '" /> ' . $this->l('Located in the top-right corner of your AvaTax Admin Console') . '
					</div>
					<div class="margin-form">
						<input type="submit" class="button" name="SubmitAvalaraTaxSettings" value="' . $this->l('Save Settings') . '" /><img src="' . $this->_path . 'img/icon-connection.gif" alt="" class="icon-connection" /><input type="submit" id="avalaratax_test_connection" class="button" name="SubmitAvalaraTestConnection" value="' . $this->l('Click here to Test Connection') . '" />
					</div>
				</fieldset>
			</form>
			<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '" method="post" class="form-half reset-label">
				<fieldset class="field-height MR7">
					<legend><img src="' . $this->_path . 'img/icon-options.gif" alt="" />' . $this->l('Options') . '</legend>
					<label>' . $this->l('Enable address validation') . '</label>
					<div class="margin-form">
						<input type="checkbox" name="avalaratax_address_validation" value="1"' . (isset($confValues['AVALARATAX_ADDRESS_VALIDATION']) && $confValues['AVALARATAX_ADDRESS_VALIDATION'] ? ' checked="checked"' : '') . ' />
						(' . $this->l('Not compatible with One Page Checkout') . ')
					</div>
					<label>' . $this->l('Enable tax calculation') . '</label>
					<div class="margin-form">
						<input type="checkbox" name="avalaratax_tax_calculation" value="1" ' . (isset($confValues['AVALARATAX_TAX_CALCULATION']) && $confValues['AVALARATAX_TAX_CALCULATION'] ? ' checked="checked"' : '') . ' />
					</div>
					<label>' . $this->l('Enable address normalization in uppercase') . '</label>
					<div class="margin-form">
						<input type="checkbox" name="avalaratax_address_normalization" value="1" ' . (isset($confValues['AVALARATAX_ADDRESS_NORMALIZATION']) && $confValues['AVALARATAX_ADDRESS_NORMALIZATION'] ? ' checked="checked"' : '') . ' />
					</div>
					<label>' . $this->l('Enable tax calculation outside of your state') . '</label>
					<div class="margin-form">
						<input type="checkbox" name="avalaratax_tax_outside" value="1" ' . (isset($confValues['AVALARATAX_TAX_OUTSIDE']) && $confValues['AVALARATAX_TAX_OUTSIDE'] ? ' checked="checked"' : '') . ' />
					</div>
					<label>' . $this->l('Request timeout') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_timeout" value="' . (isset($confValues['AVALARATAX_TIMEOUT']) ? Tools::safeOutput($confValues['AVALARATAX_TIMEOUT']) : '') . '" style="width: 40px;" /> ' . $this->l('seconds') . '
					</div>
					<div style="display: none;"
						<label>' . $this->l('Refresh tax rate cache every: ') . '</label>
						<div class="margin-form">
							<input type="text" name="avalara_cache_max_limit" value="' . (isset($confValues['AVALARA_CACHE_MAX_LIMIT']) ? Tools::safeOutput($confValues['AVALARA_CACHE_MAX_LIMIT']) : '') . '" style="width: 40px;" /> ' . $this->l('minutes') . '
						</div>
					</div>
					<div class="margin-form">
						<input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxOptions" value="' . $this->l('Save Settings') . '" />
						<input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxClearCache" value="' . $this->l('Clear Cache') . '" style="display: none;"/>
					</div>
					<div class="sep"></div>
					<h4>' . $this->l('Default Post/Commit/Cancel/Refund Options') . '</h4>
					<span class="avalara-info">' . $this->l('When an order\'s status is updated, the following options will be used to update Avalara\'s records.') . '</span>';
        // Check if the order status exist
        $orderStatusList = array();
        foreach (Db::getInstance()->ExecuteS('SELECT `id_order_state`, `name` FROM `' . _DB_PREFIX_ . 'order_state_lang` WHERE `id_lang` = ' . (int) $this->context->cookie->id_lang) as $v) {
            $orderStatusList[$v['id_order_state']] = Tools::safeOutput($v['name']);
        }
        $buffer .= '<table class="avalara-table" cellspacing="0" cellpadding="0" width="100%">
						<th>' . $this->l('Action') . '</th>
						<th>' . $this->l('Order status in your store') . '</th>
						<tr>
							<td class="avalaratax_column">' . $this->l('Post order to Avalara') . ':</td>
							<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_POST_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_POST_ID')])) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
							</td>
						</tr>
						<tr>
							<td class="avalaratax_column">' . $this->l('Commit order to Avalara') . ':</td>
							<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_COMMIT_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_COMMIT_ID')])) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
							</td>
						</tr>
						<tr>
							<td class="avalaratax_column">' . $this->l('Delete order from Avalara') . ':</td>
							<td>' . (isset($orderStatusList[Configuration::get('AVALARATAX_CANCEL_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_CANCEL_ID')])) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
							</td>
						</tr>
						<tr>
							<td class="avalaratax_column last">' . $this->l('Void order in Avalara') . ':</td>
							<td class="last">' . (isset($orderStatusList[Configuration::get('AVALARATAX_REFUND_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_REFUND_ID')])) : '<div style="color: red">' . $this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.') . '</div>') . '
							</td>
						</tr>
					</table>
				</fieldset>
			</form>
			<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '" method="post" class="form-half">
				<fieldset class="field-height ML7">
					<legend><img src="' . $this->_path . 'img/icon-address.gif" alt="" />' . $this->l('Default Origin Address') . '</legend>
					<label>' . $this->l('Address Line 1') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_address_line1" value="' . (isset($confValues['AVALARATAX_ADDRESS_LINE1']) ? Tools::safeOutput($confValues['AVALARATAX_ADDRESS_LINE1']) : '') . '" />
					</div>
					<label>' . $this->l('Address Line 2') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_address_line2" value="' . (isset($confValues['AVALARATAX_ADDRESS_LINE2']) ? Tools::safeOutput($confValues['AVALARATAX_ADDRESS_LINE2']) : '') . '" />
					</div>
					<label>' . $this->l('City') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_city" value="' . (isset($confValues['AVALARATAX_CITY']) ? Tools::safeOutput($confValues['AVALARATAX_CITY']) : '') . '" />
					</div>
					<label>' . $this->l('Zip Code') . '</label>
					<div class="margin-form">
						<input type="text" name="avalaratax_zip_code" value="' . (isset($confValues['AVALARATAX_ZIP_CODE']) ? Tools::safeOutput($confValues['AVALARATAX_ZIP_CODE']) : '') . '" />
					</div>
					<label>' . $this->l('Country') . '</label>
					<div class="margin-form">
						<select name="avalaratax_country" id="avalaratax_country">';
        foreach ($countryList as $country) {
            $buffer .= '<option value="' . substr(strtoupper($country['iso_code']), 0, 2) . '" ' . ($country['iso_code'] == $confValues['AVALARATAX_COUNTRY'] ? ' selected="selected"' : '') . '>' . Tools::safeOutput($country['name']) . '</option>';
        }
        $buffer .= '</select>
					</div>
					<label id="avalaratax_label_state" >' . $this->l('State') . '</label>
					<div class="margin-form">
						<select name="avalaratax_state" id="avalaratax_state">';
        foreach ($stateList as $state) {
            $buffer .= '<option value="' . substr(strtoupper($state['iso_code']), 0, 2) . '" ' . ($state['iso_code'] == $confValues['AVALARATAX_STATE'] ? ' selected="selected"' : '') . '>' . Tools::safeOutput($state['name']) . '</option>';
        }
        return $buffer . '</select>
					</div>
					<div class="margin-form">
						<input type="submit" class="button" name="SubmitAvalaraAddressOptions" value="' . $this->l('Save Settings') . '" />
					</div>
				</fieldset>
			</form>
			<div class="clear"></div>
		</div>';
    }
Ejemplo n.º 15
0
 protected function _installTaxes($xml)
 {
     if (isset($xml->taxes->tax)) {
         $available_behavior = array(PS_PRODUCT_TAX, PS_STATE_TAX, PS_BOTH_TAX);
         $assoc_taxes = array();
         foreach ($xml->taxes->tax as $taxData) {
             $attributes = $taxData->attributes();
             if (Tax::getTaxIdByName($attributes['name'])) {
                 continue;
             }
             $tax = new Tax();
             $tax->name[(int) Configuration::get('PS_LANG_DEFAULT')] = strval($attributes['name']);
             $tax->rate = (double) $attributes['rate'];
             $tax->active = 1;
             if (!$tax->validateFields()) {
                 $this->_errors[] = Tools::displayError('Invalid tax properties.');
                 return false;
             }
             if (!$tax->add()) {
                 $this->_errors[] = Tools::displayError('An error occurred while importing the tax: ') . strval($attributes['name']);
                 return false;
             }
             $assoc_taxes[(int) $attributes['id']] = $tax->id;
         }
         foreach ($xml->taxes->taxRulesGroup as $group) {
             $group_attributes = $group->attributes();
             if (!Validate::isGenericName($group_attributes['name'])) {
                 continue;
             }
             if (TaxRulesGroup::getIdByName($group['name'])) {
                 continue;
             }
             $trg = new TaxRulesGroup();
             $trg->name = $group['name'];
             $trg->active = 1;
             if (!$trg->save()) {
                 $this->_errors = Tools::displayError('This tax rule cannot be saved.');
                 return false;
             }
             foreach ($group->taxRule as $rule) {
                 $rule_attributes = $rule->attributes();
                 // Validation
                 if (!isset($rule_attributes['iso_code_country'])) {
                     continue;
                 }
                 $id_country = Country::getByIso(strtoupper($rule_attributes['iso_code_country']));
                 if (!$id_country) {
                     continue;
                 }
                 if (!isset($rule_attributes['id_tax']) || !array_key_exists(strval($rule_attributes['id_tax']), $assoc_taxes)) {
                     continue;
                 }
                 // Default values
                 $id_state = (int) isset($rule_attributes['iso_code_state']) ? State::getIdByIso(strtoupper($rule_attributes['iso_code_state'])) : 0;
                 $id_county = 0;
                 $state_behavior = 0;
                 $county_behavior = 0;
                 if ($id_state) {
                     if (isset($rule_attributes['state_behavior']) && in_array($rule_attributes['state_behavior'], $available_behavior)) {
                         $state_behavior = (int) $rule_attributes['state_behavior'];
                     }
                     if (isset($rule_attributes['county_name'])) {
                         $id_county = County::getIdCountyByNameAndIdState($rule_attributes['county_name'], (int) $id_state);
                         if (!$id_county) {
                             continue;
                         }
                     }
                     if (isset($rule_attributes['county_behavior']) && in_array($rule_attributes['state_behavior'], $available_behavior)) {
                         $county_behavior = (int) $rule_attributes['county_behavior'];
                     }
                 }
                 // Creation
                 $tr = new TaxRule();
                 $tr->id_tax_rules_group = $trg->id;
                 $tr->id_country = $id_country;
                 $tr->id_state = $id_state;
                 $tr->id_county = $id_county;
                 $tr->state_behavior = $state_behavior;
                 $tr->county_behavior = $county_behavior;
                 $tr->id_tax = $assoc_taxes[strval($rule_attributes['id_tax'])];
                 $tr->save();
             }
         }
     }
     return true;
 }
 public static function getStateId()
 {
     return State::getIdByIso(self::shippingAddressFormat()['isoStateCode']);
 }
Ejemplo n.º 17
0
 /**
  * @param SimpleXMLElement $xml
  * @return bool
  * @throws PrestaShopException
  */
 protected function _installTaxes($xml)
 {
     if (isset($xml->taxes->tax)) {
         $assoc_taxes = array();
         foreach ($xml->taxes->tax as $taxData) {
             /** @var SimpleXMLElement $taxData */
             $attributes = $taxData->attributes();
             if ($id_tax = Tax::getTaxIdByName($attributes['name'])) {
                 $assoc_taxes[(int) $attributes['id']] = $id_tax;
                 continue;
             }
             $tax = new Tax();
             $tax->name[(int) Configuration::get('PS_LANG_DEFAULT')] = (string) $attributes['name'];
             $tax->rate = (double) $attributes['rate'];
             $tax->active = 1;
             if (($error = $tax->validateFields(false, true)) !== true || ($error = $tax->validateFieldsLang(false, true)) !== true) {
                 $this->_errors[] = Tools::displayError('Invalid tax properties.') . ' ' . $error;
                 return false;
             }
             if (!$tax->add()) {
                 $this->_errors[] = Tools::displayError('An error occurred while importing the tax: ') . (string) $attributes['name'];
                 return false;
             }
             $assoc_taxes[(int) $attributes['id']] = $tax->id;
         }
         foreach ($xml->taxes->taxRulesGroup as $group) {
             /** @var SimpleXMLElement $group */
             $group_attributes = $group->attributes();
             if (!Validate::isGenericName($group_attributes['name'])) {
                 continue;
             }
             if (TaxRulesGroup::getIdByName($group['name'])) {
                 continue;
             }
             $trg = new TaxRulesGroup();
             $trg->name = $group['name'];
             $trg->active = 1;
             if (!$trg->save()) {
                 $this->_errors[] = Tools::displayError('This tax rule cannot be saved.');
                 return false;
             }
             foreach ($group->taxRule as $rule) {
                 /** @var SimpleXMLElement $rule */
                 $rule_attributes = $rule->attributes();
                 // Validation
                 if (!isset($rule_attributes['iso_code_country'])) {
                     continue;
                 }
                 $id_country = (int) Country::getByIso(strtoupper($rule_attributes['iso_code_country']));
                 if (!$id_country) {
                     continue;
                 }
                 if (!isset($rule_attributes['id_tax']) || !array_key_exists(strval($rule_attributes['id_tax']), $assoc_taxes)) {
                     continue;
                 }
                 // Default values
                 $id_state = (int) isset($rule_attributes['iso_code_state']) ? State::getIdByIso(strtoupper($rule_attributes['iso_code_state'])) : 0;
                 $id_county = 0;
                 $zipcode_from = 0;
                 $zipcode_to = 0;
                 $behavior = $rule_attributes['behavior'];
                 if (isset($rule_attributes['zipcode_from'])) {
                     $zipcode_from = $rule_attributes['zipcode_from'];
                     if (isset($rule_attributes['zipcode_to'])) {
                         $zipcode_to = $rule_attributes['zipcode_to'];
                     }
                 }
                 // Creation
                 $tr = new TaxRule();
                 $tr->id_tax_rules_group = $trg->id;
                 $tr->id_country = $id_country;
                 $tr->id_state = $id_state;
                 $tr->id_county = $id_county;
                 $tr->zipcode_from = $zipcode_from;
                 $tr->zipcode_to = $zipcode_to;
                 $tr->behavior = $behavior;
                 $tr->description = '';
                 $tr->id_tax = $assoc_taxes[strval($rule_attributes['id_tax'])];
                 $tr->save();
             }
         }
     }
     return true;
 }
Ejemplo n.º 18
0
        $label_format = $dhl->_dhl_label_format;
        $ShipmentReference = isset($data['ShipmentReference']) ? $data['ShipmentReference'] : '';
    } else {
        $tracking_id_type = NULL;
        $shop_name = Configuration::get('DHL_SHIPPER_SHOP_NAME') ? trim(Configuration::get('DHL_SHIPPER_SHOP_NAME')) : trim(Configuration::get('PS_SHOP_NAME'));
        $attention_name = trim(Configuration::get('DHL_SHIPPER_ATTENTION_NAME'));
        $phone_number = Configuration::get('DHL_SHIPPER_PHONE') ? trim(Configuration::get('DHL_SHIPPER_PHONE')) : trim(Configuration::get('PS_SHOP_PHONE'));
        $address1 = Configuration::get('DHL_SHIPPER_ADDR1') ? trim(Configuration::get('DHL_SHIPPER_ADDR1')) : trim(Configuration::get('PS_SHOP_ADDR1'));
        $address2 = Configuration::get('DHL_SHIPPER_ADDR2') ? trim(Configuration::get('DHL_SHIPPER_ADDR2')) : trim(Configuration::get('PS_SHOP_ADDR2'));
        $shop_city = Configuration::get('DHL_SHIPPER_CITY') ? trim(Configuration::get('DHL_SHIPPER_CITY')) : trim(Configuration::get('PS_SHOP_CITY'));
        $countries = Country::getCountries($cookie->id_lang, true);
        $states = array();
        $shop_country = Configuration::get('DHL_SHIPPER_COUNTRY') ? trim(Configuration::get('DHL_SHIPPER_COUNTRY')) : trim(Configuration::get('DHL_ORIGIN_COUNTRY'));
        $shop_country = Country::getByIso($shop_country);
        $shop_state = Configuration::get('DHL_SHIPPER_STATE') ? trim(Configuration::get('DHL_SHIPPER_STATE')) : trim(Configuration::get('DHL_ORIGIN_STATE'));
        $shop_state = State::getIdByIso($shop_state);
        $states = isset($countries[$shop_country]['states']) ? $countries[$shop_country]['states'] : array();
        $shop_postal = Configuration::get('DHL_SHIPPER_POSTCODE') ? trim(Configuration::get('DHL_SHIPPER_POSTCODE')) : trim(Configuration::get('PS_SHOP_CODE'));
        $address = new Address($order->id_address_delivery);
        $shipto_company = $address->company;
        $shipto_attention_name = $address->firstname . ' ' . $address->lastname;
        $shipto_phone = $address->phone ? $address->phone : $address->phone_mobile;
        $shipto_address1 = $address->address1;
        $shipto_address2 = $address->address2;
        $shipto_city = $address->city;
        $shipto_postcode = $address->postcode;
        $shipto_country = $address->id_country;
        $shipto_state = $address->id_state;
        $shipto_states = isset($countries[$shipto_country]['states']) ? $countries[$shipto_country]['states'] : array();
        $shipping_method = Db::getInstance()->executeS('
			SELECT `method`