Come utilizzare l'API Ikoula

Da It Ikoula wiki.
Jump to navigation Jump to search

en:How to use the Ikoula API fr:Comment utiliser l'API d’Ikoula es:Cómo utilizar la API de Ikoula nl:Hoe de Ikoula API te gebruiken? zh:如何使用Ikoula的API


Introduzione

Ikoula dispone di un’API che consente alla realizzazione di azioni sui prodotti associati al vostro conto cliente. Ecco l’URL dell’API: https://api.ikoula.com

La documentazione è ora disponibile per ogni prodotto.

Spiegazioni

Per ovvi motivi di sicurezza, l’API di Ikoula richiede un’autenticazione. È basata su un identificativo, una password e una firma:

  • L’identificativo è l’indirizzo e-mail usato per la connessione al vostro conto Ikoula oppure all’Extranet. Il nome dell’impostazione da trasmettere è sempre login ;
  • La password deve essere criptata tramite una funzione specifica che usa una chiave pubblica messa a disposizione da Ikoula (impostazione crypted_password) e base64_encode ;
  • La firma viene creata secondo delle impostazioni fornite durante la chiamata all’API.
  • Queste impostazioni devono sempre essere passate in GET all’API!


ATTENZIONE

Per i vostri test dell’API, potete ad esempio usare un utente provvisorio specifico per questi test. L’uso della crittografia della password con la chiave pubblica Ikoula è indispensabile in ogni caso di produzione oppure di non-breve termine.
Se le chiamate API devono essere usate tramite uno script o un programma, vi consigliamo la creazione di un utente dedicato a tale scopo invece di usare il vostro utente extranet classico.
Ci sono quindi due possibilità:

  • Potete creare un sotto-utente direttamente dalla homepage del vostro conto extranet (Cfr. il Wiki qui sotto per la creazione di un sotto-utente: Come creare un account secondario?).
  • Potete contattare il nostro supporto per la creazione di un utente Extranet, se ne avete bisogno.

Attenzione di non dimenticare di dargli i diritti sulle caratteristiche desiderate.

Chiave di crittografia

La chiave pubblica di crittografia della password è disponibile su questo sito: https://api.ikoula.com/downloads/Ikoula.API.RSAKeyPub.pem

Wrapper PHP

<?php 

// #################################################
// ####    ..:: Ikoula Hosting Services ::..     ###
// ####	   Wrapper for https://api.ikoula.com	 ###
// #################################################

class IkoulaAPI {

   /**
    * Email of Ikoula account
    * @var string Email account
    */
    private static $email = "EMAIL_ACCOUNT_IKOULA";

   /**
    * Password of Ikoula account
    * @var string Password account
    */
    private static $password = "PASSWORD_ACCOUNT_IKOULA";

   /**
    * Ikoula API URI
    * @var string Password account
    */ 
    private static $urlApi = "https://api.ikoula.com/";

   /** Public key path for encrypt data
    * @var string Path of public key
    * @see https://api.ikoula.com/downloads/Ikoula.API.RSAKeyPub.pem
    */ 
    private static $publicKeyPath = "/path/to/ikoula/public/key/Ikoula.API.RSAKeyPub.pem";
	
    /** Fonction for request Ikoula API
     * @param string $webservice Webservice for data
     * @param string $format JSON or XML
     * @param string $type HTTP Type (GET/POST)
     * @param array $params Params to add for request
     */
     public static function requestApi($webservice, $format, $type, $params = [])
     {
		// Add connexion information
		$params['login'] = self::$email;
		$params['crypted_password'] = base64_encode(self::opensslEncryptPublic(self::$password));
		$params['format'] = $format;

		// Fix params to lowercase for generate signature correctly
		$params = array_change_key_case($params);

		// Generate signature
		$signature = self::createSignature($params);

		// Add signature for call
		$params['signature'] = $signature;

		// Curl init
		$ch = curl_init();

		if($ch)
		{
			// Create API URI
			$url = self::$urlApi.$webservice;
	
			// Add type request
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);

			// If parameters, we encode his 
			if(is_array($params) && count($params) > 0)
				$params_str = http_build_query($params);

			// If we use post, fix params
			if(strcasecmp("POST", $type) == 0)
			{
				// Fix POST data
				curl_setopt($ch,CURLOPT_POST, true);
				curl_setopt($ch,CURLOPT_POSTFIELDS, $params_str);
			}
			else
				$url .= (strpos($url,'?') === false ? '?' : '&').$params_str;
	
			// Create curl info
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
			curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_HEADER, false);
	
