programing

SoapClient 클래스를 사용하여 PHP SOAP 호출을 발신하는 방법

luckcodes 2023. 1. 31. 21:16

SoapClient 클래스를 사용하여 PHP SOAP 호출을 발신하는 방법

PHP 코드 작성에 익숙하지만 객체 지향 코딩은 잘 사용하지 않습니다.(클라이언트로서) SOAP와 대화해야 하는데 구문을 제대로 찾을 수 없습니다.SoapClient 클래스를 사용하여 새 연결을 올바르게 설정할 수 있는 WSDL 파일이 있습니다.그러나 실제로 올바른 전화를 걸어 데이터를 반환받을 수 없습니다.다음의 (간소화된) 데이터를 송신할 필요가 있습니다.

  • 연락처 아이디
  • 담당자명
  • 개요

WSDL 문서에는 2개의 기능이 정의되어 있습니다만, 필요한 기능은 1개 뿐입니다(이하 First Function).다음은 사용 가능한 기능 및 유형에 대한 정보를 얻기 위해 실행하는 스크립트입니다.

$client = new SoapClient("http://example.com/webservices?wsdl");
var_dump($client->__getFunctions()); 
var_dump($client->__getTypes()); 

출력은 다음과 같습니다.

array(
  [0] => "FirstFunction Function1(FirstFunction $parameters)",
  [1] => "SecondFunction Function2(SecondFunction $parameters)",
);

array(
  [0] => struct Contact {
    id id;
    name name;
  }
  [1] => string "string description"
  [2] => string "int amount"
}

데이터를 사용하여 First Function에 전화를 걸려고 합니다.

  • 연락처 ID: 100
  • 담당자 이름: John
  • 일반 설명: 배럴 오브 오일
  • 금액: 500

올바른 구문은 무엇입니까?저는 여러 가지 방법을 시도해 보았지만 비누 구조가 꽤 유연해 보여서 이것을 하는 방법은 매우 많습니다.설명서에서도 알아내지 못했어...


업데이트 1: MMK에서 테스트한 샘플:

$client = new SoapClient("http://example.com/webservices?wsdl");

$params = array(
  "id" => 100,
  "name" => "John",
  "description" => "Barrel of Oil",
  "amount" => 500,
);
$response = $client->__soapCall("Function1", array($params));

이런요. '하다, 하다, 하다.Object has no 'Contact' property의 알 수getTypes() 이.struct라고 하는Contact가 포함되어 있음을 명확히 할 것 좋을까요?Contact는 어떻게 해야 할까요?

업데이트 2: 이 구조도 시도해 보았습니다만, 같은 에러입니다.

$params = array(
  array(
    "id" => 100,
    "name" => "John",
  ),
  "Barrel of Oil",
  500,
);

그 외:

$params = array(
  "Contact" => array(
    "id" => 100,
    "name" => "John",
  ),
  "description" => "Barrel of Oil",
  "amount" => 500,
);

두 경우 모두 오류:개체에 '연락처' 속성이 없습니다.

이게 네가 해야 할 일이야.

그 상황을 재현하려고 했는데...


  • 이 예에서는 를 작성했습니다. Service(를 웹 서비스(WS)WebMethod라고 하는Function1하다

기능 1(연락처, 문자열 설명, int 양)

  • 서 ★★★★★Contact은 Getters set setSetters의 입니다.id ★★★★★★★★★★★★★★★★★」name당신 경우처럼요

  • 는 다운로드 할 수 있습니다.NET 샘플 WS:

https://www.dropbox.com/s/6pz1w94a52o5xah/11593623.zip


암호.

PHP측에서 필요한 것은 다음과 같습니다.

(테스트 완료 및 동작)

<?php
// Create Contact class
class Contact {
    public function __construct($id, $name) 
    {
        $this->id = $id;
        $this->name = $name;
    }
}

// Initialize WS with the WSDL
$client = new SoapClient("http://localhost:10139/Service1.asmx?wsdl");

// Create Contact obj
$contact = new Contact(100, "John");

// Set request params
$params = array(
  "Contact" => $contact,
  "description" => "Barrel of Oil",
  "amount" => 500,
);

// Invoke WS method (Function1) with the request params 
$response = $client->__soapCall("Function1", array($params));

// Print WS response
var_dump($response);

?>

모든 것을 테스트하고 있다.

  • 하면.print_r($params)WS 、 WS 、 WS 、 음 ws음음음 ws ws ws ws ws 가 ws ws ws ws ws ws 。

어레이 ( [연락처] => 연락처 객체 ([id] => 100 [name] => John )[설명] => 배럴오일 [금액] => 500 )

  • 디버깅했을 때NET 샘플 WS 다음을 입수했습니다.

여기에 이미지 설명 입력

아시겠지만)Contactnull정상적으로 이루어졌음을 의미합니다.)PHP측에서 PHP측에서 요청이 정상적으로 되었습니다.)

  • 에서의 응답.NET 샘플 WS는 예상대로 PHP 측에서 받은 것입니다.

