Php

Consuming Web Services with PHP SoapClient and Laravel

This Laravel/Lumen tutorial help to consume SOAP request using the PHP SOAP client and laravel, one of the most popular PHP frameworks. I am using PHP soap libs to consume soap requests and send JSON responses using Rest Service.

Web services have become an essential component of modern web applications, enabling seamless integration between different systems and applications.

What’s SOAP WebService

Web services can be accessed using various protocols, including RESTful API, SOAP, and XML-RPC. SOAP (Simple Object Access Protocol) is a widely used protocol for building web services that use XML messages to exchange information between different systems.

SOAP offers a standardized way of communication and supports a wide range of data types, making it a popular choice for enterprise-level web services.

Understanding PHP SoapClient

PHP SoapClient is a built-in PHP class that provides a simple and easy-to-use interface for consuming SOAP-based web services.

Simple SOAP Request with PHP SoapClient

Let’s take a simple example of making a SOAP request using PHP’s SoapClient. Suppose that we have a SOAP service endpoint that returns weather data via a method called getWeather.

<?php

$wsdl = "http://example.com/weather-service?wsdl";

$options = [
    'trace' => 1,
    'exceptions' => true,
];

$client = new SoapClient($wsdl, $options);

try {
    $response = $client->getWeather(['city' => 'New York']);
    var_dump($response);
} catch (SoapFault $fault) {
    echo "Error: " . $fault->getMessage();
}

Consume Webservice Using Laravel and PHP SoapClient

Laravel’s built-in support for consuming web services using SoapClient makes it easy to integrate with SOAP-based APIs.

Sometimes, We have a SOAP calls to access resources at that time we need to create a SOAP request to access data.

We will create a Restful service to access the soap service call using the controller method.

We will use the following files,

  • routes.php : This file is used to create a rest route for soap service.
  • Http/Controllers/CurrencyController.php: This file is responsible for creating the controller method of the route.
  • app/Service/CurrencyService.php: This file is used to create a service method to access SOAP api.

You can also check other recommended tutorials of Lumen/Laravel,

We need to enable php_soap and open_ssl module into php.ini file, if You haven’t enabled it yet, please follow the below steps to enable php-soap libs.

we can verify this by checking the list of loaded PHP extensions using the phpinfo() function.

<?php
phpinfo();
?>

How to enable php-soap in windows

Please enable PHP soap libs from php.ini file by uncommenting below the line,

extension=php_soap.dll

After that restart the Xampp or Wamp server.

Related Post

How to enable php-soap in Linux Ubuntu

We need to install the package by run below command.

sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service

Let’s Start to Integrate SOAP with Laravel

Step 1: Included SOAP module into the Service CurrencyService.php file.

use SoapClient;

Step 2: Create a client method to access Soap WSDL in the service file.

private function _client($F5srv) {
    $opts = array(
     'ssl' => array(
       'verify_peer' => false,
       'verify_peer_name' => false,
       'allow_self_signed' => true
     )
   );

    $context = stream_context_create($opts);
    $wsdl = "wsdl path";

    try {
      $this->client = new \SoapClient($wsdl, array(
       'stream_context' => $context, 'trace' => true,
       'login' => username, 'password' => password)
    );
    
    return $this->client;
    }

    catch ( \Exception $e) {
      Log::info('Caught Exception in client'. $e->getMessage());
    }
  }

You need to replace the WSDL path with your WSDL URL and change username/password credentials, if WSDL wants authorization using credentials otherwise skip.

Step 3: Created service method to consume soap method with params into CurrencyService.php file.

public function getCurrency($params) {
    $this->client = $this->_client($params['config']);

    try {
      $result = $this->client->Currency($parms);
      return $result;
    }

    catch (\Exception $e) {
     Log::info('Caught Exception :'. $e->getMessage());
         return $e;       // just re-throw it
       }
 }

It would be best if you replaced 'Currency' method name with your method name.

Step 4: Create one HTTP Post route entry into routes.php file.

$app->post('get_currency', 'CurrencyController@getCurrency');

Step 5: Create a method getCurrency into CurrencyController.php file.

public function getCurrency(Request $request) {
      $response = array();
      $parameters = $request->json()->all();
      
      $rules =  array(
            'name'    => 'required'
        );
        
        $messages = array(
            'name.required' => 'name is required.'
        );
      
      $validator = \Validator::make(array('name' => $parameters['name']), $rules, $messages);

      if(!$validator->fails()) {
            $response = $this->currencyService->getCurrency($parameters);
            return response;
         } else {
            $errors = $validator->errors();
            return response()->json($errors->all());
         }
      
 }

You need to register the service provider in the app.php file or use the service as a namespace in the controller file to access the service currencyService class method into the above controller method.

Integrating SOAP in Laravel Using artisaninweb/laravel-soap

Laravel provides a package artisaninweb/laravel-soap to consume web services using the SoapClient.

Installing Laravel SoapClient Package

We can install artisaninweb/laravel-soap package by Composer as follows:

composer require artisaninweb/laravel-soap

Publish the package configuration

We can publish a package configuration file to customize the SoapClient settings by running the following command:

php artisan vendor:publish --provider="Artisaninweb\Soap\SoapServiceProvider"

This command generates a soap.php file in the config directory.

SOAP Requests in Laravel

You can now easily make SOAP requests within your Laravel application.

<?php

use Artisaninweb\Soap\Facades\Soap;

class CurrencyController extends Controller
{
    public function convertCurrency($amount, $fromCurrency, $toCurrency)
    {
        $response = Soap::to('http://example.com/currency-service?wsdl')
            ->call('convertCurrency', [
                'amount' => $amount,
                'fromCurrency' => $fromCurrency,
                'toCurrency' => $toCurrency,
            ]);

        return response()->json($response);
    }
}

We make use of the artisaninweb/laravel-soap package’s Soap facade. The call method starts the SOAP request, while the to method provides the WSDL URL.

Conclusion

We have learned that consuming web services with PHP’s SoapClient, whether in plain PHP or within a Laravel application. We have used currency API to get details from SOAP.

Tags: php-soap

View Comments

  • hi sr. I have a doubt. You said that we have to put the file CurrencyService.php in app/Service/CurrencyService.php but the Service folder is no longer used since version 5.1 of laravel. Then where should I put this file if in my version of laravel 5.4 this folder does not exist?? Thanks in advance

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories