Shipping Plugins

This article assumes you have a clear understanding of PHP, PHP Classes, and arrays, as well as a good working knowledge of CartThrob.

CartThrob has a shipping plugin interface, and several helper functions that simplify the creation of shipping plugins. Refer to one of the included shipping plugins as an example. The "Flat Rates" plugin uses most of the functionality available to your shipping plugins, so it's a good starter example of what's possible.

Overview

Shipping plugins are PHP Classes that contain at a minimum a $title, and a get_shipping function. If you plan to offer your customers shipping options, you will also need a plugin_shipping_options function.

All shipping plugins are stored in the following location: **cartthrob > cartthrob > plugins > shipping**. You can look there for additional shipping plugins to use as a reference.

IMPORTANT

  1. Your plugin classname should match your plugin file name.

  2. Your plugin filename/classname needs to begin with **Cartthrob_shipping` or it will not be recognized as a shipping plugin.

  3. By default, sessions data is automatically available for all shipping plugins you create, so you do not have to, and should not start a session for your plugin, or plugin functions.

  4. You need to create a language file for each shipping plugin (see more about language files). Each language file should be named the same name as your shipping plugin, plus _lang at the end, and in all lower case (example: cartthrob_shipping_my_shipping_plugin_lang.php)

Table of Contents

Plugin Information

These fields, located at the top of the plugin allow you to set some general information about your plugin. Title is required. The rest are optional.

    public $title = 'Flat Rates 2';
    public $note = 'This payment system requires you to go to the following URL and sign up, etc, etc';

Language Files

You should probably create a language file for your plugin if you intend to have any settings available to select from. The naming convention for the language file is as follows:

cartthrob_shipping_YOUR_PLUGIN_NAME_lang.php

Review existing language files for an example of the proper formatting. Create language key/value pairs as needed, for example.

my_title => 'Flat Rates 2', 

You would access this like so:

public $title   = 'my_title';

CartThrob will look for the my_title key in the language file, and replace it with the relevant value. If it's not found, then my_title will be used instead.

Plugin Settings

Each plugin has the ability to store and manage its own settings. Each setting is an array that requires at a minimum array keys for name, type, and short_name of the setting. You can also add a default, options, note, settings (to generate a matrix settings).

name

required key

Name is the settings name that the customer will see. Use plain text, or a reference to a language file key.

type

required key

This is the type of setting. The following settings types are recognized:

  1. text
  2. textarea
  3. radio (see options)
  4. select (see options)
  5. checkbox (see options) (if not checked, will not return ANY value.)
  6. matrix (see settings)
  7. header

The type will determine whether data stored in this setting is string data or an array. text, textarea and header are the only string types. The rest are arrays

short_name

required key

The short_name is what will be used by your plugin to access the content of this setting (see plugin_settings function below). Short_names should only include "alpha-dash" characters. Alphabet + numeric + underscore and hyphen.

default

optional key

Optional key. This is default data that should populate the setting. Default data can not be used to preset matrixes. Each individual matrix field can contain a default, but an entire row can't be set using one default.

options

(usually) optional key

Required if you are using a non-text type. Options is an array containing the selectable options in a radio or select dropdown. The option key is accessible using the plugin_settings function. The value is descriptive for the client only, and is not accessible, except by using the key in conjunction with a call to the language file.

'options' => array(
    'option' => 'Descriptive Name',
    'option2' => 'Other Descriptive Name',
),
note

optional key

Optional & purely descriptive. Generally the "name" key should be fairly short, but the "note" key can contain one or more paragraphs as needed to describe the setting in detail to the user.

settings

optional key

If you are using a matrix type, then you'll need to add a settings key that will contain additional keys for each matrix field. CartThrob shipping plugins do not allow the use of a matrix within a matrix. whoah

Example
    $public $settings = array(
        array(
            'name' => 'Settings Example', // descriptive name
            'short_name' => 'settings_example', // you will use this to access this setting your code.
            'type' => 'text', 
            'default' => 'Whatevs', // optional
        ),
        array(
            'name' => 'Settings Example 2', 
            'short_name' => 'settings_example_2', 
            'type' => 'radio',
            'default' => 'yes',
            'options' => array(
                'yes' => 'Yes',
                'no' => 'No',
            ),
        ),
        array(
            'name' => 'settings_example_3',
            'short_name' => 'settings_example_3',
            'type' => 'matrix',
            'settings' => array(
                array(
                    'name' => 'Matrix Settings',
                    'short_name' => 'matrix_settings',
                    'type' => 'checkbox',
                    'options' => array(
                        'they_work' => 'Yep'
                )
            ),
        ),
    );

Using the "settings" array, you can create multiple setting fields that will display in the plugin's settings when it is selected.

Required Functions

shippingRate

The shippingRate function is the only required function for most shipping plugins.

parameters: none return: float (the shipping cost)

public function shippingRate()
{
    return 10.00; 
}
initialize

Only needed if you want to set a plugin wide variable in one central location.

parameters: If not passing any, PHP 7 requires empty arrays at a minimum return: void

protected $default_rate = 0;

public function initialize($params = array(), $defaults = array())
{
     if ($this->plugin_settings('default_rate') )
    {
        $this->default_rate = $this->plugin_settings('default_rate'); 
    }
}
plugin_shipping_options

This plugin returns the price, title, and option name of each customer selectable shipping option. This data will be output by that tag as a select dropdown.

parameters: none return: array

public function plugin_shipping_options()
{
    $options = array();

    foreach ($this->rates as $rate_short_name => $price)
    {
        $options[] = array(
            'rate_short_name' => $rate_short_name,
            'price' => $price,
            'rate_price' => $price,
            'rate_title' => $this->rate_titles[$rate_short_name],
        );
    }

    return $options;
}
default_shipping_option

Set's the default shipping option when used in conjunction with the plugin_shipping_options function.

parameters: none return: string (short_name of the selected option)

public function default_shipping_option()
{
    return $this->default_shipping_option;
}

Core Cart Functions

Any of CartThrob's methods can be used by a shipping plugin, the following is a short list of the most useful core cart functions available for shipping purposes.

  1. shippable_weight
  2. shippable_subtotal
  3. shipping_info
  4. customer_info
  5. plugin_settings
  6. cart_items

ExpressionEngine functions can also be called if it is instantiated.

$this->EE =& get_instance(); 

You can also access several CartThrob helper functions by instantiating ExpressionEngine, and loading the cartthrob shipping plugins library.

$this->EE =& get_instance(); 
$this->EE->load->library('cartthrob_shipping_plugins');
shippable_weight

This returns the combined weight of all of the items in the cart

(float) $this->core->cart->shippable_weight(); 
shippable_subtotal

This returns the cost of the items in the cart without shipping or tax applied

(float) $this->core->cart->shippable_subtotal(); 
shipping_info
(string) $this->core->cart->shipping_info('shipping_option');
customer_info

This returns an array of all of the customer information.

(array) $this->core->cart->customer_info(); 

You can also call specific customer info:

$this->core->cart->customer_info("first_name"); 
plugin_settings

Outputs the contents of a particular setting, called by the setting's "short_name"

(mixed) $this->plugin_settings('YOUR_KEY'); 

example:

if ($this->plugin_settings('test_mode') == 'test')
{
    $sample_price = 10; 
}
cart_items

Outputs the contents of all items in the cart.

(object) $this->core->cart->items(); 

You can also access object methods for each item in the cart:

foreach ($this->core->cart->items() as $key => $item)
{
    echo $item->quantity(); 
    echo $item->price();
    echo $item->weight(); 
}

User selectable rates

If the customer can select from available rates, you'll need to use the plugin settings function to allow the customer to select a shipping method. The "cartthrob_shipping_flat_rates.php" file contains an example of this function.

Shipping plugins library

Additional helper functions are made available by instantiating ExpressionEngine and loading the cartthrob shipping plugins library. Normally these are not used unless integrating with an offsite shipping rates provider.

$this->EE =& get_instance(); 
$this->EE->load->library('cartthrob_shipping_plugins');

These functions are as follows:

alpha2_country_code

converts a country code from the standard 3 character to 2 character country code

parameters: string (3 char country code) return: string (2 char country code)

$country_code = alpha2_country_code("USA"); // would output "US"
curl_transaction

parameters:

  • $url (string) the URL that should be cURLed to
  • $data (string|array) the data that should sent to the cURL url. Send in either query string, or array format return: string (curled data)

    $result = $this->EE->cartthrob_shipping_plugins->curl_transaction($url,$data);

customer_location_defaults

Allows you to check a key in customer_info and optionally set a default value if none has been set already.

parameters:

return: string (customer data)

$city = $this->EE->cartthrob_shipping_plugins->customer_location_defaults("city", "My City"); 

Examples

The following is a very simple example. Check cartthrob > cartthrob > plugins > shipping for additional shipping plugins to use as a reference.

<?php if ( ! defined('CARTTHROB_PATH')) Cartthrob_core::core_error('No direct script access allowed');

class Cartthrob_shipping_single_flat_rate extends Cartthrob_shipping
{
    public $title = 'single_flat_rate';
    public $settings = array(   
        array(
            'name' => 'rate',
            'short_name' => 'rate',
            'type' => 'text',
        ),
    );

    public function shippingRate()
    {
        return $this->plugin_settings('rate');   
    }
}