How to Create Integration Module in Magento 2

When online stores need to expand their business that requires a lot of additional functionalities for their online stores. This is when they need to create integration module . An integration allows third-party services to call the Magento web APIs. It not only enables online stores to perform necessary functionalities but also adds more power to the stores when needed. Currently, Accounting, Customer Relationship Management (CRM), Product Information Management (PIM), Enterprise Resource Planning (ERP), and marketing automation systems are supported by the Magento API.

Obviously, integration plays a vital role in any online business.

Although implementing a simple integration requires little PHP or Magento internal processes knowledge, it’s necessary for you to have the basic knowledge about the following aspects and be able to work on them.

Magento API Integration Service by Mageplaza

Connect your store with any 3rd-party software and boost customer experience quickly and efficiently.

Learn more
Magento API Integration service

Before creating a module, you have to ensure that you have installed Magento 2.0 and Magento system requirements.

Below are five simple steps that you need to follow to create integration module

5 Steps to create Integration Module in Magento 2

Step 1: Create skeletal module

Here is how you are going to develop a module.

  1. Create the module file structure: The module can be placed in any place under the Magento root directory. But it is recommended to be located in <magento_base_dir>/vendor/<vendor_name>/module-<module_name>.

You also need to create subdirectories which are etc, etc/integration, and Setup under module-<module_name>, please view the example below:

 cd <magento_base_dir>
 mkdir -p vendor/<vendor_name>/module-<module_name>/etc/integration
 mkdir -p vendor/<vendor_name>/module-<module_name>/Setup

Learn more in Magento 2 File structure

  1. Define your module configuration file: Basic information about the module is provided by the etc/module.xml file. The directories are changed to etc directory. And the module.xml file is created. The value for the following attributes has to be specified.
Attribute Description
name A string which uniquely identifies the module
setup_version The Magento version which the component uses

Here is an example of etc/module.xml file:

<?xml version="1.0"?>
<!--
   /**
   * Copyright © 2015 Magento. All rights reserved.
   * See COPYING.txt for license details.
   */
   -->
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
       <module name="Vendor1_Module1" setup_version="2.0.0">
            <sequence>
                <module name="Magento_Integration"/>
            </sequence>
       </module>
     </config>

Here, the Module Magento_Integration is added to sequence to be loaded first, which would help avoid a malfunction happens when a module with integration config loaded.

  1. Add your module’s composer.json file: Composer is considered as a dependency manager for PHP. In order for Composer to install and update the libraries your module relies on, a composer.json file must be created. The composer.json file is placed in the module-<module_name> directory.

Below is an example which demonstrates a minimal composer.json file.

   {
      "name": "Vendor1_Module1",
      "description": "create integration from config",
      "require": {
         "php": "~5.5.0|~5.6.0|~7.0.0",
         "magento/framework": "2.0.0",
         "magento/module-integration": "2.0.0"
      },
      "type": "magento2-module",
      "version": "1.0",
      "autoload": {
         "files": [ "registration.php" ],
         "psr-4": {
            "Vendor1\\Module1\\": ""
         }
      }
   }
  1. Create a registration.php file: This file would help register the module with the system of Magento. And it has to be located in the root directory of the module.
   <?php
     /**
     * Copyright © 2015 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */

     \Magento\Framework\Component\ComponentRegistrar::register(
     \Magento\Framework\Component\ComponentRegistrar::MODULE,
     'Vendor1_Module1',
     __DIR__
     );
  1. Create an install class: In this step to create an integration module in Magento 2, the directories will be changed to your Setup directory. Create a new class: Create a new class named PatchData within the Setup namespace. This class will handle the patch data logic.
 namespace Vendor1\Module1\Setup\Patch\Data;

