Process SOAP Headers in PHP

2019-07-04 12:10发布

I am building (in PHP) a SOAP server that is configured by its WSDL to accept messages that look like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://my.awesome.namespace/">
    <SOAP-ENV:Header>
        <ns1:Header>
            <ns1:APIKey>E4C5BDE0-48DC-543C-1CA3-8E55C63F8E60</ns1:APIKey>
            <ns1:SiteID>111</ns1:SiteID>
        </ns1:Header>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <ns1:Heartbeat>
            <ns1:Message>Hello world.</ns1:Message>
        </ns1:Heartbeat>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I had no problem getting my SOAPServer to process Heartbeat messages - $server->addFunction("Heartbeat"); works fine. I want, however, to be able to process the contents of the <ns1:Header> enclosure - so I can validate the API key and Site ID to make sure they are what they should be.

I looked here, (and of course elsewhere) but the responder seems to have missed the point of the question. Does anyone know how I can access the header element to validate? Do I add a function for Header the way I would a method in the body? ($server->addFunction("Header");?)

Thanks very much in advance.

1条回答
虎瘦雄心在
2楼-- · 2019-07-04 12:22

Found it! Here's what you do.

Create your SOAP server:

$server = new SoapServer($your_wsdl,$any_options);
$server->setClass($name_of_your_class);
$server->handle($location_of_request_data);

The class named in $name_of_your_class, in addition to containing functions for each service defined in $your_wsdl, should also contain a function named for whatever you have in your <SOAP-ENV:Header> tag enclosure. I have <ns1:Header>, so my function is named Header. Put whatever logic you need in there. For me, I wanted to validate the API key and site ID, so I created a private variable, and if the API key and site ID are correct, the variable is set to true. All of the other functions in the class check to see if that variable is true before proceeding, and if not, a SOAPFault is thrown.

Hope this helps anyone who comes across this question on Google.

P.S.: For the functions in the class defined in $server->setClass(), don't forget that they must accept arguments in the order defined in the WSDL. That tripped me up.

Good luck to all other PHP/SOAP developers - seems like we all need it.

Edit/P.P.S.: For whatever reason, simply calling $server->addFunction("Header") did not work for me - I tried that first before I tried the setClass approach above. Just a heads-up to folks.

查看更多
登录 后发表回答