DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
實戰 SugarCRM 的 REST 介面
編輯:XML詳解     

SugarCRM 是全球領先的開源客戶關係管理(CRM)軟體供應商,客戶遍及世界各地、多達五千家,SugarCRM 應用程式的累計下載量更突破五十萬次。2009 年 12 月,SugarCRM 推出了 5.5 版,對其 Web 服務平台做了一次徹底的翻新:新版帶來更快、更順手的 API,能輕鬆擴展暴露給 Web 服務用戶端的介面,並新增了對 REST 的支援。

什麼是 REST?

先快速約定幾個縮寫:

  • API:應用程式介面
  • CSS:層疊樣式表
  • DOM:文件物件模型
  • HTML:超文本標記語言
  • HTTP:超文本傳輸協議
  • JSON:JavaScript 物件符號
  • REST:具象狀態傳輸
  • RPC:遠程程序呼叫
  • URL:統一資源定位符
  • XML:可擴展標記語言

REST 是 REpresentational State Transfer 的縮寫,理念是打造一套精簡的 Web 服務協議。它的誕生,正是為了回應 SOAP、XML-RPC 這類重量級協議——後者高度依賴預先定義好的訊息格式與方法,在伺服器與用戶端之間往返傳遞。REST 則拋開了這些束縛:訊息格式任你挑選,無論是 JSON、XML、HTML、序列化資料還是純文字皆可,操作則一律透過標準的 HTTP 動詞 GET、DELETE、POST 來完成。用戶端與伺服器之間的互動規則,完全可以由應用程式的需求來定義。舉例來說,若這個 REST 介面要給 JavaScript 用戶端使用,你或許會讓資料以 JSON 格式回傳;但若用戶端是 PHP,序列化資料或 XML 說不定更合適。

每一次 REST Web 服務呼叫,本質上就是一個搭配標準 HTTP 動詞的簡單 HTTP 請求。一般來說,選用最貼切當前意圖的動詞即可:

  • GET:從伺服器取得資料。
  • POST:向伺服器送出資料。
  • DELETE:刪除伺服器上的資源。

清單 1 示範了如何與 Yahoo! 互動,透過 PHP 呼叫一則 REST Web 服務(本文所有範例均可於「下載」區取得)。

清單 1. 在 PHP 中與 REST Web 服務互動的範例

<?PHP
// specify the REST web service to interact with
$url = 'https://search.yahooapis.com/WebSearchService/V1/
webSearch?appid=YahooDemo&query=sugarcrm';
// make the web services call; the results are returned in XML format
$resultsXML = file_get_contents($url);
// convert XML to a SimpleXML object
$xmlObject = simplexml_load_string($resultsXML);
// iterate over the object to get the title of each search result
foreach ( $XMLObject->Result as $result )
echo "{$result->Title}\n";

這段程式呼叫 Yahoo Web Search Service 搜尋 sugarcrm。它用 PHP 的 file_get_contents() 函式,對指定 URL 發出 GET 請求;服務預設以 XML 字串回傳結果,接著用 PHP 的 SimpleXML 庫把字串解析成物件,我們便能逐一走訪、取出想要的資料。理解了 REST 的運作方式,接下來就來看看如何用它串接 SugarCRM 的 Web 服務介面。

以 REST 連線到 SugarCRM

SugarCRM 現成提供了一個 Web 服務介面,位址為 https://path_to_Sugar_instance/v2/rest.PHP。呼叫方式是對這個 URL 發出 POST 請求,並把所需參數作為 POST 參數傳入。每回與 Web 服務互動,用戶端都必須先呼叫 login 方法完成驗證,如清單 2。

清單 2. 透過 REST Web 服務介面登入 SugarCRM 實例

<?PHP
// specify the REST web service to interact with
$url = 'https://localhost/sugar/v2/rest.PHP';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'passWord',
);
$json = JSon_encode($parameters);
$postArgs = 'method=login&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Echo out the session id
echo $result['id'];

由於得用 POST 而非 GET,這裡改用 PHP 的 curl 庫、而非 file_get_contents() 來呼叫 Sugar 服務。先把參數收攏成陣列並編碼成 JSON 字串,接著在請求中指定:方法(此處為 login)、參數格式(由 input_type 指定,可為 json 或 serialized),以及期望的回傳格式(由 response_type 指定,可為 json、rss 或 serialized),最後把 JSON 編碼後的參數字串放進 rest_data。呼叫完成後,再解碼伺服器回傳的 JSON。這裡我們最在意的回傳值是 id 參數——它會在後續請求中派上用場,讓伺服器認出這個已通過驗證的用戶端。

建立一筆新記錄

有了清單 2 打底,就能進一步實際操作 Sugar 的 Web 服務。清單 3 示範了如何透過這個介面,往 Accounts 模組新增一筆記錄。

清單 3. 使用 REST Web 服務介面新增帳戶

