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
  • The rationale
  • Creating a basic module
  • Building the hooks

Was this helpful?

  1. English documentation 1.4
  2. Developer Guide
  3. Developer tutorials

Creating your own payment module

PreviousCarrier modules - functions, creation and configurationNextAccelerated Security Course - Episode 1 - Never Trust Foreign Data

Last updated 4 years ago

Was this helpful?

The rationale

PrestaShop provides a seller (and his customers) with many ways to handle payment for goods, thanks to the modules installed by default. PayPal, Hipay or Authorize.Net are just a few of the modules that are a click away from activation.

Still, not all payment solutions are available by default, and if you do not find the one you need on the website, you might have to work one out yourself – and why not, sell it to other shop owners on PrestaShop Addons!

This tutorial was created to help you with this task.

Creating a basic module

A payment module is just like any other PrestaShop module, so you won't be surprised by the first few methods – except for the fact that the main class does not extend the Module object, but the PaymentModule one. Apart from that, the __construct(), install() and uninstall() methods are mostly as described in the Developer Guide.mypayment.php

class MyPayment extends PaymentModule{ public function __construct() { $this->name = 'mypayment'; $this->tab = 'payments_gateways'; $this->version = 0.1; $this->author = 'PrestaShop'; $this->currencies = true; $this->currencies_mode = 'radio'; parent::__construct(); $this->displayName = $this->l('Hipay'); $this->description = $this->l('Hipay API implementation'); if (!sizeof(Currency::checkPaymentCurrencies( $this->id))) $this->warning = $this->l('No currency set for this module'); }}

You'll notice a few lines that are not present in the module tutorial from the Developer Guide:

  • $this->currencies = true;: XXX.

  • $this->currencies_mode = 'radio';: Indicates the type of restrictions the module should answer to. If 'radio', then the module can only apply to one currency; if checkbox, then it can apply to any number of currencies.

  • if (!sizeof(Currency::checkPaymentCurrencies($this->id))): checks whether XXX.

The install() method is where you set the different values pertaining to your module, either the needed constants, or filling up the database.mypayment.php

public function install(){ if (!parent::install() OR !$this->registerHook('payment') OR !$this->registerHook('paymentReturn') OR !Configuration::updateValue('MYPAYMENT_MERCHANT_ID', '32029e6d2bcb25cab87232d92c7c634c') OR !Configuration::updateValue('MYPAYMENT_MERCHANT_KEY', '8790eb2d0fec01c544d57e839b1b3b62') OR !Configuration::updateValue('MYPAYMENT_NO_SHIPPING', '0')) return false; return true;}

All of these values should be discarded by the uninstall() method:mypayment.php

public function uninstall(){ return (parent::uninstall() AND Configuration::deleteByName('MYPAYMENT_MERCHANT_ID') AND Configuration::deleteByName('MYPAYMENT_MERCHANT_KEY') AND Configuration::deleteByName('MYPAYMENT_NO_SHIPPING') );}

This are the basics. Not any PrestaShop module should be released without these methods. Note that these are sample configuration values; you should use only the ones necessary to your provider's needs.

Now let's jump to the specifics.

Building the hooks

Every PrestaShop payment modules should implement a set of predefined methods, which are called by hooks that are triggered during the payment process (front-office) or as part of the admin interface (back-office).

hookPayment() hook

This might be the most important hook, as it is always called – namely, when displaying the payment option in the check-out process. It is also the entry point to whole payment process: exploring hookPayment will take us through many PHP and TPL files, each serving a specific purpose.mypayment.php

public function hookPayment($params){ if (!$this->active) return ; global $smarty; $smarty->assign(array( 'this_path' => $this->_path, 'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/' ) ); return $this->display(__FILE__, 'payment.tpl');}

The whole point of this hook is to display the payment.tpl template at the right location on the frontpage (namely, the payment method choosing page).

payment.tpl file

Our hookPayment() code calls for a template file which is very simple, but should match a few essential points.

