workos/workos-php
Official WorkOS PHP SDK for integrating SSO, Directory Sync, Admin Portal, Magic Links, and more. Configure with your WorkOS API key and client ID to access the WorkOS API from PHP applications via a convenient, maintained client.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require workos/workos-php
.env:
WORKOS_API_KEY=your_api_key_here
WORKOS_CLIENT_ID=your_client_id_here
use WorkOS\WorkOS;
$workos = new WorkOS(
apiKey: getenv('WORKOS_API_KEY'),
clientId: getenv('WORKOS_CLIENT_ID')
);
// Generate an auth URL
$authUrl = $workos->sso()->getAuthorizationUrl(
redirectUri: 'https://your-app.com/callback',
domain: 'your-org.workos.com'
);
// Handle callback (pseudo-code)
if (isset($_GET['code'])) {
$tokenResponse = $workos->sso()->getProfileAndToken(
code: $_GET['code'],
clientSecret: getenv('WORKOS_API_KEY') // Note: API key as client secret
);
$profile = $tokenResponse->profile;
}
// Fetch CORS origins
$corsOrigins = $workos->userManagement()->getCorsOrigins();
// Fetch redirect URIs
$redirectUris = $workos->userManagement()->getRedirectUris();
// Authorize with max_age parameter
$authResult = $workos->userManagement()->authorize(
userId: 'user_123',
maxAge: 3600 // 1 hour
);
// Singleton pattern (recommended for most apps)
$workos = new WorkOS(
apiKey: env('WORKOS_API_KEY'),
clientId: env('WORKOS_CLIENT_ID'),
baseUrl: env('WORKOS_API_BASE_URL', 'https://api.workos.com') // Optional
);
// Per-request client (for testing or multi-tenant)
$workos = new WorkOS(
apiKey: $tenantApiKey,
clientId: $tenantClientId
);
// 1. Start auth flow
$authUrl = $workos->sso()->getAuthorizationUrl(
redirectUri: route('sso.callback'),
domain: 'your-org.workos.com',
state: json_encode(['return_to' => '/dashboard'])
);
// 2. Handle callback
$tokenResponse = $workos->sso()->getProfileAndToken(
code: $request->query('code'),
clientSecret: env('WORKOS_API_KEY')
);
// 3. Use tokens
$profile = $tokenResponse->profile;
$accessToken = $tokenResponse->accessToken;
// Create user with role assignment source
$user = $workos->userManagement()->createUsers(
email: 'user@example.com',
firstName: 'John',
lastName: 'Doe'
);
// List users with role assignment sources
$page = $workos->userManagement()->listUsers(
limit: 10,
after: $lastCursor
);
foreach ($page->autoPagingIterator() as $user) {
// Process role assignments with sources
foreach ($user->roleAssignments as $assignment) {
$source = $assignment->source; // New in v8.1.0
$sourceType = $assignment->sourceType; // New enum
}
}
// Get CORS origins and redirect URIs
$corsOrigins = $workos->userManagement()->getCorsOrigins();
$redirectUris = $workos->userManagement()->getRedirectUris();
// Authorize with max_age parameter
$authResult = $workos->userManagement()->authorize(
userId: 'user_123',
maxAge: 3600 // 1 hour
);
// Sync status
$status = $workos->directorySync()->getStatus();
// Trigger sync
$workos->directorySync()->triggerSync(
connectionId: 'conn_123',
syncType: 'full'
);
use WorkOS\Exception\WorkOSException;
try {
$result = $workos->someService()->someOperation();
} catch (WorkOSException $e) {
// Handle specific exceptions
if ($e instanceof \WorkOS\Exception\AuthenticationException) {
// Redirect to login
}
// Log all errors
Log::error("WorkOS Error: {$e->getMessage()}", [
'status' => $e->getStatusCode(),
'request_id' => $e->getRequestId()
]);
// Re-throw or return user-friendly message
throw new \RuntimeException('Service unavailable');
}
// In PHPUnit tests
public function testUserRoleAssignmentSources()
{
$workos = new WorkOS(
apiKey: 'test_key',
clientId: 'test_client',
baseUrl: 'https://api.workos.com'
);
$mockUser = new \WorkOS\Response\UserResponse();
$mockUser->roleAssignments = [
(object)[
'source' => 'AUTO_PROVISIONING',
'sourceType' => \WorkOS\Enum\UserRoleAssignmentSourceType::AUTO_PROVISIONING
]
];
$this->getMockBuilder()
->expects($this->once())
->willReturn($mockUser);
$result = $workos->userManagement()->listUsers(limit: 1);
$this->assertCount(1, $result->data[0]->roleAssignments);
}
PHP Version Requirement:
php -v to verify and update via pecl upgrade or your system package managerStatic Configuration Gone:
WorkOS::setApiKey() no longer validates credentialsif (empty($workos->getApiKey()) || empty($workos->getClientId())) {
throw new \RuntimeException('Missing WorkOS credentials');
}
Named Arguments Required:
// Wrong (positional)
$workos->userManagement()->createUsers('user@example.com', 'John');
// Correct (named)
$workos->userManagement()->createUsers(
email: 'user@example.com',
firstName: 'John'
);
New Model Changes:
UserRoleAssignment now includes source and sourceType fieldsforeach ($user->roleAssignments as $assignment) {
if (property_exists($assignment, 'source')) {
$source = $assignment->source;
}
}
Magic Auth Restoration:
CreateMagicAuth logic was removed in v7.x but restored in v8.1.0$magicAuth = $workos->userManagement()->createMagicAuth(
email: 'user@example.com',
redirectUri: 'https://your-app.com/callback'
);
Enable Guzzle Debugging:
$handlerStack = \GuzzleHttp\HandlerStack::create();
$handlerStack->push(
\GuzzleHttp\Middleware::tap(function ($request) {
Log::debug('WorkOS Request', [
'url' => (string)$request->getUri(),
'method' => $request->getMethod(),
'headers' => $request->getHeaders(),
'body' => $request->getBody() ? $request->getBody()->getContents() : null
]);
})
);
$workos = new WorkOS(
apiKey: '...',
clientId: '...',
handler: $handlerStack
);
Inspect Role Assignment Sources:
try {
$users = $workos->userManagement()->listUsers();
foreach ($users->data as $user) {
Log::debug('User Role Assignments', [
'userId' => $user->id,
'assignments' => array_map(
fn($a) => [
'source' => $a->source,
'sourceType' => $a->sourceType->value
],
$user->roleAssignments
)
]);
}
} catch (WorkOSException $e) {
Log
How can I help you explore Laravel packages today?