Php soapclient как подключить

Класс SoapClient

Введение

Класс SoapClient представляет собой клиента для серверов » SOAP 1.1, » SOAP 1.2. Он может использоваться в режиме с WSDL или без него.

Обзор классов

Содержание

User Contributed Notes 19 notes

When you need to connect to services requiring to send extra header use this method.

Here how we can to it with PHP and SoapClient

$devKey = «» ;
$password = «» ;
$accountId = «» ;

CAUTION:
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url. I kept getting a 400 Bad Request back from the remote host. It was receiving the proxy url as the SNI host. In order to get around this I had to explicity set the SNI host to the domain I was trying to reach. It’s apparently the issue outlined in this bug:

You need to redefine the soapClient class and force the port in each call.

when they want to pass variables into the http header that is how it is done:

[ ‘http’ ][ ‘header’ ] = «User-Agent: PHP-SOAP/5.5.11\r\n» ;

There is a known bug with some versions of Xdebug which can cause SoapClient to not throw an exception but instead cause a fatal error.

Surround the SoapClient call with xdebug_disable(); and xdebug_enable(); to work around this problem.

When you get errors like:
«Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in»
after a few (time intensive) SOAP-Calls, check your webserver-config.

Sometimes the webservers «KeepAlive»-Setting tends to result in this error. For SOAP-Environments I recommend you to disable KeepAlive.

Hint: It might be tricky to create a dedicated vhost for your SOAP-Gateways and disable keepalive just for this vhost because for normal webpages Keepalive is a nice speed-boost.

If the XML have identities with same name in different levels there is a solution. You don´t have to ever submit a raw XML (this PHP SOAP object don´t allows send a RAW XML), so you have to always translate your XML to a array, like the example below:

//Translate the XML above in a array, like PHP SOAP function requires
$myParams = array(‘firstClient’ => array(‘name’ => ‘someone’,
‘adress’ => ‘R. 1001’),
‘secondClient’ => array(‘name’ => ‘another one’,
‘adress’ => »));

Under IIS and PHP 7, when creating an new SoapClient, it will through an internal 500 error.

READ  Телефон говорит кто звонит андроид как подключить

This could be caused by invalid permissions to the wsdl cache directory when using ‘cache_wsdl’=>WSDL_CACHE_DISK or WSDL_CACHE_BOTH.

This worked for me:
try <
$arrContextOptions=array(«ssl»=>array( «verify_peer»=>false, «verify_peer_name»=>false,’crypto_method’ => STREAM_CRYPTO_METHOD_TLS_CLIENT));

Exception Error!

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.

To make an HTTPS call with a client certificate, you can do it this way:

——BEGIN RSA PRIVATE KEY——
MIICXAIBAAKagQC1N27Ilb9pWil2NaX2qM8FquXBXK5T1AydOv7sCotsc8MAwbi7
. (snip).
wAiOCD4K9TyMS76pIS8UyfJl/oIrn7EF24BUpaUfsh8=
——END RSA PRIVATE KEY——
——BEGIN CERTIFICATE——
MIIC/zCCAmigAwIBAgIEAIl1JzANBgkqhkiG9w0BAQQuADBQMQswCQYxVQQGEaJV
. (snip).
eSPds1hLKYSg0bd3uI7LhaDLOC1PPgb77sYe/uYkUWuHBzllts5x/pfue0zaIBKG
Omjy
——END CERTIFICATE——

2) Reference your certificate in the creation of the SOAP client, like this:

$protected_url = «https://my-server/?wsdl»;
$my_cert_file = «/my/path/to/mycert.pem»;

slow SOAP servers.
As for the KeepAlive, if creating a new separate vhost for the soap api is not possible, you can add this to your existing vhost: BrowserMatch «^PHP-SOAP» nokeepalive
where PHP-SOAP is the agent name of your soap client, if you dont know what agent name your client use, just checkout the access.log of your apache.

If you want to connect to a server that only supports SSLv2/3 and/or TLS 1.0 (no TLS 2 or 3), tell the SOAP client if you get a connection error by setting the appropriate stream context:
= array(
‘ssl’ => array( ‘ciphers’ => ‘RC4-SHA’ )
);

This one drove me nuts. if you are connecting to a web service run on Cassini, (Visual Studio’s web server) from php, you may not be able to call web service functions or load a WSDL out-of-the-box.

My set up is that I am using xampp on my windows development machine, and also using Visual Studio’s built in web-server. I built a web service in visual studio. I wrote a simple PHP script, running under xampp, to access this service, so the two projects can ‘talk’ to each other. What I found was the WSDL was never loaded.

So I moved the WSDL local to the PHP file and accessed it directly. Still no calls. Turns out, PHP’s SoapClient seems to have a problem with ‘localhost’ as a web service endpoint. So I hand-edited the web service endpoint URL to read 127.0.0.1 instead of localhost, and Voila! Web Service calls work:

I got the following error when trying to load the WSDL file:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: ‘MessageName’ already defined

I resolved it by loading the WSDL in SoapUI, right-clicking and selecting «Export definition». The WSDL that then got created worked fine. Hope this helps somebody.

READ  Как подключить хайвей 3гб на билайне

Well, this example works fine:

when they want to pass variables into the http header that is how it is done:

[ ‘http’ ][ ‘header’ ] = «User-Agent: PHP-SOAP/5.5.11\r\n» ;

