Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Soap Laravel Package

artisaninweb/laravel-soap

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require artisaninweb/laravel-soap
    

    For Laravel 5.2+, add the service provider and facade alias to config/app.php:

    'providers' => [
        Artisaninweb\SoapWrapper\ServiceProvider::class,
    ],
    'aliases' => [
        'SoapWrapper' => Artisaninweb\SoapWrapper\Facade\SoapWrapper::class,
    ]
    
  2. First Use Case: Define a SOAP service in config/soap.php:

    'services' => [
        'example' => [
            'wsdl' => 'http://example.com/service?wsdl',
            'trace' => true,
            'exceptions' => true,
        ],
    ],
    

    Call the SOAP service in a controller or service:

    $response = SoapWrapper::service('example')->__soapCall('MethodName', [$arg1, $arg2]);
    

Implementation Patterns

Common Workflows

1. Service Configuration

  • Centralized Configuration: Define all SOAP services in config/soap.php for easy maintenance.
    'services' => [
        'payment_gateway' => [
            'wsdl' => env('PAYMENT_GATEWAY_WSDL'),
            'trace' => env('SOAP_TRACE', false),
            'exceptions' => true,
            'options' => [
                'login' => env('PAYMENT_GATEWAY_LOGIN'),
                'password' => env('PAYMENT_GATEWAY_PASSWORD'),
            ],
        ],
    ],
    

2. Service Usage

  • Facade-Based Calls:

    // Call a SOAP method
    $result = SoapWrapper::service('payment_gateway')->Charge([
        'amount' => 100.00,
        'currency' => 'USD',
    ]);
    
    // Handle complex types
    $complexData = [
        'Customer' => [
            '@attributes' => ['id' => '123'],
            'Name' => 'John Doe',
        ],
    ];
    $response = SoapWrapper::service('example')->CreateCustomer($complexData);
    
  • Dynamic Service Binding:

    $serviceName = request()->input('service');
    $response = SoapWrapper::service($serviceName)->__soapCall('Method', [$data]);
    

3. Error Handling

  • Exceptions: Enable exceptions in config to throw SoapFault exceptions.

    try {
        $response = SoapWrapper::service('example')->FaultyMethod();
    } catch (\SoapFault $e) {
        Log::error('SOAP Error: ' . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 500);
    }
    
  • Fallback Logic:

    if (SoapWrapper::service('example')->__getLastRequestHeaders()) {
        // Log request/response for debugging
        Log::debug('SOAP Request:', [
            'headers' => SoapWrapper::service('example')->__getLastRequestHeaders(),
            'response' => SoapWrapper::service('example')->__getLastResponse(),
        ]);
    }
    

4. Integration with Laravel Features

  • Service Container Binding: Bind the SOAP service to the container for dependency injection:

    $this->app->bind('payment.gateway', function ($app) {
        return SoapWrapper::service('payment_gateway');
    });
    
  • Queue Jobs: Offload SOAP calls to queues to avoid timeouts:

    dispatch(new ProcessPaymentJob($orderId));
    
    class ProcessPaymentJob implements ShouldQueue {
        public function handle() {
            $response = SoapWrapper::service('payment_gateway')->Charge($this->paymentData);
            // Process response...
        }
    }
    

5. Testing

  • Mock SOAP Services: Use Laravel's mocking capabilities to test SOAP interactions:
    $this->app->instance('payment.gateway', Mockery::mock([
        'Charge' => ['success' => true],
    ]));
    
    $response = $this->app->make('payment.gateway')->Charge([...]);
    $this->assertTrue($response['success']);
    

Gotchas and Tips

Pitfalls and Debugging

1. WSDL Caching Issues

  • Problem: WSDL caching can cause stale service definitions.
  • Fix: Disable caching during development or clear cache manually:
    SoapWrapper::service('example')->__setLocation('http://updated-wsdl-url');
    SoapWrapper::service('example')->__setUse('literal');
    

2. SOAP Headers and Authentication

  • Problem: Some SOAP services require headers (e.g., OAuth, WS-Security).
  • Solution: Use the options key in config:
    'services' => [
        'secure_service' => [
            'wsdl' => 'http://secure.example.com/wsdl',
            'options' => [
                'stream_context' => stream_context_create([
                    'http' => [
                        'header' => "Authorization: Bearer token123\r\n",
                    ],
                ]),
            ],
        ],
    ],
    

3. Large Payloads and Timeouts

  • Problem: SOAP calls may timeout or fail with large payloads.
  • Fix:
    • Increase PHP timeouts in config/soap.php:
      'options' => [
          'connection_timeout' => 30,
          'execution_timeout' => 60,
      ],
      
    • Use chunking or compression for large requests.

4. Namespace and Complex Type Issues

  • Problem: SOAP responses with complex types may not deserialize correctly.
  • Solution: Manually map responses or use SoapWrapper::service()->__getLastResponse() to inspect raw XML:
    $rawResponse = SoapWrapper::service('example')->__getLastResponse();
    $dom = new \DOMDocument();
    $dom->loadXML($rawResponse);
    // Parse manually if needed
    

5. Facade vs. Direct Instantiation

  • Gotcha: Facade calls are resolved via the service container, while direct instantiation bypasses config.
  • Tip: Prefer the facade for consistency:
    // Good: Uses config/soap.php
    $response = SoapWrapper::service('example')->Method();
    
    // Avoid unless necessary
    $client = new \SoapClient('http://example.com/wsdl');
    

Extension Points

1. Custom SOAP Clients

  • Extend the base SoapWrapper class to add reusable logic:
    class CustomSoapWrapper extends \Artisaninweb\SoapWrapper\Facade\SoapWrapper {
        public static function retry($serviceName, $method, $args, $retries = 3) {
            $lastError = null;
            for ($i = 0; $i < $retries; $i++) {
                try {
                    return parent::service($serviceName)->$method($args);
                } catch (\SoapFault $e) {
                    $lastError = $e;
                    sleep(2 ** $i); // Exponential backoff
                }
            }
            throw $lastError;
        }
    }
    

2. Middleware for SOAP Calls

  • Create middleware to log or transform SOAP requests/responses:
    class SoapLoggingMiddleware {
        public function handle($request, Closure $next) {
            $service = SoapWrapper::service('example');
            $service->__setLocation('http://example.com/wsdl');
            $response = $next($request);
    
            Log::debug('SOAP Request:', [
                'headers' => $service->__getLastRequestHeaders(),
                'response' => $service->__getLastResponse(),
            ]);
    
            return $response;
        }
    }
    

3. Dynamic Service Discovery

  • Load SOAP services dynamically from a database or API:
    $services = DB::table('soap_services')->get();
    foreach ($services as $service) {
        config(['soap.services.' . $service->name => [
            'wsdl' => $service->wsdl_url,
            'options' => json_decode($service->options, true),
        ]]);
    }
    

4. Testing Utilities

  • Create a helper trait for testing SOAP interactions:
    trait SoapTestHelper {
        protected function mockSoapService($serviceName, $methods = []) {
            $mock = Mockery::mock();
            foreach ($methods as $method => $response) {
                $mock->shouldReceive($method)->andReturn($response);
            }
            $this->app->instance("soap.{$serviceName}", $mock);
        }
    }
    

Configuration Quirks

  • Trace Enabled: Setting 'trace' => true in config logs raw SOAP requests/responses to storage/logs/soap.log.
  • Environment Variables: Use .env for sensitive data like WSDL URLs or credentials:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui