LogoLogo
Homepage
  • Documentations for PrestaShop 1.5
  • English documentation 1.5
    • About PrestaShop 1.5
    • New features in PrestaShop 1.5
    • Getting Started
      • What you need to get started
      • Installing PrestaShop
      • Installing PrestaShop using the command line
      • Updating & Uninstalling
      • Misc. information
    • Updating PrestaShop
      • Automatic update
      • Manual update
      • Making and restoring your own backup
      • In case of issues
    • User Guide
      • Training
      • Customizing your shop
      • Browsing the front-office
      • Connecting to the PrestaShop back-office
      • First steps with PrestaShop 1.5
      • Adding Products and Product Categories
      • A Look Inside the Catalog
      • Managing Orders
      • Managing Customers
      • Creating Price Rules and Vouchers
      • Managing Shipping
      • Understanding Local Settings
      • Managing Modules and Themes
      • Making the Native Modules Work
      • Understanding the Preferences
      • Understanding the Advanced Parameters
      • Administering the Back-Office
      • Understanding Statistics
      • Advanced Stock Management
      • Managing Multiple Shops
    • Developer Guide
      • Developer tutorials
        • Using the PrestaShop Web Service
          • Webservice one-page documentation
          • 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
          • 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
          • Chapter 9 - Image management
          • Chapter 10 - Price management
          • Cheat-sheet - Concepts outlined in this tutorial
          • Web service reference
        • Helpers
          • HelperForm
          • HelperOptions
          • HelperList
          • Using helpers to overload a back-office template
        • New Developers Features In PrestaShop 1.5
        • Using the Context Object
        • DB class best practices
        • Public and overloadable methods
        • Overriding default behaviors
        • Using addJquery(), addJqueryPlugin() and addJqueryUI()
        • Handling special characters in links
        • Auto-updating modules
        • Front-Office Controllers
        • Controllers correspondence table
        • Specifics of multistore module development
        • Developer tips and tricks
        • PrestaShop's developer tools
        • Using the backward compatibility toolkit
      • Fundamentals
      • Coding Standards
      • Setting up your local development environment
      • Diving into PrestaShop Core development
      • Creating a PrestaShop module
      • Creating a front-office module
      • Creating a module with both front-end and back-end controllers
      • Hooks in PrestaShop 1.5
      • Translations in PrestaShop 1.5
      • How to use the Forge to contribute to PrestaShop
      • How to write a commit message
      • Contributing code to PrestaShop
    • Designer Guide
      • Theme development fundamentals
      • Integrating content in a page using hooks
      • Characteristics of a front-office theme
      • Characteristics of a back-office theme
      • Creating your own theme
      • Theme templates and Smarty
      • Using jQuery and Ajax
      • Best practices
      • Designer tutorials
        • Changes in version 1.5 which impact theme development
        • Changing a 1.4 theme to support gift products
        • Implementing layered navigation in a theme
    • System Administrator Guide
    • Merchant's Guide
      • Our advices
      • Sample price rules
    • FAQ
      • Using PrestaShop with WordPress
    • Troubleshooting
  • Documentation française 1.5
    • À propos de PrestaShop 1.5
    • Nouveautés de PrestaShop 1.5
    • Guide de démarrage
      • Ce dont vous avez besoin
      • Installer PrestaShop
      • Installer PrestaShop en ligne de commande
      • Mettre PrestaShop à jour
      • Informations diverses
    • Guide de mise à jour
      • Mise à jour automatique
      • Mise à jour manuelle
      • Faire une sauvegarde et la restaurer
      • En cas de problème
    • Guide de l'utilisateur
      • Formations
      • Personnaliser votre boutique
      • Parcourir le front-office
      • Se connecter au back-office de Prestashop
      • Premiers pas avec PrestaShop 1.5
      • Ajouter des produits et des catégories de produits
      • Un aperçu du catalogue
      • Gérer les commandes
      • Gérer les clients
      • Mettre en place des promotions
      • Gérer les transporteurs
      • Comprendre les réglages locaux
      • Gérer les modules et les thèmes
      • Configurer les modules natifs
      • Comprendre les préférences
      • Comprendre les paramètres avancés
      • Administrer le back-office
      • Comprendre les statistiques
      • Gestion avancée des stocks
      • Gérer plusieurs boutiques
    • Guide du développeur
      • Fondamentaux
      • Norme de développement
      • Mettre en place votre environnement de développement
      • Plonger dans le développement PrestaShop
      • Créer un module PrestaShop
      • Les hooks de PrestaShop 1.5
      • Les traductions dans PrestaShop 1.5
      • Comment utiliser la Forge pour contribuer à PrestaShop
      • Comment écrire un descriptif de modification
    • Guide de l'intégrateur
      • Fondamentaux de la création de thème
      • Intégrer du contenu dans une page à l'aide de hooks
      • Caractéristiques d'un thème front-office
      • Caractéristiques d'un thème back-office
      • Template de thème et Smarty
      • Utiliser jQuery et Ajax
      • Bonnes pratiques
    • Guide de l'administrateur système
    • Guide du vendeur
      • Exemples de promotions
      • Nos bons conseils
    • Questions fréquentes
    • Dépannage
  • Documentación española 1.5
    • Acerca de PrestaShop 1.5
    • Introducción
      • Lo que necesita para empezar
    • Guía del usuario
      • Formación
      • Personalización de su tienda
      • Exploración del front-office
      • Conexión al back-office de PrestaShop
      • Primeros pasos con PrestaShop 1.5
      • Añadir productos y categorías de productos
      • Una mirada interna al catálogo
      • Gestionar pedidos
      • Gestionar clientes
      • Crear reglas de precios y cupones
      • Gestionar el transporte
      • Comprender la Configuración Local
      • Gestionar módulos y temas
      • Configurar los Módulos Nativos
      • Comprender las Preferencias
      • Comprender los Parámetros avanzados
      • Administrar el Back-Office
      • Comprender las estadísticas
      • Gestión avanzada de stock
      • Gestionar varias tiendas
    • Guía del Desarrollador
      • Tutoriales para Desarrolladores
        • Uso del Web Service de Prestashop
          • Capítulo 1 - Creación de acceso al Back Office
  • Документация на русском языке 1.5
    • Информация о PrestaShop 1.5
    • Новые функции в PrestaShop 1.5
    • Приступая к работе
      • Что нужно чтобы приступить к работе
      • Установка PrestaShop
      • Установка PrestaShop при помощи командной строки
      • Обновление и удаление PrestaShop
      • Прочая информация
    • Руководство пользователя
      • Обучение
      • Настройка вашего магазина
      • Изучение публичной части сайта
      • Бэк-офис PrestaShop
      • Первые шаги в PrestaShop 1.5
      • Добавление товаров и товарных категорий
      • Внутри каталога
      • Управление заказами
      • Работа с клиентами
      • Создание правил ценообразования корзины и ваучеров
      • Управление доставкой
      • Ориентация в локальных настройках
      • Управление модулями и темами
      • Настойка встроенных модулей
      • Ориентация в настройках
      • Ориентация в расширенных параметрах
      • Администрирование Back-Office
      • Ориентация в статистике
      • Расширенное управление запасами
      • Управление мультимагазином