Источник

Работа с веб-серверами на php посредством SOAP

Не буду останавливаться на вопросе, что такое веб-сервисы и зачем они нужны. В сети очень много статей на эту тему. Просто постараюсь вкратце показать, каким простым способом возможно создание клиента к любому веб-сервису на php.

Для использования SOAP в php необходимо подключить модуль SOAP (входит в дистрибутив php5). Под windows это делается просто – необходимо дописать (именно дописать, так как эта строка там не просто закомментирована, она отсутствует вообще) в php.ini:
extension=php_soap.dll

Не забудьте перезапустить сервер, если php у вас установлен как модуль.

Создание SOAP-клиента по WSDL-документу

Создание SOAP-клиента обычно происходит по WSDL-документу, который представляет собой XML-документ в определенном формате, полностью описывающий тот или иной веб-сервис. За подробностями по поводу WSDL – отправляю Вас на сайт консорциума W3C — www.w3.org/TR/2005/WD-wsdl20-soap11-binding-20050510.

Главное же, что необходимо знать для того, чтобы построить клиента к веб-сервису – это знать URL его WSDL-документа.
Для примера возьмем веб-сервис «Currency Exchange Rate» от xmethods.com. Адрес этого веб-сервиса, который позволяет получать курсы валют в режиме онлайн — www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl.

Второй важный момент – из описания веб-сервиса необходимо получить информацию о том, какие методы этот сервис предоставляет, и какие параметры мы должны передавать ему в качестве входных значений (очень похоже на вызов обычной функции php или метода класса). Обычно эта информация содержится в описании сервиса на его сайте. Наш веб-сервис для получения курса валют предоставляет метод getRate(), которому в качестве аргументов передаются коды валют.

И последнее – важно знать, что ожидать в качестве ответа: сколько значений, какого типа и т.п. Это также можно получить из описания.
А в результате код получается очень простым и компактным, почти элементарным:

Как видно из кода в конструктор класса SoapClient необходимо передать URL WSDL-документа и получить объект для работы с нужным веб-сервисом. Затем вызывается метод этого объекта, имя которого совпадает с именем самого метода веб-сервиса. Возвращает же этот метод желаемый нами результат.

Итак, этот простой пример иллюстрирует нам принцип построения SOAP-клиента для веб-сервисов на php. Однако в реальном приложении еще о многом придется позаботиться, в частности о том, что в момент обращения к веб-сервису он может быть временно недоступен или возвращать ошибку. Явно напрашивается использование блока try/catch/throw 🙂

Источник

SoapClient::SoapClient

SoapClient::SoapClient — Конструктор SoapClient

Описание

Список параметров

Опции style и use используются только в не-WSDL режиме. В режиме WSDL они поступают из WSDL-файла.

READ  Как через спутниковый ресивер подключить интернет

Опция compression позволяет использовать сжатие запросов и ответов HTTP SOAP.

Опция encoding определяет внутреннюю кодировку. Опция не меняет кодировку SOAP-запросов (она всегда utf-8), но преобразует строки в нее.

Опция exceptions принимает логическое значение, определяющее, будут ли SOAP-ошибки бросать исключения типа SoapFault.

Опция connection_timeout определяет тайм-аут в секундах для соединения с SOAP-сервисом. Опция не устанавливает тайм-аут для сервисов с медленными ответами. Для ограничения времени ожидания вызовов используется default_socket_timeout.

Ошибки

Исключение SoapFault будет выбрасываться, если wsdl URI не может быть загружен.

Примеры

Пример #1 Пример использования SoapClient::SoapClient()

= new SoapClient ( «some.wsdl» );

User Contributed Notes 54 notes

It took me longer than a week to figure out how to implement WSSE (Web Service Security) headers in native PHP SOAP. There are no much resource available on this, so thought to add this here for community benefit.

Step1: Create two classes to create a structure for WSSE headers

= 1111 ;
$password = 1111 ;

//Check with your provider which security name-space they are using.
$strWSSENS = «http://schemas.xmlsoap.org/ws/2002/07/secext» ;

//Third parameter here makes ‘mustUnderstand=1
//Forth parameter generates ‘actor=»http://abce.com»‘
?>

Step9: Create object of Soap Client

Do note that *contrary* to the ssl context option (http://php.net/manual/en/context.ssl.php#context.ssl.local-pk), `local_pk` is NOT a valid option. For the `local_cert` option, you should combine the private key with the certificate file.

Alternatively, if you do want to keep the private key and certificate file separate, you can create a stream context and pass that as the `context` option:

As noted in the bug report http://bugs.php.net/bug.php?id=36226, it is considered a feature that sequences with a single element do not come out as arrays. To override this «feature» you can do the following:

$x = new SoapClient($wsdl, array(‘features’ =>
SOAP_SINGLE_ELEMENT_ARRAYS));

The documentation is wrong (version 7.1.12): A SoapFault exception will be thrown if the wsdl URI cannot be loaded.

CAUTION:
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url. I kept getting a 400 Bad Request back from the remote host. It was receiving the proxy url as the SNI host. In order to get around this I had to explicity set the SNI host to the domain I was trying to reach. It’s apparently the issue outlined in this bug:

This doesn’t seem to be documented, but when you want to use compression for your outgoing requests, you have to OR with the compression level:

Источник

Как подключить и установить...
Adblock
detector