LogoLogo
Homepage
  • Documentations for PrestaShop 1.4
  • English documentation 1.4
    • Getting Started
    • Updating PrestaShop
    • User Guide
      • Training
      • Customizing your shop
      • Browsing the front-office
      • Connecting to the PrestaShop back-office
      • Adding Products and Product Categories
      • A Look inside the Catalog
      • Managing Customers
      • Managing Orders
      • Managing Payment Methods
      • Managing Shipping
      • Understanding Statistics
      • Managing Modules
      • Managing Employees
      • Understanding the Preferences
      • Exploring PrestaShop's Tools
      • PrestaShop Support
    • System Administrator Guide
    • Developer Guide
      • Developer tutorials
        • Using the REST webservice
          • Chapter 1 - Creating Access to Back Office
          • Chapter 2 - Discovery - Testing access to the web service with the browser
          • Chapter 3 - First steps - Access the Web service and list client
            • 3.1 - Access the web service
            • 3.2 - Handling errors
            • 3.3 - List clients
          • Chapter 4 - Retrieve Data - Retrieving a Client
          • Chapter 5 - Modification - Update client
          • Chapter 6 - Creation - Remote Online Form
          • Chapter 7 - Removal - Remove customer accounts from the database
          • Chapter 8 - Advanced Use
          • Cheat-sheet - Concepts outlined in this tutorial
        • Understanding and using hooks
        • Synchronization via Hooks
        • Modules, Classes and Controller Override
        • Modules, Override, Web Service
        • Db class good practices for Prestashop 1.4
        • Carrier modules - functions, creation and configuration
        • Creating your own payment module
        • Accelerated Security Course - Episode 1 - Never Trust Foreign Data
        • Accelerated Security Course - Episode 2 - SQL Injections
        • Accelerated Security Course - Episode 3 - XSS
        • Accelerated Security Course - Episode 4 - CSRF
      • Fundamentals
      • Creating a PrestaShop module
      • Development standard
      • Public and overloadable methods
      • Web-service reference
      • How to use the forge to contribute to PrestaShop
      • Rocky's guides
        • PrestaShop 1.4.3 Development Guide
          • Architecture
          • Overriding Files
          • Creating Modules
          • Cookie Structure
          • Database Structure
        • PrestaShop 1.4.3 Performance Guide
    • Designer Guide
      • Coding a theme
      • Design tips
      • Implementing layered navigation in a theme
    • Troubleshooting
    • FAQ
    • User contributions
    • Documentation PDFs
  • Documentation française 1.4
    • Guide de démarrage
    • Mettre à jour PrestaShop
    • Guide de l'utilisateur
      • Formation
      • Personnaliser votre boutique
      • Se connecter au back-office de Prestashop
      • Ajouter des produits et des catégories de produits
      • Un aperçu du catalogue
      • Gérer les clients
      • Gérer les commandes
      • Gérer les méthodes de paiement
      • Gérer le transport
      • Comprendre les statistiques
      • Gérer les modules
      • Gérer les employés
      • Comprendre les préférences
      • Explorer les outils de PrestaShop
      • Obtenir de l'aide
    • Guide de l'administrateur système
    • Guide du développeur
      • Fondamentaux
      • Créer un module PrestaShop
      • Tutoriels pour développeurs
        • Tutoriel Webservice REST
          • Chapitre 1 - Mise en place - Création des accès dans le Back Office
          • Chapitre 2 - Découverte - Tester l'accès au service web avec le navigateur
          • Chapitre 3 - Premiers pas - Accéder au service web et lister les clients
            • 3.1 Accéder au service web
            • 3.2 Gestion des erreurs
            • 3.3 Lister les clients
          • Chapitre 4 - Récuperer des données : Récupérer un client
          • Chapitre 5 - Modification : Mettre à jour un client
          • Chapitre 6 - Création : Formulaire d'ajout à distance
          • Chapitre 7 - Suppression : Retirer des comptes client de la base
          • Chapitre 8 – Utilisation avancée
          • Chapitre 9 - Gestion des images
          • Chapitre 10 - Gestion des prix
          • Mémento : Notions énoncées dans ce tutoriel
        • Mieux comprendre et utiliser les hooks
        • La synchronisation via les Hooks
        • Surcharge et override
        • Modules, surcharge, web service
        • Les bonnes pratiques de la classe Db sur Prestashop 1.4
        • Les modules transporteurs - fonctionnement, création, configuration
        • Cours de sécurité accéléré no. 1 - Never trust foreign data
        • Cours de sécurité accéléré no. 2 - Injections SQL
        • Cours de sécurité accéléré no. 3 - XSS
        • Cours de Sécurité accéléré no. 4 - CSRF
    • Guide du designer
      • Conseils en design
      • Créer un thème
    • Guide du Vendeur
    • Import Wiki FR
      • Dépannage
        • Changer la taille maximum de téléchargement de fichiers
        • Comment ajouter une page à PrestaShop
        • Générer le fichier .htaccess par Prestashop pour avoir des URLs simplifiées
        • Générer un nouveau mot de passe manuellement
        • Import CSV
        • Personnalisation des mails clients
        • Problème d'allocation mémoire chez 1&1
        • Problème pour se connecter après avoir effacé une langue
        • Votre site ne répond plus, une page blanche s’affiche
      • Fidéliser les Clients
      • Gestion des Taxes
      • Installer Un Module
      • Sauvegarder votre Base de Données
    • PDF de la documentation
    • Contributions des utilisateurs
    • Questions fréquentes
  • Documentación española 1.4
    • Introducción
    • Actualización de PrestaShop
    • Guía de Usuario
      • Entrenamiento
      • Personalización de su tienda
      • Exploración del front-office
      • Conexión al back-office PrestaShop
      • Añadir Productos y Categorías de Productos
      • Una Mirada Dentro del Catálogo
      • Gestión de Clientes
      • Gestión de Pedidos
      • Gestión de Métodos de Pago
      • Gestión de Envío
      • Comprensión de las Estadísticas
      • Gestión de Módulos
      • Gestión de Empleados
      • Comprensión de Preferencias
      • Exploración de las herramientas de PrestaShop
      • Soporte PrestaShop
    • Guía del Administrador del Sistema
    • Guía del Desarrollador
      • Aspectos Fundamentales
      • Creación de un módulo de PrestaShop
      • Estándares de desarrollo
      • Manuales de desarrollador
        • Utilización del servicio web REST
          • Capítulo 1 - Creación de Acceso al Back Office
          • Capítulo 2 - Descubrimiento - Pruebas de acceso al servicio web con el navegador
          • Capítulo 3 - Primeros pasos - Acceso al servicio Web y lista de clientes
            • 3.1 - Acceso al servicio web
            • 3.2 - Manejo de errores
            • 3.3 - Enumeración de clientes
          • Capítulo 4 - Recuperación de datos - Recuperación de un cliente
          • Capítulo 5 - Modificación - Actualización de cliente
          • Capítulo 6 - Creación - Formulario En Línea Remoto
          • Capítulo 7 - Eliminación - Eliminar cuentas de clientes de la base de datos
          • Capítulo 8 - Uso avanzado
        • Comprensión y uso de hooks
        • Sincronización a través de Hooks
        • Módulos, Reemplazo, Servicio Web
        • Módulos, Clases y Reemplazo del Controlador
        • Buenas prácticas de Clase DB para Prestashop 1.4
        • Módulos de transportistas - funciones, creación y configuración
        • Curso Acelerado de Seguridad - Episodio 1 - Nunca Confíe en Datos Exteriores
        • Curso Acelerado de Seguridad - Episodio 2 - Inyecciones SQL
        • Curso Acelerado de Seguridad - Episodio 3 - XSS
        • Curso Acelerado de Seguridad - Episodio 4 - CSRF
      • Referencia del servicio web
    • Guía de Diseñador
      • Codificación de un tema
      • Consejos de Diseño
    • Solución de problemas
    • Preguntas Frecuentes
