amusarra
9/16/2015 - 9:27 PM

SugarCRM HttpClient Example

SugarCRM HttpClient Example

curl 'http://192.168.142.128/crm1/index.php' \
  -H 'Pragma: no-cache' -H 'Origin: http://192.168.142.128' \
  -H 'Accept-Encoding: gzip, deflatAccept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4' \
  -H 'Upgrade-Insecure-Requests: 1' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' \
  -H 'Cache-Control: no-cache' \
  -H 'Referer: http://192.168.142.128/crm1/index.php?module=Users&action=Login' \
  -H 'Connection: keep-alive' -H 'X-FirePHP-Version: 0.0.6' \
  --data 'module=Users&action=Authenticate&return_module=Users&return_action=Login&cant_login=&login_module=&login_action=&login_record=&login_token=&login_oauth_token=&login_mobile=&user_name=admin&user_password=admin&Login=Log+In' \
  --compressed -v -c sugarcrmcookie.txt -L
<?php
   if(!defined('sugarEntry'))define('sugarEntry', true);

    require_once('include/entryPoint.php');

    // specify the REST web service to interact with
    $base_url = "http://192.168.142.128/crm2";
    $rest_url = "$base_url/service/v4_1/rest.php";

    // Open a SugarHttpClient session for making the call
    require_once('include/SugarHttpClient.php');

    $client = new SugarHttpClient;

    // Set the POST arguments to pass to the Sugar server
    $parameters = array(
        'user_auth' => array(
            'user_name' => 'admin',
            'password' => md5('admin'),
	          'version' => '1'
        ),
	       'application_name' => 'SugarCRM Rest Client',
	        'name_value_list' => array()
    );

    $json = json_encode($parameters);
    $postArgs = array(
        'method' => 'login',
        'input_type' => 'JSON',
        'response_type' => 'JSON',
        'rest_data' => $json,
    );

    $postArgs = http_build_query($postArgs);

    // Make the REST call, returning the result
    $response = $client->callRest($rest_url, $postArgs);

    if ( $response === false )
    {
        die("Request failed.\n");
    }

    // Convert the result from JSON format to a PHP array
    $result = json_decode($response);

    if ( !is_object($result) )
    {
        die("Error handling result.\n");
    }

    if ( !isset($result->id) )
    {
        die("Error: {$result->name} - {$result->description}\n.");
    }

    // Get the session id
    $sessionId = $result->id;
    $home_url = "$base_url/index.php?action=index&module=Home&MSID=$sessionId";

    echo "Your sessionId: $sessionId";
    echo "Home Url with SessionId: $home_url";
    echo  "\n";
?>