PHP实现带身份验证的DHL ELP Web服务连接方法问询
在PHP中通过基础身份认证连接DHL ELP Web服务
你已经能在SOAP UI里完成操作,那迁移到PHP里核心就是搞定身份验证的传递,这里分两种常见情况来处理,对应DHL ELP的两种认证方式:
情况1:HTTP基础认证(SOAP UI里设置了Basic Auth)
如果你的SOAP UI是在Authentication标签下选择了Basic Auth来输入用户名密码,那这属于HTTP层面的认证,PHP里可以通过stream_context给SOAP请求添加Authorization头:
// 替换成你的DHL ELP WSDL地址 $wsdl = 'https://your-dhl-elp-service-url?wsdl'; $username = '你的DHL用户名'; $password = '你的DHL密码'; // 创建包含基础认证头的流上下文 $authContext = stream_context_create([ 'http' => [ 'header' => "Authorization: Basic " . base64_encode("$username:$password") ] ]); // 初始化SOAP客户端,传入上下文 try { $soapClient = new SoapClient($wsdl, [ 'stream_context' => $authContext, 'trace' => true, // 开启调试,方便查看请求/响应 'exceptions' => true ]); // 接下来组装你的请求对象(用你已有的类) $processRequest = new TypeElpProcess(); // 填充Command、Data等其他参数... $processRequest->Command = new TypeCommand(); $processRequest->Command->Name = '你要执行的命令(比如BookShipment)'; // ... 其他参数赋值 // 调用对应的服务方法(替换成实际的方法名,比如Process) $response = $soapClient->Process($processRequest); print_r($response); } catch (SoapFault $e) { echo "请求出错:" . $e->getMessage() . "\n"; // 调试时可以打印最后一次请求的XML echo "请求XML:" . $soapClient->__getLastRequest() . "\n"; }
情况2:SOAP消息体中的Security节点认证
如果你的SOAP UI是在请求的SOAP体里添加了Security节点来传递凭证,那你需要先完善你定义的TypeSecurity类,添加对应的用户名和密码属性(具体字段名要和DHL WSDL定义一致):
// 完善TypeSecurity类,根据WSDL里的字段名调整属性名 class TypeSecurity { public $Username; // 对应WSDL中的用户名字段 public $Password; // 对应WSDL中的密码字段 } // 初始化SOAP客户端(如果不需要HTTP认证,就不用stream_context) $wsdl = 'https://your-dhl-elp-service-url?wsdl'; $soapClient = new SoapClient($wsdl, [ 'trace' => true, 'exceptions' => true ]); // 组装Security对象 $security = new TypeSecurity(); $security->Username = '你的DHL用户名'; $security->Password = '你的DHL密码'; // 组装完整请求 $processRequest = new TypeElpProcess(); $processRequest->Security = $security; // 填充Command、Data等其他参数... $processRequest->Command = new TypeCommand(); $processRequest->Command->Name = 'BookShipment'; // ... 其他参数赋值 // 调用服务方法 try { $response = $soapClient->Process($processRequest); print_r($response); } catch (SoapFault $e) { echo "请求出错:" . $e->getMessage() . "\n"; echo "请求XML:" . $soapClient->__getLastRequest() . "\n"; }
关键提示
- 先确认SOAP UI里的认证方式:查看SOAP UI发送的请求XML,如果Authorization头在HTTP请求头里,就是情况1;如果Security节点在SOAP体里,就是情况2。
- 你的现有代码中
TypeSecurity类是空的,一定要根据DHL提供的WSDL来完善它的属性,字段名必须和WSDL定义完全匹配,否则服务端会识别不到凭证。 - 开启
trace=true后,用__getLastRequest()可以查看PHP发送的XML请求,和SOAP UI里的请求对比,就能快速定位问题。
内容的提问来源于stack exchange,提问作者Sergio
相关产品推荐
相关产品推荐