use Vendor1\Module1\Setup\InstallData;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class PatchData implements DataPatchInterface
{
    /**
     * @var InstallData
     */
    private $installData;

/**
      * @var ConfigBasedIntegrationManager
      */


     private $integrationManager;


    /**
     * @param InstallData $installData
     * @param ConfigBasedIntegrationManager $integrationManager
     */
    public function __construct(InstallData $installData,ConfigBasedIntegrationManager $integrationManager)
    {
        $this->installData = $installData;
         $this->integrationManager = $integrationManager;
    }



    /**
     * {@inheritdoc}
     */
    public function apply(ModuleContextInterface $context)
    {
        $this->installData->install(null, $context);
  $this->integrationManager->processIntegrationConfig(['testIntegration']);
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public static function getVersion()
    {
        return '1.0.0';
    }
}

In the line: $this->integrationManager->processIntegrationConfig(['testIntegration']);, the testIntegration have to refer to your etc/integrations/config.xml file, also the integration name value have to be the same. Please make sure that the path after namespace for your vendor and module names are changed.

Step 2: Create integration files

The Integration module which is provided by Magento, helps simplify the defining integration process. This module performs the following functions:

  • Manage the 3rd account which connects to Magento.
  • Manage OAuth authorizations and user data.
  • Manage security tokens and requests.

In order to customize your module, multiple XML files need to be created and read through other files to identify the resources which existing Magento modules have access to.

The module customizing process includes two steps:

Define required resources

The etc/integration/api.xml determines the API resources which the integration has access to.

To define the resources which integration needs access to, you can view the permissions defined in the module’s etc/acl.xml file.

Here is an example in which the test integration requires access to the resources in the Sales module:

<integrations>
    <integration name="testIntegration">
        <resources>
            <!-- To grant permission to Magento_Log::online, its parent Magento_Customer::customer needs to be declared as well-->
            <resource name="Magento_Customer::customer" />
            <resource name="Magento_Log::online" />
            <!-- To grant permission to Magento_Sales::reorder, all its parent resources need to be declared-->
            <resource name="Magento_Sales::sales" />
            <resource name="Magento_Sales::sales_operation" />
            <resource name="Magento_Sales::sales_order" />
            <resource name="Magento_Sales::actions" />
            <resource name="Magento_Sales::reorder" />
        </resources>
    </integration>
</integrations>

Pre-configure integration

A configuration file config.xml can be provided optionally, which would allow the integration to be automatically pre-configured with default values. In order to enable this feature, you have to create the config.xml file in the directory etc/integration.

This file will define the API resources which integration can access.

<integrations>
   <integration name="TestIntegration">
       <email></email>
       <endpoint_url></endpoint_url>
       <identity_link_url></identity_link_url>
   </integration>
</integrations>

| Element | Description | |——————————|——————————————————————————————————————————————————————————————————————————————————————————————————| | integrations | One or various integration definitions are contained. | | integration name=”” | It is used to define an integration. The name has to be specified. | | email | It is an email that you can use to associate with the integration. | | endpoint_url (Optional) | It is the URL where OAuth credentials can be sent when using OAuth for token exchange. Using https:// is strongly recommended. View OAuth-based authentication for more details. | | identity_link_url (Optional) | The URL which redirects the user to link their third-party account with the Magento integration. |

Step 3: Install module

Next step to create integration module in Magento 2 is installation. To install your module, following these steps:

  1. Update the Magento database schema and data by running the command: bin/magento setup:upgrade
  2. Generate the new code by running the command: bin/magento setup:di:compile
  3. Clean the cache by running the command: bin/magento cache:clean

Step 4: Check integration

In this step, you can check your integration by loggin into Magento and then go to System > Extensions > Integrations. The integration will be displayed in the grid.

Step 5: Integrate with application

Before activating your integration in Magento, you have to create two pages on your application which are used to handle OAuth communications.

  • The location which is specified in the identity_link_url parameter has to point to a page that could handle login requests.
  • The location which is specified in the endpoint_url parameter has to be able to process OAuth token exchanges.

Login page

A pop-up login page for the third-party application will be displayed when you click on the Activate button in Admin. Values for oauth_consumer_key and success_call_back parameters are sent by Magento. The value for oauth_consumer_key must be store and tie to the login ID. The success_call_back parameter can be used to return control back to Magento.

Call back page

The callback page has to have the ability to perform the below tasks:

  • Receive an initial HTTPS POST which is sent by Magento when the integration is activated. This post includes the Magento store URL, the OAuth consumer key, an oauth_verifier, and the OAuth consumer secret. The consumer key and also secret will be generated when you create Integration Module.
  • Ask for a request token. A request token is a temporary token that is used to exchange for an access token. The below API can be used to get a request token from Magento:
    POST /oauth/token/request
    
  • Parse request token response. An oauth_token and oauth_token_secret are included in the response.

  • Ask for an access token. The request token has to be used to exchange for an access token. The below API can be used to get a request token from Magento:
    POST /oauth/token/access
    
  • Parse access token response. An oauth_token and oauth_token_secret are included in the response. These values will be different than those which are provided in the request token response.

  • Save access token and other OAuth parameters. You must specify the access token and OAuth parameters in the Authorization header in each call to Magento.

Conclusion

Finding it too technical and complicated to understand? Our experts can help you create Integration Module in Magento 2 quickly and efficiently!

By integrating your website with a number of third-party apps, we’ll help you leverage your capabilities, discover new business opportunities, improve customer experience, and boost sales. With nearly a decade of experience in this field, we’ve helped a number of clients successfully integrate their stores with other platforms.

Besides, our Magento support service will answer and address relevant issues even after 2 months and help you get the most out of it. We want to make sure that you’re satisfied with the results.

Contact us for free consultations now!

CONTACT OUR API INTEGRATION EXPERTS

Related posts:

Magento 2 Module development

Create Magento 2 integration: Manually and Programmatically

Enable/Disable Magento 2 Module

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.
x