Powered by GitBook
On this page
  • Prefacio
  • ¿Por dónde empiezo?
  • Explicación del ejemplo
  • 1) Los métodos __construct, install y uninstall
  • 2) Métodos del Back Office
  • 3) Métodos de front office
  • Medidas adicionales

Was this helpful?

  1. Documentación española 1.4
  2. Guía del Desarrollador
  3. Manuales de desarrollador

Módulos de transportistas - funciones, creación y configuración

PreviousBuenas prácticas de Clase DB para Prestashop 1.4NextCurso Acelerado de Seguridad - Episodio 1 - Nunca Confíe en Datos Exteriores

Last updated 4 years ago

Was this helpful?

Este artículo fue escrito por Fabien Serny y .

Prefacio

Tenga en cuenta que este artículo está dirigido a desarrolladores avanzados (el conocimiento de los hook, el objeto Transportista ...) y se aplica a PrestaShop 1.4 y versiones posteriores. Para saber lo que es un hook, le recomiendo leer el artículo de Julien Breux aquí:

En un nivel básico PrestaShop le permite crear transportistas y configurar la manera como los gastos de envío son calculados basados en rangos de peso y precio que puede especificar en el back office.

Los límites de este sistema se alcanzan cuando desea recuperar precios a través de servicios web (UPS, USPS, Fedex) o si desea crear su propio sistema para el cálculo de gastos de envío (por número de artículos en la cesta, restringiendose de un transportista o de uno o más países, etc.).

