Search code examples
phpgoogle-apigoogle-api-php-client

Create New User Google Workspace PHP api


I am little new in PHP and Google Workspace. I am trying to create new user in my workspace. I have my code like this

putenv("GOOGLE_APPLICATION_CREDENTIALS=credentials.json");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($workspace_admin_email);
$client->setApplicationName("Quickstart");
$client->setScopes(["https://www.googleapis.com/auth/admin.directory.user"]);
$service = new Directory($client);

$optParams = array(
        'customer' => 'my_customer',
        'maxResults' => 500,
        'orderBy' => 'email',
    );
    $results = $service->users->listUsers($optParams);

Its working fine for get all users from my workspace but I do not know how I can create new user

They have not any PHP sample for same. They have given rest API documentation for javascript here

https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/insert

But I am using PHP in all places so I want do it with PHP. Let me know if anyone here can help me for same

Thanks!


Solution

  • You need to use the user insert method.

    //create user
    $user = new Google_Service_Directory_User();
    $name = new Google_Service_Directory_UserName();
    // SET THE ATTRIBUTES
    $name->setGivenName('John');
    $name->setFamilyName('Smith');
    $user->setName($name);
    $user->setHashFunction("MD5");
    $user->setPrimaryEmail("[email protected]");
    $user->setPassword(hash("md5","Horse"));
    
    
    try 
    { 
        $createUserResult = $service -> users -> insert($user); 
        var_dump($createUserResult); 
    }