How to Create Shipping Module for Prestashop

August 22, 2014 / Posted in Prestashop, Tips&Tricks by Alex Simonchik
blog-shipping

Today, we’ll show you how to create a module for the shipping service. The main peculiarity is that such module should be inherited from the abstract class CarrierModule and should implement the following 2 methods: «getOrderShippingCost», «getOrderShippingCostExternal»:

These methods are required to calculate shipping costs. We will create a shipping module to better understand all the nuances. The theoretical part is available on this page:  http://doc.prestashop.com/display/PS16/Creating+a+carrier+module. At the end of the article you can download the ready-to-use module. So, let’s begin:

Here we use the standard constructor, and we are going to use only one hook “асtiоnCаrrierUpdаte”. This hook is required to ensure that the module will not lose connection with the carrier, created by the module. The thing is that a carrier is given a new ID each time it is edited through the admin panel. Users do not notice this, but for the program this is very important, because ID serves as a unique identifier, which we can use to find the necessary carrier at any time.

When installing the module we also create a carrier and assign it to the module. This way the carrier will be receiving the shipping costs not from a static database, but dynamically, perhaps, by using a third-party API. It is important to keep the ID and reference of the carrier, because we are going to identify the carrier exactly by that field when the ID changes.

When removing the module also delete the carrier.

Implementing the functions of the abstract class CarrierModule. We are not going to focus attention on any logic for dynamic calculation of the cost, but will just return the amount of 777.

The hook «ActionCarrierUpdate» keeps the reference of the original carrier.

So, this is the entire module.  When developing such a module the main part of the work takes to receive data via API and to develop the logic for calculating the cost of delivery.