object(stdClass)[3] public 'Function1Result' => 문자열 '요청 세부 정보! ID: 100, 이름: John, 설명: 오일 배럴, 양: 500'(길이=98)


SOAP 서비스는 다음과 같이 사용할 수도 있습니다.

<?php 
//Create the client object
$soapclient = new SoapClient('http://www.webservicex.net/globalweather.asmx?WSDL');

//Use the functions of the client, the params of the function are in 
//the associative array
$params = array('CountryName' => 'Spain', 'CityName' => 'Alicante');
$response = $soapclient->getWeather($params);

var_dump($response);

// Get the Cities By Country
$param = array('CountryName' => 'Spain');
$response = $soapclient->getCitiesByCountry($param);

var_dump($response);

이것은 실제 서비스의 예이며, URL이 업 상태일 때 동작합니다.

http://www.webservicex.net 가 다운되었을 경우에 대비해서.

다음은 W3C XML Web Services의 에서 웹 서비스를 사용하는 다른 입니다.링크에 대한 자세한 내용은 이쪽에서 확인할 수 있습니다.

<?php
//Create the client object
$soapclient = new SoapClient('https://www.w3schools.com/xml/tempconvert.asmx?WSDL');

//Use the functions of the client, the params of the function are in
//the associative array
$params = array('Celsius' => '25');
$response = $soapclient->CelsiusToFahrenheit($params);

var_dump($response);

// Get the Celsius degrees from the Farenheit
$param = array('Fahrenheit' => '25');
$response = $soapclient->FahrenheitToCelsius($param);

var_dump($response);

이것은 동작하며 변환된 온도 값을 반환합니다.

먼저 웹 서비스를 초기화합니다.

$client = new SoapClient("http://example.com/webservices?wsdl");

그런 다음 파라미터를 설정하고 전달합니다.

$params = array (
    "arg0" => $contactid,
    "arg1" => $desc,
    "arg2" => $contactname
);

$response = $client->__soapCall('methodname', array($params));

WSDL 에서는, 메서드명은 동작명으로서 사용할 수 있는 것에 주의해 주세요.다음은 예를 제시하겠습니다.

<operation name="methodname">

왜 제 웹 서비스가 당신과 같은 구조를 가지고 있는지 모르겠지만 파라미터에 클래스가 필요 없고 배열일 뿐입니다.

예: - My WSDL:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:ns="http://www.kiala.com/schemas/psws/1.0">
    <soapenv:Header/>
    <soapenv:Body>
        <ns:createOrder reference="260778">
            <identification>
                <sender>5390a7006cee11e0ae3e0800200c9a66</sender>
                <hash>831f8c1ad25e1dc89cf2d8f23d2af...fa85155f5c67627</hash>
                <originator>VITS-STAELENS</originator>
            </identification>
            <delivery>
                <from country="ES" node=””/>
                <to country="ES" node="0299"/>
            </delivery>
            <parcel>
                <description>Zoethout thee</description>
                <weight>0.100</weight>
                <orderNumber>10K24</orderNumber>
                <orderDate>2012-12-31</orderDate>
            </parcel>
            <receiver>
                <firstName>Gladys</firstName>
                <surname>Roldan de Moras</surname>
                <address>
                    <line1>Calle General Oraá 26</line1>
                    <line2>(4º izda)</line2>
                    <postalCode>28006</postalCode>
                    <city>Madrid</city>
                    <country>ES</country>
                </address>
                <email>gverbruggen@kiala.com</email>
                <language>es</language>
            </receiver>
        </ns:createOrder>
    </soapenv:Body>
