What can we help you with?

If you are interested in finding out more about how we can help your organization, please provide your details and project requirements. We'll get back to you soon.

Magento 2 SOAP API

Magento

Magento development supports both REST and SOAP API services to work with the Magento system.

There are three types of API users –

  1. Guest Users: These users can access or process the data which is publically accessible
  2. Admin Users: These users can access all the data and perform all the operations in the systems
  3. Customers: These users can access or process the data for which they are authorized or given access also they can access the data which are public similar to guest users.

About the SOAP API services

The SOAP API provides the ability to communicate with web applications over the HTTP as it is supported by all internet browsers and servers.

The applications using SOAP API service can be run on different Operating systems and different languages on various platform.

Magento SOAP API provides three types of authentication for API requests.

  1. Token based:

    Token is an electronic key which allows users to access the API and Magento development is having three types of tokens as below.

    Integration:  It allows only those resources for which the access rights are given by the admin. This kind of tokens never expires. It can be manually destroyed/revoked. To create the integrations token follow the below steps –

    Step 1: Login as Admin and go to System & Integrations.

    Step 2: Click on “Add New Integration”.

    Step 3: Provide a unique name for the integration in the Name field. Then enter the admin password in the Password field.

    Step 4: Go to the API tab and select the Magento resources which you want to allow access for the integration. You can choose all resources, or opt a custom list.

    Step 5: Click on the “Save” button to save and update the information.

    Step 6: Now from the integration’s listing page click on the “Activate” link for the newly created integration.

    Step 7: Now in the dialog box Click on “Allow” and a dialog box as displayed below will be opened which is displaying the generated tokens and keys for the Integration created.

    1. Integration token for extension
      • Admin: These are the separate tokens for the admin users and customers provided separately by Magento. It allows accessing the data to which the admin is given the access rights. Below is the call to get the tokens.
      • For admin – integrationAdminTokenServiceV1
        Lifetime of this type of token is 4 hours.

      • Customer: It allows only those data to which they have self-permission means only that data can be access which is allowed to customer role/users. Below is the call to get the token.

      For customers – integrationCustomerTokenServiceV1
      This type of token will be expired in 1 hour.

      Magento Developers can change the expiry time of the above token from admin by opting Configuration > Services > OAuth > Access Token Expiration.

      There is a built-in cron job in the Magento that runs hourly and deletes all the expired tokens.

      Example of how to create SOAP API using token-based authentication:

      $request = new SoapClient("http://tatvamagento2.com/index.php/soap/?wsdl&services=integrationAdminTokenServiceV1", array("soap_version" => SOAP_1_2));
      $token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array("username"=>"tatvaadmin", "password"=>"tatva123"));
      $header = array(
                  'http'=>array(
                      'header' => 'Authorization: Bearer '.json_decode($token->result)
                  )
              );
      $wsdlUrl = 'http://tatvamagento2/soap/default?wsdl&services=tatvawsdlfirst';
      $context = stream_context_create($header);
      $soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'context' => $context]);
      $soapResponse = $soapClient->__getFunctions();
    2. Session Based:

      In this, the access rights (credentials) are being saved in the session of the browser and the Magento API will use that session data to allow the requested resources. It also allows access to the resources for which the admin have given access rights manually.

    3. OAuth Based (Third Party authentication)

      OAuth is a standard API authentication tool for the security purpose and Magento SOAP API service allows access to the system resources to third-party extensions with accesses given by resource owners.

      To get more information about OAuth, refer this link: https://tools.ietf.org/html/rfc5849

      In Magento, if any third party extension is added with using OAuth authentication method is called integration and it manages the resources which are accessible to the third party extensions. The extension can access all the resources or customized resources which are granted to access.

      Magento SOAP API service creates short-lived tokens for the extensions and these third-party extensions need to provide this token to get the access tokens to access the resources. These access tokens will never be expired unless the customer or merchant revokes the access to the system extension.

      For more details about how the Magento integrates the third party extensions with OAuth Integration please refer the link:
      https://devdocs.magento.com/guides/v2.2/get-started/authentication/gs-authentication-oauth.html

    Use of Magento 2 SOAP API

    In Magento, a WSDL file is generated for every service that is requested. The clients of the API service will use different services to access the resources and for every service, there will be different WSDL files generated.

    The Magento SOAP API uses WSDL 1.2 version which complies with WS-I 2.0 Basic Profile.

    Every Magento SOAP API services are represented with separate Service in the WSDL and each service is s part of a service contract.

    Here the service contract is a set of PHP interfaces which are defined for a module. It includes data interfaces, which preserve data integrity, and service interfaces.

    The service interfaces hide business logic details from service requestors such as controllers, web services, and other modules. The SOAP API services can be bound with different service contracts via configuration files. And we can define the contracts for the services in the WSDL files.

    Below is the example for which we must need to specify the service contracts in the WSDL endpoint URL.

    Service

    WSDL endpoint URL

    Available services

    customer

    http://tatvasoftmagento2/soap?

    wsdl&services=customerV1

    \Magento\Customer\Service\V1\CustomerService

    customer, catalogProduct

    http://magentohost/soap/custom_store?

    wsdl&services=customerCustomerAccountServiceV1,

    catalogProductV2

    \Magento\Customer\Service\V1\

    CustomerAccountServiceInterface, \Magento\Catalog\Service\V2\ProductInterfac

    The WSDL URL follows the following pattern to specify the service rquest:

    http://<magento.host>/soap/<optional_store_code>?wsdl&services=<service_name_1>,<service_name_2>

    The Service version must be provided in the endpoint URL for each service. Using this we can define a service contract between the application and the Magento service provider

    SOAP API service name conversion rules

    Following are the rules to convert the service class in the SOAP service –

    • Always use CamleCase to create the service name
    • Some of the keywords like “Service”, ”Magento”, “Interface” are not allowed as prefix or suffix in the service name.
    • If the module name and the service name is equal then the module name will be omitted.

    Example– If there is a Merchant Service Interface in the Merchant module then the word “Merchant” can be used only once in the service name.

    The service name and its interface name can be defined as below for the above example.

    Original Service Interface Name Service Name
    \Magento\Merchant\Service\V1\MerchantInterface merchantV1
    \Magento\Merchant\Service\V1\MerchantAccountServiceInterface merchantMerchantAccountServiceV1
    \Enterprise\Merchant\Service\V3\Merchant\AddressInterface enterpriseMerchantAddressV3

    Authentication Example

    The Magento SOAP resources can be protected and accessed by using the OAuth access tokens bearer over the HTTP. Here as discussed above the access tokens will be unique and provided to the users of the SOAP services.

    The below example describes how to generate the access token for the Magento SOAP service.

    <?php
    $options = array ('http'=>array ('header' => 'Authorization: Bearer 36849300bca4fbff758d93a3379f1b8e');
    $wsdlUrl = 'http://tatvasoftMagento2.com/soap/default?wsdl=1&services=testMerchantModuleSoapV1';
    $serviceArguments = array ("name"=>”testTatvasoft”);
    $context = stream_context_create ($options);
    $soapClient = new SoapClient ($wsdlUrl, ['version' => SOAP_1_2, 'context' => $context]);
    $soapResponse = $soapClient-> testMerchantModuleSoapV1Item ($serviceArguments); 
    ?>

    The $soapResponse will return the access token of the created service.

    • SOAP API format Example to get Category tree:

    SOAP URL: http://tatvasoftMagento2.com/soap?wsdl_list=1
    WSDL format will be as following –

    SOAP API Format

    Create Role to use API
    • Go to System > User Roles
    • Click on “Add New Role”
    • In the Role Info tab, enter the role name and password
    • In the Role Resources tab select the resources which can be accessed by this role.
    Create User to use API
    • Go to System & All USers
    • Click on “Add New User”
    • In the User Info tab, enter the necessary user data like name, password etc. and select the “This account is” field as Active.
    • In the User Role, select a role for this user.
    • SOAP v1
    $client = new SoapClient ('http://tatvasoftmagento2/magento2/api/soap/?wsdl');
    $session = $client->login ('apiUser', 'apiKey');
    $result = $client->call ($session, 'catalog_category.info', '5');
    var_dump ($result);
    • SOAP v2
    $proxy = new SoapClient ('http:// tatvasoftmagento2/magento19/api/v2_soap/?wsdl');
    $sessionId = $proxy->login ('apiUser', 'apiKey'); 
    $result = $proxy->catalogCategoryInfo ($sessionId, '5');
    var_dump ($result);

    The result will be as show in the below screen.

    Result SOAP API

    For more information please refer to: http://devdocs.magento.com/guides/m1x/api/soap-api-index.html

    Advantages of using Magento 2 SOAP API services

    • The SOAP API Service is an essential building block for developing the distributed applications that exploit functionality published as services over the internet.
    • It introduces extended capabilities to data transfers between Magento 2 and external systems.
    • The only requirement to implement the SOAP APIs is the necessity to formulate and understand SOAP messages.
    • SOAP provides Flexible data transfers from any external systems to Magento 2
    • Fully automated schedules of updates;
    • No need to rely on data transfers;
    • Advanced mapping functionality.

    Magento 2 SOAP characteristics

    • SOAP API service provides messaging protocol layer. The XML based protocol contains three parts as below
      Envelope: It defines the structure of the message and the way to process it. Encoding Rules: It is a set of rules which defines the instances of application-defined data types. Representing Convention: This part represents the procedure calls and responses.
    • Extensibility: This XML based standard can be extended in various systems for the more complicated business cases.
    • Neutrality: The SOAP can be operated over any protocol
    • Independent: It can be communicated and leverage the standard for any programming model or languages.

    Syntax Rules for Magento 2 SOAP

    • The SOAP API message must be encoded via XML
    • The SOAP API message must use the SOAP Envelope namespace.
    • The SOAP API message must use the SOAP Encoding namespace.
    • It must not contain a DTD reference
    • It must not include XML Processing Instructions.

    Example:

    ...
    <soap:Envelope
    xmlns:soap="http://www.tatvasoftMagento2.com/2018/05/soap-envelope/"
    soap:encodingStyle="http://www.tatvasoftMagento2.com/2018/05/soap-encoding">
    <soap:Header>
    ...
    </soap:Header>
    <soap:Body>
    ...
    <soap:Fault>
    ...
    </soap:Fault>
    </soap:Body>
    </soap:Envelope>

    Workflow for the SOAP API service run

    Workflow in SOAP API

    The above screen defines how the workflow in the SOAP API request works.

    The process itself serves several purposes. It decodes the incoming SOAP request and then modifies/ transforms it into an invocation of the method. Now, it is time to take the result of the method call and encode it into a SOAP message (which is also the response of the API). Finally, the response can be sent back to the requester.