Here's a a sample template file:payment.tpl

<p class="payment_module"> <a href="{$this_path_ssl}validation.php" title="{l s='Pay with MyPayment module' mod='mypayment'}"> <img src="{$this_path}mypayment.gif" alt="{l s='Pay with MyPayment module' mod='mypayment'}" style="float:left;" /> <br />{l s='Pay with MyPayment module' mod='mypayment'} <br />{l s='A great way to pay online!' mod='mypayment'} <br style="clear:both;" /> </a></p>

Here is what PrestaShop needs in that template file:

  • wrapper <P> tag with the "payment_module" class.

  • a link to a PHP file, which role is to validate the payment method choice (recommended: validation.php or payment.php).

  • HTML elements should feature a mod attribute, with the module's name as only value

  • (optional) an image, ideally the payment provider's logo, making it easier to make a decision. Must be left aligned (style="float:left;"), and with size 86*49.

  • {optional) at most two lines of description.

This template merely creates a link to validation.php, which is the first real step in putting your payment method into the payment process.

The payment method validation file: validation.php

In this step of the payment process, the customer has chosen his mean of payment. Now we need to display a form to obtain his payment details – typically, his credit card details, unless the process is different for the payment gateway provider.validation.php

<?php include(dirname(__FILE__).'/../../config/config.inc.php');include(dirname(__FILE__).'/../../header.php');include(dirname(__FILE__).'/mypayment.php'); if (!$cookie->isLogged()) Tools::redirect('authentication.php?back=order.php'); $mypayment= new MyPayment();echo $mypayment->execPayment($cart); include_once(dirname(__FILE__).'/../../footer.php'); ?>

The first lines are files which contain methods that we need for the process to continue:

  • config.inc.php is PrestaShop's own configuration, with important data, such as the MySQL access identifiers.

  • header.php and footer.php are the theme's header and footer file, which will build the theme for us around the payment form.

  • mypayment.php is our own module's PHP file. This way, we can easily use methods that were define in that file.

We must make sure that the user is already logged, and if not, redirect him to the authentication form.

Once the user is logged with certainty, we can trigger the needed function, execPayment(), which is defined in the main module file. The $cart variable is handled by PrestaShop.

Here is a sample execPayment() method:mypayment.php

public function execPayment($cart){ if (!$this->active) return; global $cookie, $smarty; $smarty->assign(array( 'this_path' => $this->_path, 'this_path_ssl' => (Configuration::get('PS_SSL_ENABLED')?'https://':'http://') .htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT,'UTF-8') .__PS_BASE_URI__.'modules/'.$this->name.'/') ); return $this->display(__FILE__, 'payment_execution.tpl');}

The point of execPayment() is to:

  • assert that the module is indeed active.

  • assign values to the Smarty engine, pertaining to the module's path.

  • display the payment_execution.tpl template file.

payment_execution.tpl

hookPaymentReturn() hook

Another essential hook, hookPaymentReturn() is called

public function hookPaymentReturn($params){ if (!$this->active) return ; return $this->display(__FILE__, 'confirmation.tpl');}

getContent() hook

The getContent() hook is specifically triggered when the user clicks on the module's "Configure" link. Thus, the method should feature all the interface and methods calls necessary to have the user configure the payment gateway properly. If your module doesn't need configuring, then this method is not necessary.

***

Basic modules can feature the whole configuration page within the getContent() method. For more complexes pages, it is recommended to separate the configuration code to another page with its own object and methods. for instance :mypayment.php

public function getContent(){ include(_PS_MODULE_DIR_.$this->name.'/settings.php'); $mypaymentSettings = new MyPaymentSettings(); return $mypaymentSettings->home();}

execPayment() hook

hookOrderConfirmation() hook

preparePayment() hook

validate() hook

As you might know already, PrestaShop's module framework is based on a system of hooks. If you are not aware of what hooks are, read Julien Breux's .

PrestaShop Addons
Understanding and using hooks