			// Exec request
			$data = curl_exec($ch);
	
			// Close curl object
			curl_close($ch);
	
			// Return response
			return($data);
		}

		return null;
    }

    /** Create signature with params
     * @param array $params Params to add for request
     * @return string Signature encoded
     */
    private static function createSignature($params = [])
    {
        // Signature to send
        $signature = null;

        // Verify parameters
        if (count($params) > 0)
        {
            // Sort params
            ksort($params);
            
            // Encode params
            $query = http_build_query($params);

            // Encode "plus "+"
            $query = str_replace("+", "%20", $query);

            // Transform in lowercase
            $query = strtolower($query);

            $public_key = "";

            // Verify if key file is present
            if (file_exists(self::$publicKeyPath))
            {
				// Get public key
                $public_key = trim(
                        str_replace(
                                array("\n", '-----BEGIN PUBLIC KEY-----','-----END PUBLIC KEY-----'), 
                                array('', '', ''), 
                                file_get_contents(self::$publicKeyPath)
                            )
                        );
            }

   			// SHA1 hash
            $hash = hash_hmac("SHA1", $query, $public_key, true);

    		// base64 encode
            $signature = base64_encode($hash);
        }

    	return $signature;
	}
	
	/** Fonction for crypt Ikoula password
	 * @param string $password Ikoula account password
	 * @return mixed Ikoula password encrypted, null if error
	 */
	private static function opensslEncryptPublic($password)
	{
		// Verify if key file exist
		if(file_exists(self::$publicKeyPath))
		{
			 // Verify if password is not empty
 			if(!empty($password))
			{
				// Get file content
				$publicKey = openssl_pkey_get_public('file://'.realpath(self::$publicKeyPath));
	
				// If we get file content without error
				if ($publicKey !== FALSE)      
				{
					// Encrypt password
					if(openssl_public_encrypt($password, $crypted, $publicKey) === TRUE)
						return $crypted;
					else
						return NULL;
				}
				else
					return NULL;
			}
			else
				return NULL;
		}
		else
			return NULL;
	}
}

Esempi di utilizzo

// Fix JSON header
header("Content-type: application/json");

// Get Exch schema for prestation
echo IkoulaAPI::requestApi("wsexch/schema-subscr", "json", "GET", ['subscr_id' => 999999999]);

// Get Flex VM for Ikoula Account
echo IkoulaAPI::requestApi("wsflex/list", "json", "GET", []);

// Get Flex VM for Ikoula Account
echo IkoulaAPI::requestApi("wsflex/list", "json", "GET", []);

// Get Platform list
echo IkoulaAPI::requestApi("wsplatform/list", "json", "GET", []);

// Get Platform dossiers
echo IkoulaAPI::requestApi("wsplatform/dossiers", "json", "GET", ['platform_id' => 999999999]);

// Get Billing conso for CloudStack prestation
echo IkoulaAPI::requestApi("wscs/conso-for-billing", "json", "GET", ['subscr_id' => '999999999', 'billing_id' => '1']);

// Reboot server
echo IkoulaAPI::requestApi("wsds/reboot-apc-request", "json", "GET", ['server_ip' => 'XXX.XXX.XXX.XXX', 'tempo' => '3']);

Aggiunta di funzionalità

In caso di richiesta di funzionalità, contattare il supporto tecnico.