Powered by GitBook
On this page
  • First steps - Access the Web service and list client
  • Preparation
  • Accessing the web service
  • Handling errors
  • Listing clients

Was this helpful?

  1. English documentation 1.5
  2. Developer Guide
  3. Developer tutorials
  4. Using the PrestaShop Web Service

Chapter 3 - First steps - Access the Web service and list client

PreviousChapter 2 - Discovery - Testing access to the web service with the browserNextChapter 4 - Retrieve Data - Retrieving a Client

Last updated 4 years ago

Was this helpful?

Table of content

/*<![CDATA[*/ div.rbtoc1597308497683 {padding: 0px;} div.rbtoc1597308497683 ul {list-style: disc;margin-left: 0px;} div.rbtoc1597308497683 li {margin-left: 0px;padding-left: 0px;} /*]]>*/

First steps - Access the Web service and list client

Preparation

  1. Configure your PHP installation so that it has the cURL extension installed and activated:

    • With Windows: Place this line in your php.ini file:

      extension=php_curl.dll
    • Linux/Mac: install the cURL extension:

      sudo apt-get install php5-curl
  2. Copy the PSWebServiceLibrary.php file at the root of your Web server.

    You can also do this tutorial on a local server even while your shop is on the Internet.

  3. Create a list_the_clients.php file at the root of the Web server that you have chosen.

  4. Specify where to find the web server in your file:

    require_once( './ PSWebServiceLibrary.php' );

