elniño
elniño

Reputation: 121

Add custom http header to each request in php SoapClient

When I use SoapClient I can add custom header (X-Api-Key) in stream context:

$stream = array('stream_context' => stream_context_create(array(
            'http' => array(
                'header' => 'Content-Type: application/soap+xml; charset=utf-8; X-Api-Key: XXXXX'
            ),
        )));

$soapOptions = array(
        'trace'         => 1,
        'exceptions'    => 1,
        'login'         => $this->AUTH_BASIC_USER,
        'password'      => $this->AUTH_BASIC_PASS,
        'soap_version'  => SOAP_1_2,
        'use'           => SOAP_LITERAL,
    );

$client = new \SoapClient($this->SOAP_URL . 'customer?wsdl=single', $soapOptions + $stream);

It works fine. I can check available methods so client object works and can load WSDL.

But if I run any method, X-Api-Key header is missing (and I don't know how to add it) so I'm getting 401 error.

If I check request headers, X-Api-Key is missing:

POST /ws/soap/v1/customer HTTP/1.1\r\n
Host: api-test.XXX.com\r\n
Connection: Keep-Alive\r\n
User-Agent: PHP-SOAP/8.0.3\r\n
Content-Type: application/soap+xml; charset=utf-8; action="create"\r\n
Content-Length: 605\r\n
Authorization: Basic XXX=\r\n

How can I add custom http header to all request on this client object?

Upvotes: 0

Views: 1523

Answers (1)

Sergio Rinaudo
Sergio Rinaudo

Reputation: 2363

Try to use "\r\n" as separator in your 'header' key:

Your current value

Content-Type: application/soap+xml; charset=utf-8; X-Api-Key: XXXXX

should be

Content-Type: application/soap+xml\r\ncharset=utf-8\r\nX-Api-Key: XXXXX

Upvotes: 1

Related Questions