</soapenv:Envelope>

I var_dump:

var_dump($client->getFunctions());
var_dump($client->getTypes());

결과는 다음과 같습니다.

array
  0 => string 'OrderConfirmation createOrder(OrderRequest $createOrder)' (length=56)

array
  0 => string 'struct OrderRequest {
 Identification identification;
 Delivery delivery;
 Parcel parcel;
 Receiver receiver;
 string reference;
}' (length=130)
  1 => string 'struct Identification {
 string sender;
 string hash;
 string originator;
}' (length=75)
  2 => string 'struct Delivery {
 Node from;
 Node to;
}' (length=41)
  3 => string 'struct Node {
 string country;
 string node;
}' (length=46)
  4 => string 'struct Parcel {
 string description;
 decimal weight;
 string orderNumber;
 date orderDate;
}' (length=93)
  5 => string 'struct Receiver {
 string firstName;
 string surname;
 Address address;
 string email;
 string language;
}' (length=106)
  6 => string 'struct Address {
 string line1;
 string line2;
 string postalCode;
 string city;
 string country;
}' (length=99)
  7 => string 'struct OrderConfirmation {
 string trackingNumber;
 string reference;
}' (length=71)
  8 => string 'struct OrderServiceException {
 string code;
 OrderServiceException faultInfo;
 string message;
}' (length=97)

그래서 내 코드로:

    $client  = new SoapClient('http://packandship-ws.kiala.com/psws/order?wsdl');

    $params = array(
        'reference' => $orderId,
        'identification' => array(
            'sender' => param('kiala', 'sender_id'),
            'hash' => hash('sha512', $orderId . param('kiala', 'sender_id') . param('kiala', 'password')),
            'originator' => null,
        ),
        'delivery' => array(
            'from' => array(
                'country' => 'es',
                'node' => '',
            ),
            'to' => array(
                'country' => 'es',
                'node' => '0299'
            ),
        ),
        'parcel' => array(
            'description' => 'Description',
            'weight' => 0.200,
            'orderNumber' => $orderId,
            'orderDate' => date('Y-m-d')
        ),
        'receiver' => array(
            'firstName' => 'Customer First Name',
            'surname' => 'Customer Sur Name',
            'address' => array(
                'line1' => 'Line 1 Adress',
                'line2' => 'Line 2 Adress',
                'postalCode' => 28006,
                'city' => 'Madrid',
                'country' => 'es',
                ),
            'email' => 'test.ceres@yahoo.com',
            'language' => 'es'
        )
    );
    $result = $client->createOrder($params);
    var_dump($result);

하지만 성공했어요!

이것을 읽다;-

http://php.net/manual/en/soapclient.call.php

또는

이것은 SOAP 함수 '_call'의 좋은 예입니다.단, 권장되지 않습니다.

<?php
    $wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
    $int_zona = 5;
    $int_peso = 1001;
    $cliente = new SoapClient($wsdl);
    print "<p>Envio Internacional: ";
    $vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
    print $vem;
    print "</p>";
?>

먼저 비누를 사용하세요.UI: wsdl에서 SOAP 프로젝트를 만듭니다.wsdl의 조작으로 재생하는 요구를 송신해 주세요.xml 요청이 데이터 필드를 구성하는 방법을 관찰합니다.

그리고 SoapClient를 얻는 데 문제가 있는 경우 디버깅 방법은 다음과 같습니다.__getLastRequest() 함수를 사용할 수 있도록 옵션 트레이스를 설정합니다.

$soapClient = new SoapClient('http://yourwdsdlurl.com?wsdl', ['trace' => true]);
$params = ['user' => 'Hey', 'account' => '12345'];
$response = $soapClient->__soapCall('<operation>', $params);
$xml = $soapClient->__getLastRequest();

그런 다음 $xml 변수에는 SoapClient가 요청에 대해 구성하는 xml이 포함됩니다.이 xml을 Soap에서 생성된 xml과 비교합니다.UI.

SoapClient는 관련 배열 $params의 키를 무시하고 인덱스 배열로 해석하여 xml에서 잘못된 파라미터 데이터를 발생시키는 것 같습니다.즉, $params로 데이터를 재정렬하면 $response가 완전히 달라집니다.

$params = ['account' => '12345', 'user' => 'Hey'];
$response = $soapClient->__soapCall('<operation>', $params);