Aquí es cuando los módulos de transportista entran en juego.

¿Por dónde empiezo?

Hay un módulo básico que se puede . El artículo comenzará a partir de este módulo básico, pero por supuesto usted puede modificarlo y adaptarlo a sus necesidades

En nuestro ejemplo, usted puede manejar dos transportistas y establecer un costo adicional para ellos, además del precio por rango configurado en el back office.

Algunas partes del código se duplican deliberadamente para ayudarle a entender el mecanismo. Depende de usted manejar su lista específica de transportistas (utilizando un cuadro de datos, por ejemplo).

Explicación del ejemplo

En primer lugar, tenga en cuenta el hecho de que el módulo pertenece a la clase CarrierModule y no la clase Module. Por ahora, vamos a hacer una breve lista de los métodos contenidos en este módulo y la forma en que funciona en general.

1) Los métodos __construct, install y uninstall

Construct:

// The carrier id is automatically filled in with the right id for the carrier.
// We will look at the purpose of this a little later.
public  $id_carrier;

private $_html = '';
private $_postErrors = array();
private $_moduleName = 'mycarrier';
/*
** Construct Method
**
*/
public function __construct()
{
       // Variables common to all modules (no need to present them)
    $this->name = 'mycarrier';
    $this->tab = 'shipping_logistics';
    $this->version = '1.0';
    $this->author = 'YourName';
    $this->limited_countries = array('fr', 'us');
    parent::__construct ();
    $this->displayName = $this->l('My Carrier');
    $this->description = $this->l('Delivery methods that you want');
        // If the module is installed, we run a few checks
    if (self::isInstalled($this->name))
    {
        // We retrieve the list of carrier ids
        global $cookie;
        $carriers = Carrier::getCarriers($cookie->id_lang, true, false, false,
                NULL, PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
        $id_carrier_list = array();
        foreach($carriers as $carrier)
            $id_carrier_list[] .= $carrier['id_carrier'];




        // We look to see if the carriers have been created for the module
        // And if any additional fees have been configured
        // These warnings will appear on the page where the modules are listed
        $warning = array();
        if (!in_array((int)(Configuration::get('MYCARRIER1_CARRIER_ID')),
                   $id_carrier_list)) $warning[] .= $this->l('"Carrier 1"').' ';
        if (!in_array((int)(Configuration::get('MYCARRIER2_CARRIER_ID')),
               $id_carrier_list)) $warning[] .= $this->l('"Carrier 2 Overcost"').' ';
        if (!Configuration::get('MYCARRIER1_OVERCOST'))
            $warning[] .= $this->l('"Carrier 1 Overcost"').' ';
        if (!Configuration::get('MYCARRIER2_OVERCOST'))
            $warning[] .= $this->l('"Carrier 2 Overcost"').' ';
        if (count($warning))
    $this->warning .= implode(' , ',$warning).$this->l('must be <br />configured');
    }
}

Install:

/*
** Install / Uninstall Methods
**
*/
public function install()
{
    // We create a table containing information on the two carriers
   // that we want to create

    $carrierConfig = array(
    0 => array('name' => 'Carrier1',
      'id_tax_rules_group' => 0, // We do not apply thecarriers tax
      'active' => true, 'deleted' => 0,
      'shipping_handling' => false,
      'range_behavior' => 0,
      'delay' => array(
        'fr' => 'Description 1',
        'en' => 'Description 1',
        Language::getIsoById(Configuration::get
                ('PS_LANG_DEFAULT')) => 'Description 1'),
      'id_zone' => 1, // Area where the carrier operates
      'is_module' => true, // We specify that it is a module
      'shipping_external' => true,
      'external_module_name' => 'mycarrier', // We specify the name of the module
      'need_range' => true // We specify that we want the calculations for the ranges
    // that are configured in the back office
      ),
     1 => array('name' => 'Carrier2',
      'id_tax_rules_group' => 0,
      'active' => true,
      'deleted' => 0,
      'shipping_handling' => false,
      'range_behavior' => 0,
      'delay' => array(
        'fr' => 'Description 1',
        'en' => 'Description 1',
        Language::getIsoById(Configuration::get<br />
               ('PS_LANG_DEFAULT')) => 'Description 1'),
      'id_zone' => 1,
      'is_module' => true,
      'shipping_external' => true,
      'external_module_name' => 'mycarrier',
      'need_range' => true
    ),
);
    // We create the two carriers and retrieve the carrier ids
    // And save the ids in a database
    // Feel free to take a look at the code to see how installExternalCarrier works
    // However you should not normally need to modify this function

    $id_carrier1 = $this->installExternalCarrier($carrierConfig[0]);
    $id_carrier2 = $this->installExternalCarrier($carrierConfig[1]);
    Configuration::updateValue('MYCARRIER1_CARRIER_ID', (int)$id_carrier1);
    Configuration::updateValue('MYCARRIER2_CARRIER_ID', (int)$id_carrier2);
    // Then proceed with a standard module install
    // Later we will take a look at the purpose of theupdatecarrier hook

    if (!parent::install() ||
        !Configuration::updateValue('MYCARRIER1_OVERCOST', '') ||
        !Configuration::updateValue('MYCARRIER2_OVERCOST', '') ||
        !$this->registerHook('updateCarrier'))
        return false;

    return true;
}

Uninstall:

public function uninstall()
{
    // We first carry out a classic uninstall of a module
    if (!parent::uninstall() ||
        !Configuration::deleteByName('MYCARRIER1_OVERCOST') ||
        !Configuration::deleteByName('MYCARRIER2_OVERCOST') ||
        !$this->unregisterHook('updateCarrier'))
        return false;
    // We delete the carriers we created earlier
    $Carrier1 = new Carrier((int)(Configuration::get('MYCARRIER1_CARRIER_ID')));
    $Carrier2 = new Carrier((int)(Configuration::get('MYCARRIER2_CARRIER_ID')));
// If one of the two modules was the default carrier,
//we choose another
    if (Configuration::get('PS_CARRIER_DEFAULT') == (int)($Carrier1->id) ||
        Configuration::get('PS_CARRIER_DEFAULT') == (int)($Carrier2->id))
    {
        global $cookie;
        $carriersD = Carrier::getCarriers($cookie->id_lang, true, false, false, <br />
                NULL, PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
        foreach($carriersD as $carrierD)
            if ($carrierD['active'] AND !$carrierD['deleted']
                AND ($carrierD['name'] != $this->_config['name']))
                Configuration::updateValue('PS_CARRIER_DEFAULT',<br />
                                $carrierD['id_carrier']);
    }
    // Then we delete the carriers using variable delete
    // in order to keep the carrier history for orders placed with them

    $Carrier1->deleted = 1;
    $Carrier2->deleted = 1;
    if (!$Carrier1->update() || !$Carrier2->update())
        return false;

    return true;
}

2) Métodos del Back Office

No voy a concentrarme en la mayoría de los métodos de back office (getContent, _displayForm, _postValidation and _postProcess), ya que son relativamente simples y se encuentran ahí para que pueda establecer los costos del transportista. Le dejaré descubrirlos en el módulo de ejemplo.

Sin embargo, me gustaría concentrarme en el método hookupdateCarrier. En PrestaShop, cada vez que edita un transportista, el transportista se archiva automáticamente y uno nuevo es creado.

Técnicamente, PrestaShop cambia la bandera de eliminado del transportista a 1 y crear uno nuevo.

Por eso, cuando edita un transportista a través de la pestaña "Transportista" en su back office, su id cambia.

Por lo tanto, debe conectar con un hook el módulo con el fin de actualizar el Id del transportista cuando este cambia.

/*
** Hook update carrier
**
*/
public function hookupdateCarrier($params)
{
    // Update the id for carrier 1
    if ((int)($params['id_carrier']) == (int)(Configuration::get<br />('MYCARRIER1_CARRIER_ID')))
        Configuration::updateValue('MYCARRIER1_CARRIER_ID', (int)<br />
                ($params['carrier']->id));
    // Update the id for carrier 2
    if ((int)($params['id_carrier']) == (int)(Configuration::get<br />('MYCARRIER2_CARRIER_ID')))
        Configuration::updateValue('MYCARRIER2_CARRIER_ID', (int)<br />
               ($params['carrier']->id));
}

3) Métodos de front office