<?PHP
// specify the REST web service to interact with
$url = 'https://localhost/sugar/v2/rest.PHP';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'passWord',
);
$json = JSon_encode($parameters);
$postArgs = 'method=login&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Accounts record
$parameters = array(
'session' => $session,
'module' => 'Accounts',
'name_value_list' => array(
array('name' => 'name', 'value' => 'New Account'),
array('name' => 'description', 'value' => 'This is an
account created from a REST web services call'),
),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the newly created record id
$recordId = $result['id'];

登入之後,接著發出第二次呼叫,這回改用 set_entry 方法。把 login 回傳的 session ID 帶入 session 參數,把要寫入的模組帶入 module 參數;name_value_list 則是一串「名稱/值」對,用來為新記錄設定各欄位。呼叫完成後,就會收到新記錄的 ID。

想更新既有記錄,同樣再呼叫一次 set_entry 即可——只要確保在 name_value_list 裡帶上欲更新記錄的 ID,如清單 4。

清單 4. 使用 REST Web 服務介面建立並更新聯絡人

<?PHP
// specify the REST web service to interact with
$url = 'https://localhost/sugar/v2/rest.PHP';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'passWord',
);
$json = JSon_encode($parameters);
$postArgs = 'method=login&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Contacts record
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_list' => array(
array('name' => 'first_name', 'value' => 'John'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the newly created record id
$recordId = $result['id'];
// Now let's update that record we just created
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_list' => array(
array('name' => 'id', 'value' => $recordId),
array('name' => 'title', 'value' => 'Engineer'),
),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the record id of the record we just updated
$recordId = $result['id'];

清單 4 中,第二次呼叫 set_entry 只用來更新剛建立的記錄。這回把欲更新記錄的 ID 當作 name_value_list 裡的一個條目傳入,並一併帶上要更新的欄位(此例把 title 設為 Engineer)。送出請求後,一如預期地回傳該記錄 ID,代表更新成功。

批次建立多筆記錄

若要在同一模組中一次建立多筆記錄,可改用 set_entries 方法,把對 Web 服務的呼叫次數壓到僅一次,而不必在迴圈裡反覆呼叫 set_entry,如清單 5。

清單 5. 透過一次方法呼叫建立多筆記錄

<?PHP
// specify the REST web service to interact with
$url = 'https://localhost/sugar/v2/rest.PHP';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'passWord',
);
$json = JSon_encode($parameters);
$postArgs = 'method=login&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Contacts record
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_lists' =>
array(
array('name' => 'first_name', 'value' => 'John'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
array(
array('name' => 'first_name', 'value' => 'Dominic'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
array(
array('name' => 'first_name', 'value' => 'Mallory'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the newly created record ids as an array
$recordIds = $result['ids'];

set_entries 的參數與 set_entry 大同小異,唯一的差別是:它不用 name_value_list,而改用 name_value_lists——這是一個關聯陣列,每個元素對應一筆要建立的記錄。完成後,各筆新記錄的 ID 會以陣列形式放在 ids 參數中回傳,順序與傳入時一致。

關聯記錄

SugarCRM 的一大特色,就是能把記錄彼此關聯起來。最典型的例子便是 Account 與 Contact 的關係:每個 Account 都可關聯一或多個 Contact。這種關係可以透過 Web 服務框架完整建立,如清單 6。

清單 6. 使用 REST Web 服務 API 關聯 Account 與 Contact

<?PHP
// specify the REST web service to interact with
$url = 'https://localhost/sugar/v2/rest.PHP';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'passWord',
);
$json = JSon_encode($parameters);
$postArgs = 'method=login&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Accounts record
$parameters = array(
'session' => $session,
'module' => 'Accounts',
'name_value_list' => array(
array('name' => 'name', 'value' => 'New Account'),
array('name' => 'description', 'value' => 'This is an
account created from a REST web services call'),
),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the newly created Account record id
$accountId = $result['id'];
// Now, let's add a new Contacts record
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_list' => array(
array('name' => 'first_name', 'value' => 'John'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = JSon_decode($response);
// Get the newly created Contact record id
$contactId = $result['id'];
// Now let's relate the records together
$parameters = array(
'session' => $session,
'module_id' => $accountId
'module_name' => 'Accounts',
'link_fIEld_name' => 'contacts',
'related_ids' => array($contactId),
);
$json = JSon_encode($parameters);
$postArgs = 'method=set_relationship&input_type=JSon&
response_type=json&rest_data=' . $JSon;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call
$response = curl_exec($session);

建立好需要關聯的 Account 與 Contact 之後,接著呼叫 set_relationship 方法,並傳入下列參數:

  • session:取得 Web 服務工作階段的 session ID。
  • module_name:關係的主模組。
  • module_id:作為關係基礎的那筆記錄的 ID。
  • link_field_name:模組中用來連向其他模組的關係名稱(此例為 contacts)。

最後,再指定一份要關聯過去的記錄 ID 清單。呼叫完成後,這層關係便正式建立。

以上僅是眾多可用 Web 服務方法的一小部分;完整的清單可查閱 SugarCRM Developer Documentation。

結語

本文介紹了 SugarCRM 5.5 的一項新特性——Sugar Web 服務框架的 REST 介面。我們先弄懂了 REST Web 服務的運作原理,接著透過一連串實作範例,學會了如何為模組新增記錄、修改記錄、以單次呼叫批次建立多筆記錄(省去反覆呼叫遠端服務的開銷),並運用 set_relationship 方法把兩個不同記錄關聯起來。掌握這些基本功,你就能把 SugarCRM 的 Web 服務能力靈活接入自己的應用中了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved