API cURL REQUEST PHP

Esta es la función que yo uso para hacer llamadas a las diferentes API’s que utilizo.

function callAPI($method, $api, $data = '', $headers = array(),$debug = false) {
    $status = array('error' => false, 'status' => array('code' => '','message' => ''),'data' => '');

    try {
      $curl = curl_init($api);
      curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false); // Necesario para HTTPS

      if($debug){
        $out = fopen('php://temp', 'w+');

        // Activar el debug verbose
        curl_setopt($curl,CURLOPT_VERBOSE, true);
        curl_setopt($curl,CURLOPT_NOPROGRESS, true);
        curl_setopt($curl,CURLOPT_STDERR, $out);
      }

      // Comprobar los metodos aceptados
      if(in_array($method,array('GET','POST','PUT','DELETE'))){
        curl_setopt($curl,CURLOPT_CUSTOMREQUEST, $method);
      }else{
        throw new Exception("Method not allowed", 1);
      }

      // Si hay datos los añadimos
      if(!empty($data))
        curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($data));

      // Cabecera si la hay, por defecto indicamos que todo es en JSON
      $h = array('Content-Type: application/json');
      if(!empty($headers)){
        foreach ($headers as $key => $value) {
          $h[] = $key.': '.$value;
        }
      }
      curl_setopt($curl, CURLOPT_HTTPHEADER, $h);

      $response = curl_exec($curl);

      /* Comprobar el codigo HTTP de respuesta */
      $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
      switch ($httpCode) {
        case 200:
          $status['status']['code'] = 200;
          $status['status']['message'] = '200: Success';
          $status['data']   = isJSON($response) ? json_decode($response,true) : $response;
          break;
        case 400:
          $status['error']  = true;
          $status['status']['code']    = 400;
          $status['status']['message'] = '400: Bad Request.';
        case 404:
          $status['error']  = true;
          $status['status']['code']    = 404;
          $status['status']['message'] = '404: API Not found.';
          break;
        case 503:
          $status['error']  = true;
          $status['status']['code']    = 503;
          $status['status']['message'] = '503: Service unavailable.';
          break;
        default:
          $status['error']  = true;
          $status['status']['code']    = $httpCode;
          $status['status']['message'] = 'Undocumented error: '.$httpCode. ' : ' . curl_error($curl);
          break;
      }

      if($debug){
        rewind($out);
        $status['verbose'] = str_replace('"',"'", stream_get_contents($out));
        fclose($out);
        # to display the data in the console you need to make it Javascript friendly.
        # This pattern & replacement will replace newline characters to make it suitable for javascript multiline display.
        $pttn='@(\r\n|\n)@i';
        $repl='"+\'\n\'+"';
        printf('<script>console.info("Status code:%s\n\nVerbose output:\n%s")</script>', $httpCode, preg_replace(
          $pttn,
          $repl,
          $status['verbose']
        ));
      }

      curl_close($curl);
      return $status;

    } catch (\Exception $e) {
      $status['error']  = true;
      $status['status'] = $e->getMessage();
      return $status;
    }
  }
$return = callAPI('POST', $url.'accounts/sign_in?login_name='.$X_Login_Name.'&password='.$pass);
$headers = array('X-Login-Name' => $X_Login_Name,'X-Auth-Token' => $X_Auth_Token);
$params = '?per_page=200';
$return = callAPI('GET', $url.$organization.'/vehicles'.$params,'',$headers,true);

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Captcha cargando...