Configured this way, your file should be found in the same folder as PSWebServiceLibrary.php.

Accessing the web service

In this section we will see how to access the web service using the PHP library.

First, you must create an instance of the PrestaShopWebservice object, which takes 3 parameters in its constructor:

  • The store's root path (ex: http://example.com/ ).

  • The authentication key (ex: ZR92FNY5UFRERNI3O9Z5QDHWKTP3YIIT).

  • A boolean value, indicating whether the Web service must use its debug mode.

If you do not understand the terms of object-oriented programming such as instance, method, or constructor, that's okay for the rest of the tutorial. Here's how you create a Web service call:

$webService = new PrestaShopWebservice('http://example.com/', 'ZR92FNY5UFRERNI3O9Z5QDHWKTP3YIIT', false);

Once the instance is created, you can access the following methods:

Method

HTTP equivalent

get()

GET

add()

POST

edit()

PUT

delete()

DELETE

We will explain how to use of these methods in other parts of the tutorial.

Handling errors

It is essential that you understand how to handle errors with the web service library. By implementing error-catch method early, you will more easily detect issues, and be able to correct them on the go.

How it works

The error handling is done within a try..catch block, with the web service processing being done in the try section, the catch one containing the error handling code.

try {
  // Execution ( if an error occurs in this code, stops and goes in the catch block)
}
catch {
  // Error handling (tries to catch the error or the error display)
} 

Example

That means each creation or use of the library must be located within a "try" block. The "catch" block can then handle the error if it occurs during the execution of the try block. Now we'll see how to list all customers via the web service, and then we will see the four CRUD methods.

In the following code sample, we want to to get the list of all customers:

  1. In the try block, we instantiate the PrestaShopWebservice object with the necessary parameters and retrieve the customer resource XML in a variable.

  2. In the catch block, we put code to display the PHP error message, if anything wrong happens in the try block.

try {
	// creating web service access
	$webService = new PrestaShopWebservice('http://example.com/', 'ZR92FNY5UFRERNI3O9Z5QDHWKTP3YIIT', false);

	// call to retrieve all clients
	$xml = $webService->get(array('resource' => 'customers'));
}
catch (PrestaShopWebserviceException $ex) {
	// Shows a message related to the error
	echo 'Other error: <br />' . $ex->getMessage(); 
}

Listing clients

Let's now see how to view a full list of client IDs. We could display more information and customize it, but that's for another part of this tutorial

As we saw in the previous code sample, we need the get() method to retrieve an XML file containing all the customers. The parameter has to be a key-value array, where we define the resource we want:

Key

Value

resource

customers

// The key-value array
$opt['resource'] = 'customers';

Retrieving the XML data
$xml = $webService->get($opt); 

The value defines the resource that the web service will use in a future call. The value could be carrier types, countries or any other type of resource that can be found in the "Web service" menu of your back-office.

Result

Launching the code above will return a SimpleXML object containing all the client IDs.

<?xml>
<prestashop>
  <customers>
    <customer>
      Client ID
    </customer>
    <customer>
      Client ID
    </customer>
    <customer>
      Client ID
    </customer>
...Other client tags
  </customers>
</prestashop>

Now we need to access the tags that interest us in the XML file.

Structure

The data returned by calling $webService->get puts us at the root of the document.

To access the fields of clients who are children from the Customers tag, we only need to retrieve all fields in an associative array in SimpleXML like this:

$resources = $xml->customers->children();

From there, we can access client IDs easily. Here's an example with a path from identifiers:

foreach ($resources as $resource)
	echo $resource->attributes() . '<br />'; 

Thanks to these elements, we can create a HTML table containing all the client IDs. Try that before reading the next chapter.

You can use the "Customers" menu in the back-office to find the IDs of all customers. If you encounter difficulties, have a look at the example file named 0-CustomersList.php, to see the results you should get.

Error handling with the web service library is done using PHP exceptions. If you do not know about them, you should read , as exceptions are an essential part of good coding practice.

http://php.net/manual/en/language.exceptions.php
First steps - Access the Web service and list client
Preparation
Accessing the web service
Handling errors
Listing clients