Magento 2 APIs by default supports marketing automation, accounting, ERP, CRM, PIM systems.

To enable your third-party services to call the Magento 2 web APIs, you can create an integration programmatically via a custom Magento 2 extension or manually from Magento 2 backend .

In this article, we will provide you with a step-by-step guide to create an integration programmatically in Magento 2.

We will create a module with minimal settings, and specific files for the integration. Then we will install the module, check the integration and complete the integration with the application/system.

Before Getting Started

Make sure that you have a working Magento 2 installation and that all the system requirements are met

Integrations in Magento 2 are managed under Magento_Integration module.

The module for an integration, like any other of your custom modules, should be placed under <magento_base_dir>/app/code/<vendor_name>/<module_name> or <magento_base_dir>/vendor/ folder.
In this tutorial, we will place the source code under <magento_base_dir>/app/code/<vendor_name>/<module_name>

Our module structure under module app/code/<vendor_name>/<module_name> will looks as follow:

  • etc/module.xml
  • etc/integration/api.xml
  • etc/config.xml
  • Setup/InstallData.php
  • composer.json
  • registration.php

Step 1: Create A Skeletal Module

a) Create the module file structure
Under <magento_base_dir>/app/code/<vendor_name>/<module_name>, run :

cd <magento_base_dir>
mkdir -p app/code/<vendor_name>/<module_name>/etc/integration
mkdir -p app/code/<vendor_name>/<module_name>/Setup

b) Define the module configuration file: etc/module.xml 
Create this file etc/module.xml and add this code:

<?xml version="1.0"?>
   <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>
  • name="Vendor1_Module1": is is the module name
  • setup_version="2.0.0": is the version of Magento that the component uses
  • <module name="Magento_Integration"/>: is the “sequence” to be loaded first to avoid a malfunction when a module with integration config is loaded.

c) Add the module’s composer.json file
Composer is a dependency manager for PHP. A composer.json file is useful for the module so that composer can install and update any library the module relies on.

Create this composer.json and add this code:

  {
     "name": "Vendor1_Module1",
     "description": "create integration from config",
     "require": {
        "php": "~7.2.0|~7.3.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\\": ""
        }
     }
  }

 

d) Add a registration.php file
The registration.php file registers the module with the Magento 2 system.

In the module’s root directory, create this file registration.php and add this code :

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor1_Module1',
__DIR__
);

 

e) Add the install file: Setup/InstallData.php
The Setup/InstallData.php is used to installs the integration configuration data into the Magento 2 integration table.

In the module’s root directory, create this file Setup/InstallData.php and add this code :

<?php
namespace Vendor1\Module1\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Integration\Model\ConfigBasedIntegrationManager;
use Magento\Framework\Setup\InstallDataInterface;

class InstallData implements InstallDataInterface
{
    /**
     * @var ConfigBasedIntegrationManager
     */

    private $integrationManager;

    /**
     * @param ConfigBasedIntegrationManager $integrationManager
     */

    public function __construct(ConfigBasedIntegrationManager $integrationManager)
    {
        $this->integrationManager = $integrationManager;
    }

    /**
     * {@inheritdoc}
     */

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->integrationManager->processIntegrationConfig(['TestIntegration']);
    }
}
  • The Setup/InstallData.php above is a sample and requires minor changes to make your Magento 2 integration work.
  • In this line $this->integrationManager->processIntegrationConfig(['testIntegration']); testIntegration must refer to your etc/integration/config.xml, and the integration name value must be the same
  • replace Vendor1\Module1 with your vendor and module names

Here is an example of a minimal etc/integration/config.xml file:

 <integrations>
    <integration name="TestIntegration">
       <email>[email protected]</email>
       <endpoint_url>https://example.com</endpoint_url>
       <identity_link_url>https://example.com/identity_link_url</identity_link_url>
    </integration>
 </integrations>

Step 2: Create Integration Files

Integrations in Magento 2 are managed under Magento_Integration module, which simplifies the process of defining any integration.
This Magento_Integration module automatically performs functions such as: managing the third-party account that connects to Magento 2, managing security tokens and requests, and maintaining OAuth authorizations and user data

The integration files include:

  • etc/integration/api.xml where we define the API resources that the integration has access to
  • etc/integration/config.xml where we pre-configure the integration

a) Define the required resources: etc/integration/api.xml

In the example below, the test integration requires access to the Sales resources.

Create the etc/integration/api.xml with this code:

<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>

Review the permissions defined in each module’s etc/acl.xml file to check which resources an integration needs access to.

b) Pre-configure the integration: etc/integration/config.xml

This etc/integration/config.xml file defines which API resources the integration has access to. It allows to automatically pre-configured the integration with default values.

Note that if you choose to pre-configure the integration, the values cannot be edited from the backend.

To pre-configure, update this file etc/integration/config.xml per your needs. Example of a pre-configure in etc/integration/config.xml

<integrations>
   <integration name="TestIntegration">
       <email></email>
       <endpoint_url></endpoint_url>
       <identity_link_url></identity_link_url>
   </integration>
</integrations>
  • integrations: contains one or more integration definitions
  • <integration name="TestIntegration">: defines an integration. The name must be specified.
  • email: an email to associate with this integration
  • endpoint_url : thee URL where OAuth credentials can be sent when using OAuth for token exchange. This field is optional in the config file. However, it's recommended to use a secure URL there (https://)
  • identity_link_url: the URL that redirects the user to link their 3rd party account with the Magento 2 integration. This field is optional in the config file

Step 3: Install The Module

Go to the Magento 2 root directory, and run this command to install the module, generate the new code, and flush caches

bin/magento module:enable Vendor1_Module1
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento cache:clean

Note that Magento 2 does not prompt to run the compile command in developer mode.

Step 4: Check The Integration

Once the module is installed you can check the integration in the backend.

Login to the backend and go to System > Extensions > Integrations. The integration should be displayed in the grid

API integration grid

If you click on the integration, you can see the detail as configured in the etc/integration/config.xml file

API integration info view

If you click the API tab, you can see the API resources granted to the integration as configured in the etc/integration/api.xml

API integration view

If you activate the integration, the external application/system can start accessing the resources configured above. The way it works is similar to when you create an integration manually from the backend.

Step 5: Integrate With The Application

In order to activate your integration in Magento 2, you need to create two pages (for "identity_link_url" and "endpoint_url") on your application/system to handle the OAuth communications.

  • In this parameter "identity_link_url" you can specify the page that will handle the login requests
  • In this parameter "endpoint_url" you can specify the page that will process OAuth token exchanges

a) Login Page
The login page works as follows:

  • when a merchant clicks the Activate button in the Backend
  • a pop-up login page for the third-party application/system displays
  • the values for oauth_consumer_key and success_call_back parameters are sent by Magento 2. The application must store the value for oauth_consumer_key to tie it to the login ID. You can use the success_call_back parameter to return control back to Magento 2.

b) Callback Page
The callback page is able to perform the following:

  • Receive an initial HTTPS POST that Magento sends when the merchant activates integration
  • Ask for a request token. You can use "POST /oauth/token/request" API to get a request token from Magento 2.
  • Parse the request token response. The response contains an oauth_token_secret and oauth_token
  • Ask for an access token. You can use "POST /oauth/token/access" API to get a request token from Magento 2.
  • Parse the access token response. The response contains an oauth_token and oauth_token_secret with values different than those provided in the request token response.
  • Save the access token and other OAuth parameters. In each call to Magento 2, you need to specify the access token and OAuth parameters in the Authorization header

Conclusion

To works with Magento Integration, it's good to understand how Magento 2 and the external application handle OAuth communications. Also great to have a knowledge of REST, SOAP, and Web API authentication.

If you prefer to create an integration manually from Magento 2 backend, check the complete step-by-step guide to create an API integration manually from Magento 2 backend

We hope you find this helpful. Feel free to share this article.

If you have any issues in integrating Magento 2 with your external application/system, feel free to let us know in the comment field below or contact us

Tags: magento 2 api api