使用 php 在 non-wsdl soap 客户端中设置 xml rquest header

Set xml rquest header in non-wsdl soap client using php

我正在尝试使用 php 进行 non-wsdl SOAP 客户端调用。我的代码是这样的:

try {
$URL = 'http://example.com/webservices/security/accesscontrol.asmx';

$sc = new SoapClient(null, array(
  'location' => $URL,
  'uri' => 'http://example.com/webservices/security/',
  'trace' => 1
  ));

$usertoken = array('UserNameToken' =>
array(
  'UserName' => 'test',
  'Password' => 'test123'
));

$header = new SoapHeader('http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', $usertoken);

$sc->__setSoapHeaders($header);

$test = $sc->__soapCall("AuthenticateClient",
  array(),
  array('soapaction' => 'http://example.com/webservices/security/AuthenticateClient')
);

如果我调试并看到 xml 的最后请求 header 部分,它看起来像这样:

<SOAP-ENV:Header>
    <ns2:Security>
        <item><key>UserNameToken</key><value><item><key>UserName</key><value>test</value></item><item><key>Password</key><value>test123</value></item></value></item>
    </ns2:Security>
</SOAP-ENV:Header>

但是如果我使用 wsdl 文件,xml header 看起来像这样:

<SOAP-ENV:Header>
    <ns2:Security>
        <ns2:UserNameToken>
            <ns2:UserName>test</ns2:UserName>
            <ns2:Password>test123</ns2:Password>
        </ns2:UserNameToken>
    </ns2:Security>
</SOAP-ENV:Header>

如何使用 non-wsdl SOAP 客户端调用使 header 部分像上面那样?因为它不起作用并给出由 "if either the UserName Token or the UserName was not provided in the AuthenticateClient Soap Header Request"

引起的错误

在此先感谢您的帮助。

请注意,我有意更改了 URL 和密码,因为我不能透露它们。

你可以手动创建header的一部分,然后插入到SoapHeader中,尝试这样做:

    $URL = 'http://example.com/webservices/security/accesscontrol.asmx';

    $soapClient = new SoapClient(null, array(
        'location' => $URL,
        'uri' => 'http://example.com/webservices/security/',
        'trace' => 1
    ));

    $headerPart = '
            <SOAP-ENV:Header>
                <ns2:Security>
                    <ns2:UserNameToken>
                        <ns2:UserName>DASKO</ns2:UserName>
                        <ns2:Password>welcome1</ns2:Password>
                    </ns2:UserNameToken>
                </ns2:Security>
            </SOAP-ENV:Header>
    ';

    $soapVarHeader = new SoapVar($headerPart, XSD_ANYXML, null, null, null);

    $header = new SoapHeader(
        'http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', // Namespace - namespace of the WebService
        'Security',
        $soapVarHeader,
        false // mustunderstand
    );

    $soapClient->__setSoapHeaders($header);