AnsweredAssumed Answered

How do you create an API call in PHP?

Question asked by sharif sharif on Mar 19, 2014
Latest reply on May 17, 2014 by paperless
I am devloping in php using yii framework. I am trying to implement the example given in the docs but it is not working. i get error url not found. i am using sugar 6.5.13

public function actionCreateSIDBAccount2(){ 

    $model=new SugarAccounts;

    if(isset($_POST['SugarAccounts']))
    {
     $model->attributes=$_POST['SugarAccounts'];
     $record=SugarAccounts::model()->find(array(     
       'condition'=>'name LIKE :name AND billing_address_street LIKE :billing_street AND billing_address_country LIKE :billing_country',
       'params'=>array(':name'=>"%".$model->name."%", ':billing_street'=>"%".$model->billing_address_street."%",":billing_country"=>"%".$model->billing_address_country."%" ))
     );

     if(!empty($record)){
      //echo
      echo json_encode(array("error"=>true,"message"=>"Account exists"));
      return;
      //throw new CHttpException(404,'The requested page does not exist.');
     }
     $accountid = $this->create_guid();
     $model->id = $accountid;
     $model->deleted = 0;

     /****************************************/

     $base_url = "http://portal-test/sugarcrm//service/v4_1/";
     $username = "admin";
     $password = "support";

     //Login - POST /oauth2/token ---------------------------------

     $url = $base_url . "/oauth2/token";

     $oauth2_token_parameters = array(
       "grant_type" => "password",
       "client_id" => "sugar",
       "client_secret" => "",
       "username" => $username,
       "password" => $password,
       "platform" => "base"
     );

     $oauth2_token_result = $this->call($url, '', 'POST', $oauth2_token_parameters);

      echo "
";
     print_r($oauth2_token_result);
     echo "
";
     exit();

     //Account update - POST //:record ---------------------------------

     $url = $base_url . "/Accounts";

     $new_record_parameters = array(
       "name" => $_POST['SugarAccounts']['name'],
       "phone_office" => $_POST['SugarAccounts']['phone_office'],
       "website" => $_POST['SugarAccounts']['website'],
       /*"email" => array(
         array(
           "email_address" => "abc.account@sugar.crm",
           "primary_address" => "1",
           "invalid_email" => "0",
           "opt_out" => "0"
         ),
         array(
           "email_address" => "abc@sugar.crm",
           "primary_address" => "0",
           "invalid_email" => "0",
           "opt_out" => "1"
         ),
       ),*/
     );

     $new_record_result = $this->call($url, $oauth2_token_result->access_token, 'POST', $new_record_parameters);

     echo "
";
     print_r($new_record_result);
     echo "
";

     /*******************************************/

     /*

     $trans = Yii::app()->dbSugar->beginTransaction();
     $error = false;
     try {
      if($model->validate()){
       //create account
       //$model->save();
      }else{
       $error .= "Failed account validations";
      }
      $trans->commit();

     } catch (Exception $e) {
      $trans->rollback();
      Yii::log("Error occurred on order form while saving. Rolling back... . Exception: " . $e->getMessage(), CLogger::LEVEL_ERROR, __METHOD__);
      $error .=  $e->getMessage();
      echo $e->getMessage();

     }
     */
     if($error)
      echo json_encode(array('error'=>true,"message"=>$error,'accountid'=>$model->id));
     else
      echo json_encode(array('error'=>false,'accountid'=>$model->id,"name"=>$model->name));
    }

  }

  /**
   * Generic function to make cURL request.
   * @param $url - The URL route to use.
   * @param string $oauthtoken - The oauth token.
   * @param string $type - GET, POST, PUT. Defaults to GET.
   * @param array $parameters - Endpoint parameters.
   * @param array $encodeData - Whether or not to JSON encode the data.
   * @param array $returnHeaders - Whether or not to return the headers.
   * @return mixed
   */
  public function call(
    $url,
    $oauthtoken='',
    $type='GET',
    $parameters=array(),
    $encodeData=true,
    $returnHeaders=false
  )
  {
   $type = strtoupper($type);
   $curl_request = curl_init($url);

   if ($type == 'POST')
   {
    curl_setopt($curl_request, CURLOPT_POST, 1);
   }
   elseif ($type == 'PUT')
   {
    curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
   }
   elseif ($type == 'DELETE')
   {
    curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
   }

   curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_setopt($curl_request, CURLOPT_HEADER, $returnHeaders);
   curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);

   if (!empty($oauthtoken))
   {
    $token = array("oauth-token: {$oauthtoken}");
    curl_setopt($curl_request, CURLOPT_HTTPHEADER, $token);
   }

   if (!empty($parameters))
   {
    if ($encodeData)
    {
     //encode the parameters as JSON
     $parameters = json_encode($parameters);
    }

    curl_setopt($curl_request, CURLOPT_POSTFIELDS, $parameters);
   }

   $result = curl_exec($curl_request);

   if ($returnHeaders)
   {
    //set headers from response
    list($headers, $content) = explode("\r\n\r\n", $result ,2);
    foreach (explode("\r\n",$headers) as $header)
    {
     header($header);
    }

    //return the nonheader data
    return trim($content);
   }

   curl_close($curl_request);

   //decode the response from JSON
   $response = json_decode($result);

   return $response;
  }



Outcomes