« GLPI/Configuration/Générale/API/Exemple 1 » : différence entre les versions

Aller à la navigation Aller à la recherche
(Page créée avec « {{Sommaire}} Exemple de script PHP d'utilisation de l'API GLPI. Source : * forum GLPI : https://forum.glpi-project.org/ * membre : MrCraac * https://forum.glpi-project.org/viewtopic.php?id=170219 <source> <?php // * * * * * Début des fonctions * * * * * // SESSION OPENING function OpenSession() { try { $api_url = "http://localhost/apirest.php"; $user_token = "QU6a1yy6Fpf2aVxg4rFzjTiZUcpFbGOyB8uBApFA"; $app_token = "Ia9UgZflvuqO7P1Sg5... »)
 
 
(4 versions intermédiaires par le même utilisateur non affichées)
Ligne 8 : Ligne 8 :
* https://forum.glpi-project.org/viewtopic.php?id=170219
* https://forum.glpi-project.org/viewtopic.php?id=170219


Autre source identique :
* https://github.com/Carlos18075/Auto-Create-User/blob/main/Auto%20Create%20user.php
== Exemple ==
<source>
<source>
<?php
<?php


// * * * * * Début des fonctions * * * * *
// * * * * * Début des fonctions * * * * *
// SESSION OPENING
 
function OpenSession() {
function OpenSession() {
     try {
     try {
         $api_url = "http://localhost/apirest.php";
         $api_url = "http://localhost/glpi10/apirest.php";
         $user_token = "QU6a1yy6Fpf2aVxg4rFzjTiZUcpFbGOyB8uBApFA";
 
         $app_token = "Ia9UgZflvuqO7P1Sg5u4Qz3QsylIGfh6CMFxbp5l";
        // Jeton personnel (préférence du compte de l'utilisateur)
         $user_token = "SITuxell3jzgeCLCAiwcEfGz7s92qryCt7REDyrr";
       
        // Jeton d'API (préférence du compte de l'utilisateur)       
$userapp_token = "eU5uFEuoa2r6LwxFvmp9FCSsNxCN4QwcWUmB8tEI";
       
        // Jeton d'application (app_token) ; (Configuration > Général > API
         $app_token = "My0pKoDQElYhBqOFzXhfzd3nrvury0ZphwAcYtll";
       
         $ch = curl_init();
         $ch = curl_init();
         $url = $api_url . "/initSession?Content-Type=%20application/json&app_token=" . $app_token . "&user_token=" . $user_token;
          
        // ATTENTION, c'est bien le jeton d'application de l'utilisateur qui est utilisé pour un bon fonctionnement
        $url = $api_url . "/initSession?Content-Type=%20application/json&app_token=" . $app_token . "&user_token=" . $userapp_token;
       
        // ATTENTION, ne fonctionne pas (avec le jeton utilisateur)
        // $url = $api_url . "/initSession?Content-Type=%20application/json&app_token=" . $app_token . "&user_token=" . $user_token;
       
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         $json = curl_exec($ch);
         $json = curl_exec($ch);
echo ("json : " . $json);
         curl_close($ch);
         curl_close($ch);
         $obj = json_decode($json, true);
         $obj = json_decode($json, true);
echo ("objet : " . $obj);
         $sess_token = $obj['session_token'];
         $sess_token = $obj['session_token'];
         $headers = array(
         $headers = array(
Ligne 39 : Ligne 59 :
}
}


// USER CREATION
function CreateUser($name, $realname = null, $firstname = null, $entities_id, $pwd, $headers){
function CreateUser($name,$realname = null,$firstname = null ,$entities_id,$pwd, $headers){
     try {
     try {
         $data = [
         $data = [
Ligne 48 : Ligne 67 :
                 'realname' => $realname,
                 'realname' => $realname,
                 'firstname' => $firstname,
                 'firstname' => $firstname,
                 'language' => 'en_GB',
                 'language' => 'fr_FR',
                 'is_active' => 1,
                 'is_active' => 1,
                 'entities_id' => $entities_id,
                 'entities_id' => $entities_id,
            ]
]
        ];
];
         $input = json_encode($data);
         $input = json_encode($data);


         $api_url = "http://localhost/apirest.php";
         $api_url = "http://localhost/glpi10/apirest.php";
         $url=$api_url . "/User";
         $url = $api_url . "/User";


         $ch = curl_init();
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL,$url);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
         curl_setopt($ch, CURLOPT_POSTFIELDS,$input);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $input);


         $json = curl_exec($ch);
         $json = curl_exec($ch);
Ligne 70 : Ligne 89 :
         $res = json_decode($json, true);
         $res = json_decode($json, true);


         if ($res[0]== "ERROR_GLPI_ADD") {
         if ($res[0] == "ERROR_GLPI_ADD") {
             return ["status" => false, "message" => $res[1], "user" => $name];
             return ["status" => false, "message" => $res[1], "user" => $name];
}
}
Ligne 81 : Ligne 100 :
}
}


// Email CREATION
function AddEmail($name, $headers) {
function AddEmail($name, $headers) {
// GET USER ID
// GET USER ID
     try {
     try {
         $api_url="http://localhost/apirest.php";
         $api_url = "http://localhost/glpi10/apirest.php";
         $url = $api_url . "/search/User?criteria[0][field]=1&criteria[0][searchtype]=contains&criteria[0][value]=^" . $name . "$&forcedisplay[0]=2";
         $url = $api_url . "/search/User?criteria[0][field]=1&criteria[0][searchtype]=contains&criteria[0][value]=^" . $name . "$&forcedisplay[0]=2";


Ligne 95 : Ligne 113 :
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
         //curl_setopt($ch, CURLOPT_POSTFIELDS,$input);
         //curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
         $json = curl_exec($ch);
         $json = curl_exec($ch);
         curl_close($ch);
         curl_close($ch);
Ligne 108 : Ligne 126 :
     try {
     try {
         $user_id = $obj['data']['0']['2'];
         $user_id = $obj['data']['0']['2'];
         $api_url="http://localhost/apirest.php";
         $api_url = "http://localhost/apirest.php";
         $url = $api_url . "/User/" . $user_id . "/UserEmail/";
         $url = $api_url . "/User/" . $user_id . "/UserEmail/";
         $fields = '{"input":{"users_id":' . $user_id . ',"is_default":1,"is_dynamic":0,"email":"' . $name . '"}}';
         $fields = '{"input": {"users_id":' . $user_id . ', "is_default":1, "is_dynamic":0, "email":"' . $email . '"}}';
         $ch = curl_init();
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_URL, $url);
Ligne 131 : Ligne 149 :
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *  
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *  
//  USER TEST
//  USER TEST
$name = "hello2@coucou.fr";
$name = "pagep2";
$realname = 'test';
$realname = 'Page2';
$firstname = 'bbb';
$firstname = 'Philippe';
$entities_id = 3;
$email = 'philippe.page2@domaine.fr';
$entities_id = 0;
$pwd = sha1($name);
$pwd = sha1($name);
$headers = OpenSession();
$headers = OpenSession();
Ligne 141 : Ligne 160 :


if ($CreateUser['status']) {
if ($CreateUser['status']) {
   $AddEmail = AddEmail($name, $headers);
   $AddEmail = AddEmail($email, $headers);
   if (!$AddEmail){ echo "error for user: $name while adding email";}
   if (!$AddEmail){ echo "error for user: $email while adding email";}
   else {echo "user: $name added successfuly";}
   else {echo "user: $email added successfuly";}
}
}


else { echo "error: ". $CreateUser['message']. " User: ". $CreateUser['user'] ;}
else { echo "error: ". $CreateUser['message']. " User: ". $CreateUser['user'] ; }</source>
</source>


== Voir aussi ==
== Voir aussi ==

Dernière version du 9 novembre 2022 à 23:31

Exemple de script PHP d'utilisation de l'API GLPI.

Source :

Autre source identique :

Exemple

<?php

// * * * * * Début des fonctions * * * * *

function OpenSession() {
    try {
        $api_url = "http://localhost/glpi10/apirest.php";

        // Jeton personnel (préférence du compte de l'utilisateur)
        $user_token = "SITuxell3jzgeCLCAiwcEfGz7s92qryCt7REDyrr";
        
        // Jeton d'API (préférence du compte de l'utilisateur)        
		$userapp_token = "eU5uFEuoa2r6LwxFvmp9FCSsNxCN4QwcWUmB8tEI";
        
        // Jeton d'application (app_token) ; (Configuration > Général > API
        $app_token = "My0pKoDQElYhBqOFzXhfzd3nrvury0ZphwAcYtll";
        
        $ch = curl_init();
        
        // ATTENTION, c'est bien le jeton d'application de l'utilisateur qui est utilisé pour un bon fonctionnement
        $url = $api_url . "/initSession?Content-Type=%20application/json&app_token=" . $app_token . "&user_token=" . $userapp_token;
        
        // ATTENTION, ne fonctionne pas (avec le jeton utilisateur)
        // $url = $api_url . "/initSession?Content-Type=%20application/json&app_token=" . $app_token . "&user_token=" . $user_token;
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($ch);
				echo ("json : " . $json);
        curl_close($ch);
        $obj = json_decode($json, true);
		echo ("objet : " . $obj);
        $sess_token = $obj['session_token'];
        $headers = array(
            'Content-Type: application/json',
            'App-Token: ' . $app_token,
            'Session-Token: ' . $sess_token
        );

        return $headers;
		}
	catch (Exception $e) {
        echo "session opening error: $e->getMessage()";
		}
	}

function CreateUser($name, $realname = null, $firstname = null, $entities_id, $pwd, $headers){
    try {
        $data = [
            'input' => [
                'name' => $name,
                "password" => $pwd,
                'realname' => $realname,
                'firstname' => $firstname,
                'language' => 'fr_FR',
                'is_active' => 1,
                'entities_id' => $entities_id,
				]
			];
        $input = json_encode($data);

        $api_url = "http://localhost/glpi10/apirest.php";
        $url = $api_url . "/User";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $input);

        $json = curl_exec($ch);
        curl_close ($ch);

        $res = json_decode($json, true);

        if ($res[0] == "ERROR_GLPI_ADD") {
            return ["status" => false, "message" => $res[1], "user" => $name];
			}
        else {
            return ["status" => true];
			}

		}
    catch (Exception $e) {echo "user creation error: $e->getMessage()";}
	}

function AddEmail($name, $headers) {
	// GET USER ID
    try {
        $api_url = "http://localhost/glpi10/apirest.php";
        $url = $api_url . "/search/User?criteria[0][field]=1&criteria[0][searchtype]=contains&criteria[0][value]=^" . $name . "$&forcedisplay[0]=2";

        //$url=$api_url . "/listSearchOptions/User";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        //curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
        $json = curl_exec($ch);
        curl_close($ch);
		} 
	catch (Exception $e) {
        echo "get user id error: $e->getMessage()";
		}

    $obj = json_decode($json, true);

	// ADD USER EMAIL
    try {
        $user_id = $obj['data']['0']['2'];
        $api_url = "http://localhost/apirest.php";
        $url = $api_url . "/User/" . $user_id . "/UserEmail/";
        $fields = '{"input": {"users_id":' . $user_id . ', "is_default":1, "is_dynamic":0, "email":"' . $email . '"}}';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        $json = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($json, true);
			//print_r($res);
        return true;
		} 
	catch (Exception $e) {
        echo "email add error: $e->getMessage()";
		}
	}
// * * * * * Fin des fonctions * * * * *

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
//  USER TEST
$name = "pagep2";
$realname = 'Page2';
$firstname = 'Philippe';
$email = 'philippe.page2@domaine.fr';
$entities_id = 0;
$pwd = sha1($name);
$headers = OpenSession();

$CreateUser = CreateUser($name, $realname, $firstname, $entities_id, $pwd, $headers);

if ($CreateUser['status']) {
   $AddEmail = AddEmail($email, $headers);
   if (!$AddEmail){ echo "error for user: $email while adding email";}
   else {echo "user: $email added successfuly";}
	}

else { echo "error: ". $CreateUser['message']. " User: ". $CreateUser['user'] ; }

Voir aussi