SoapParam 개체를 만들면 문제가 해결됩니다.클래스를 만들고 WebService에서 지정한 개체 유형에 매핑한 후 값을 초기화하고 요청을 전송합니다.아래 샘플을 참조하십시오.

struct Contact {

    function Contact ($pid, $pname)
    {
      id = $pid;
      name = $pname;
  }
}

$struct = new Contact(100,"John");

$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "Contact","http://soapinterop.org/xsd");

$ContactParam = new SoapParam($soapstruct, "Contact")

$response = $client->Function1($ContactParam);

저도 같은 문제를 안고 있었는데, 이렇게 논쟁을 마무리하고 지금은 통하고 있습니다.

    $args = array();
    $args['Header'] = array(
        'CustomerCode' => 'dsadsad',
        'Language' => 'fdsfasdf'
    );
    $args['RequestObject'] = $whatever;

    // this was the catch, double array with "Request"
    $response = $this->client->__soapCall($name, array(array( 'Request' => $args )));

다음 기능을 사용합니다.

 print_r($this->client->__getLastRequest());

XML 요청은 인수에 따라 변경 여부를 확인할 수 있습니다.

SoapClient 옵션에서 [trace = 1, exceptions = 0 ]를 사용합니다.

getLastRequest():

이 메서드는 트레이스 옵션이 TRUE로 설정된 상태에서 SoapClient 개체를 만든 경우에만 작동합니다.

이 경우 TRUE는 1로 표시됩니다.

$wsdl = storage_path('app/mywsdl.wsdl');
try{

  $options = array(
               // 'soap_version'=>SOAP_1_1,
               'trace'=>1,
               'exceptions'=>1,
               
                'cache_wsdl'=>WSDL_CACHE_NONE,
             //   'stream_context' => stream_context_create($arrContextOptions)
        );
           // $client = new \SoapClient($wsdl, array('cache_wsdl' => WSDL_CACHE_NONE) );
        $client = new \SoapClient($wsdl, array('cache_wsdl' => WSDL_CACHE_NONE));
        $client     = new \SoapClient($wsdl,$options);

클래스 계약을 선언해야 합니다.

class Contract {
  public $id;
  public $name;
}

$contract = new Contract();
$contract->id = 100;
$contract->name = "John";

$params = array(
  "Contact" => $contract,
  "description" => "Barrel of Oil",
  "amount" => 500,
);

또는

$params = array(
  $contract,
  "description" => "Barrel of Oil",
  "amount" => 500,
);

그리고나서

$response = $client->__soapCall("Function1", array("FirstFunction" => $params));

또는

$response = $client->__soapCall("Function1", $params);

다차원 배열이 필요하며 다음을 시도할 수 있습니다.

$params = array(
   array(
      "id" => 100,
      "name" => "John",
   ),
   "Barrel of Oil",
   500
);

PHP에서 어레이는 구조이며 매우 유연합니다.보통 soap calls에서는 XML 래퍼를 사용하기 때문에 동작할지는 잘 모르겠습니다.

편집:

송신할 json 쿼리를 작성하거나 이 페이지에 기재되어 있는 XML buy를 작성하기 위해 사용합니다.http://onwebdev.blogspot.com/2011/08/php-converting-rss-to-json.html

WsdlInterpreter 클래스를 사용하여 php5 개체를 생성하는 옵션이 있습니다.자세한 것은, https://github.com/gkwelding/WSDLInterpreter 를 참조해 주세요.

예를 들어 다음과 같습니다.

require_once 'WSDLInterpreter-v1.0.0/WSDLInterpreter.php';
$wsdlLocation = '<your wsdl url>?wsdl';
$wsdlInterpreter = new WSDLInterpreter($wsdlLocation);
$wsdlInterpreter->savePHP('.');

아래 코드가 도움이 될 수 있습니다.

    $wsdl ='My_WSDL_Service.wsdl";
    $options = array(
        'login' => 'user-name',
        'password' => 'Password',
    );
    try {
        $client = new SoapClient($wsdl, $options);
        $params = array(
            'para1' => $para1,
            'para2' => $para2
        );
        $res = $client->My_WSDL_Service($params);

언급URL : https://stackoverflow.com/questions/11593623/how-to-make-a-php-soap-call-using-the-soapclient-class