25 comments

  1. Hello. Thank you for your tutorial.
    I can’t seem to find the link to download the ready-to-use module.
    That would be very helpful!
    Thank you

  2. Hi.

    this is an excellent tutorial, thanks for sharing this.
    I have a question, How can I add the tracking code to the order when is already paid.

  3. You can set a tracking number for the order in the admin panel. Click edit and set the tracking number:

  4. name = ‘shippingconfigurator’;
    $this->tab = ‘shipping_logistics’;
    $this->version = ‘1.0’;
    $this->author = ‘R. Pepelea’;
    $this->limited_countries = array();

    parent::__construct ();

    $this->displayName = $this->l(‘Shipping Configurator’);
    $this->description = $this->l(‘Configure your shipping prices depending on weight.’);

    }

    public function install(){

    if (parent::install()) {
    foreach ($this->_hooks as $hook) {
    if (!$this->registerHook($hook)) {
    return FALSE;
    }
    }

    return TRUE;
    }

    return FALSE;

    }

    public function uninstall()
    {

    if (parent::uninstall()) {
    foreach ($this->_hooks as $hook) {
    if (!$this->unregisterHook($hook)) {
    return FALSE;
    }
    }

    return TRUE;
    }

    return FALSE;

    }

    public function hookactionCartSave($params)
    {

    global $smarty;

    $product_list = $params[‘cart’]->getProducts();

    $total_weight = 0;
    $total_extra_cost = 0;

    foreach ( $product_list as $product ):
    $total_weight += $product[‘weight_attribute’];
    endforeach;

    $total_extra_cost = $total_weight * 33;

    }

    public function hookActionCarrierUpdate($params)
    {

    }

    public function getOrderShippingCost($params = null, $shipping_cost = 0){

    return 777;
    }

    public function getOrderShippingCostExternal($params){

    return 999;
    // return $this->getOrderShippingCost($params, 0);
    }
    }

    I have this code, could you please tell me why doesn’t it overwrite my shipping costs?
    I get the same shipping cost, it doesn’t change to 999 or 777.

  5. Thank you for the tutorial,

    could you please share tutorial for the essential part for shipping module that is using the API to get the cost of shipping based on total weight, city or sub city of destination, service type (eg economy, reguler, fast)

    i belive it will need city or sub -city field as required for shipping address, and teh API processing than integrate to the rest of the modul.

    Regards,
    Bun Hin

  6. Thanks for tut, helpfull. But anyways, you firt should test before publishing. Your code have errors.
    You defined hooks into variable, but never used it in installation to register them. Unless maybe PS registers them automatically, who knows. Anyways, thanks.

  7. bun hin,

    The reference to the API for some other module does not make much sense, because they all are different. Besides these modules are paid.

  8. I followed you tutorial code without changing a single alphabet but instead of returning shipping cost as 777, it shows “Free Shipping”.
    I don’t care about logic I just want this 777 as shipping price but i can’t get it. Can you suggest anything?

  9. Vipul Hadiya,

    It is really strange. As we do not use any logic in calculating the shipping cost, it should just return 777.

  10. Thank you for the tutorial.

    I have a problem trying to test the module. I try to upload the module but does not appear in the list of modules, so I can not install it.
    I followed the instructions in the user manual but I can not make it work, I appreciate any suggestions.

  11. Hi Alex,

    First of all thanks for this tutorial !

    Do you know how i can make the delays dynamic on a carrier module.

    I’m trying to have dynamic delays called on an API.

    Thank you for your time.

    Stefan K.

  12. Hello Alex. A question… I use for value creation delivery third-party widget. This widget is built in to the front page. Therefore, the shipping cost is determined by the third party service at the time of registration of the order by the client. So here is how to pass the value of shipping cost in function getOrderShippingCostExternal? Thx.

  13. @bona

  14. Still more questions than answers.
    For example, this page babynabor.com/carrier.html I want to show what I need.
    So, I have a widget from an external site, which calculates the shipping cost depending on city. City of delivery is selected in the same widget at the time of order. I was able to embed the widget without creating a module, but the problem is that it is not clear how to pass the cost of delivery. One idea is to use the module with minor modifications. You can go the way of embedding the widget in order-carrier.tpl based on ID, but I think that making changes to Your module would be more correct.
    In this regard, could You tell where to paste in Your module code of the widget, so it can recalculate the shipping cost to the total cost?

    Thank you.

    Всё равно вопросов больше, чем ответов.
    На примере этой страницы (babynabor.com/carrier.html) я хочу показать что мне необходимо.
    Итак, у меня есть виджет стороннего сайта, который просчитывает стоимость доставки в зависимости от выбранного города. Город доставки выбирается в этом же виджете во время заказа. У меня получилось встроить данный виджет без создания модуля, но проблема состоит в том, что не понятно как передать стоимость доставки. Есть мысль использовать Ваш модуль с небольшими доработками. Можно пойти по пути встраивания виджета в order-carrier.tpl основываясь на ID, но думаю, что внесение изменений в Ваш модуль будет более правильным.
    В связи с этим, могли бы Вы подсказать куда вставлять в Вашем модуле код виджета, чтобы он мог пересчитывать стоимость доставки в итоговой стоимости?

    Спасибо.

  15. Hello Alex, I download you module and juste install in my new prestashop 1.6.1.7.
    In the admin, i see the carrier but in the front office part on the shipping step, the carrier it’s not propose ….
    Have you an idea ? I need to configure something ?
    You see a resume of my carrier config:
    This carrier is not free and the delivery announced is: Depends on the freight company [1-2 days].

    The shipping cost is calculated according to the weight and the tax rule No tax will be applied.

    This carrier can deliver orders from 0.000000 KGS to 1000000.000000 KGS. If the order is out of range, the behavior is to apply the cost of the highest defined range.

    This carrier will be proposed for those delivery zones
    Africa
    Asia
    Central America/Antilla
    Europe
    Europe (non-EU)
    North America
    Oceania
    South America
    And it will be proposed for those client groups
    Visitor
    Guest
    Customer
    Tarif2
    BojanLearning

  16. Do you know if exist a module for Fedex V2 webservice and for prestashop v1.6.1.7

Post a new comment