/*
** Front Methods
**
** If you set the variable need_range to true when you created your carrier
** in the install() method, the method called up by the Cart class
** will be getOrderShippingCost()
** Otherwise the method called up will be getOrderShippingCostExternal
**
** The $params variable contains the basket, the customer and their addresses
** The $shipping_cost variable contains the cost calculated
** according to the price ranges set
** for the carrier in the backoffice
**
*/

public function getOrderShippingCost($params, $shipping_cost)
{
    // This example returns the shipping fee with the additional cost
    // but you can call up a webservice or perform the calculation you want
    // before returning the final shipping fee

    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER1_CARRIER_ID')) &&
        Configuration::get('MYCARRIER1_OVERCOST') > 1)
        return (float)(Configuration::get('MYCARRIER1_OVERCOST'));

    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER2_CARRIER_ID')) &&
        Configuration::get('MYCARRIER2_OVERCOST') > 1)
        return (float)(Configuration::get('MYCARRIER2_OVERCOST'));
    // If the carrier is not recognised, just return false
    // and the carrier will not appear in the carrier list

    return false;
}
public function getOrderShippingCostExternal($params)
{
    // This example returns the additional cost
    // but you can call up a webservice or perform the calculation you want
    // before returning the final shipping fee

    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER1_CARRIER_ID')) &&
        Configuration::get('MYCARRIER1_OVERCOST') > 1)
                return (float)(Configuration::get('MYCARRIER1_OVERCOST'));
    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER2_CARRIER_ID')) &&
            Configuration::get('MYCARRIER2_OVERCOST') > 1)
                return (float)(Configuration::get('MYCARRIER2_OVERCOST'));
    / If the carrier is not recognised, just return false
    // and the carrier will not appear in the carrier list

    return false;
}

Medidas adicionales

El ejemplo es muy sencillo, pero puede crear módulos más complejos mediante la asociación con servicios web, por ejemplo (como es el caso de los módulos UPS) o realizar un cálculo basado en el número de productos en su carrito.

En resumen, ahora ya domina el cálculo de gastos de envío

publicado el 28 de septiembre de 2011 en el blog PrestaShop
Comprensión y uso de hooks
descargar aquí