參與編輯工作賺 adsense 及個人曝光

PHP 的 SOAP 串接 – 使用 NuSOAP

Posted by Tsung Hao on Mar 16, 2010 | Leave a Comment
  • A A A
  • 好久沒串 SOAP, 最近有個 API 使用 SOAP, 重新拿出來複習~ 此篇都是以 Client 為主.

    什麼是 SOAP

    PHP NuSOAP

    • PHP 的 SOAP 可以使用 PHP: SOAP – Manual, 或者其它套件, 在此篇使用的是 NuSOAP.
    • 使用 NuSOAP 的原因, 主要是因為 NuSOAP 完整又簡單, 而且以前使用起來很愉快, 就繼續用下去~ :P

    NuSOAP 安裝、使用

    1. NuSOAP 官方網站: NuSOAP – SOAP Toolkit for PHP -   由此下載 NuSOAP
    2. unzip nusoap-0.7.3.zip
    3. 使用

      <?php
      include('soap/nusoap.php'); // 即可
      ?>

    NuSOAP Client 範例

    主要是 $param (參數, 注意裡面的型態, 須要與 API 的型態一致, 不然有可能會出錯.), $serverpath (Server 位置), $client->call() (API 名稱), 就可以取得 API 的結果.

    範例

    <?php
    $param = array(
    'id'      => 1,
    'user_id' => (string)$user_id,
    'name'    => 'jon',
    );

    $serverpath = ‘http://soap.example.com/user/userinfo’;
    $client = new nusoap_client($serverpath);

    $err = $client->getError();
    if ($err)
    return false;

    $result = $client->call(‘showUserInfo’, $param);

    print_r($result);
    ?>

    NuSOAP Client 範例 – Login

    SOAP 經常使用在 SSO (Single Sign-On 單一登入), 登入完後的 cookie 要如何紀錄, 並於下個 API call 時帶入?

    註: 此篇範例是需要帶入 SOAPAction 的, SOAPAction: http://soap.example.com/user/Login, http://soap.example.com/user/GetUserData

    範例

    <?php
    // Login
    $url = 'https://soap.example.com/v3/Services/UserLogin.asmx';
    $client = new nusoap_client($url);
    $err = $client->getError();
    if ($err)
    return false;

    $param = array(
    ‘user’ => ‘jon’,
    ‘password’ => ‘test’,
    );

    $result = $client->call(‘Login’, $param, ”, ‘http://soap.example.com/user/Login’);
    print_r($result); // 此段已經可以登入完成, 看看是否有取得資料

    // Debug
    //echo “request:\n” . $client->request . “\n”; // 發出的 SOAP request XML 長什麼樣子
    //echo “response:\n” . $client->response . “\n”; // 接收到的 XML 長什麼樣子

    // Get User Info (登入完成, 取得 cookie 後, 再接著去要使用者相關資料)
    $cookie = $client->getCookies(); // 上面登入完成, 取得 Cookie 值
    $url = ‘https://soap.example.com/v3/Services/UserInfo.asmx?wsdl’;
    $client = new nusoap_client($url); // create new soap client
    $client->setCookie($cookie[0]['name'], $cookie[0]['value']); // 指定 Cookie 值
    $result = $client->call(‘GetUserInfo’, ”, ”, ‘http://soap.example.com/user/GetUserData’);
    print_r($result); // 即取得登入後, call GetUserInfo 的資料
    ?>

    相關說明

    相關網頁

    Source

    Top Daily

    Top Weekly

    Leave a comment

    Advertisement

    Subscription

    You can subscribe by e-mail to receive news updates and breaking stories.

    Follow me

    Follow technowhk on Twitter

    AD




    網頁寄存贊助商

    Alexa