Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Workos Php Laravel Package

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.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require workos/workos-php
  1. Configure Environment: Add these to your .env:
    WORKOS_API_KEY=your_api_key_here
    WORKOS_CLIENT_ID=your_client_id_here
    
  2. Initialize Client:
    use WorkOS\WorkOS;
    
    $workos = new WorkOS(
        apiKey: getenv('WORKOS_API_KEY'),
        clientId: getenv('WORKOS_CLIENT_ID')
    );
    

First Use Case: SSO Flow

// 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;
}

New Use Case: User Management CORS/Redirect URIs

// 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
);

Implementation Patterns

Core Workflow: Client Initialization

// 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
);

Product-Specific Patterns

SSO Integration

// 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;

Enhanced User Management

// 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
);

Directory Sync

// Sync status
$status = $workos->directorySync()->getStatus();

// Trigger sync
$workos->directorySync()->triggerSync(
    connectionId: 'conn_123',
    syncType: 'full'
);

Error Handling Pattern

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');
}

Testing Pattern

// 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);
}

Gotchas and Tips

Common Pitfalls

  1. PHP Version Requirement:

    • Gotcha: SDK requires PHP 8.2+
    • Fix: Update your PHP version if using older versions
    • Tip: Use php -v to verify and update via pecl upgrade or your system package manager
  2. Static Configuration Gone:

    • Gotcha: WorkOS::setApiKey() no longer validates credentials
    • Fix: Always pass credentials to constructor or verify first API call
    • Tip: Add constructor validation:
      if (empty($workos->getApiKey()) || empty($workos->getClientId())) {
          throw new \RuntimeException('Missing WorkOS credentials');
      }
      
  3. Named Arguments Required:

    • Gotcha: Positional arguments may call wrong parameters
    • Fix: Always use named arguments:
      // Wrong (positional)
      $workos->userManagement()->createUsers('user@example.com', 'John');
      
      // Correct (named)
      $workos->userManagement()->createUsers(
          email: 'user@example.com',
          firstName: 'John'
      );
      
  4. New Model Changes:

    • Gotcha: UserRoleAssignment now includes source and sourceType fields
    • Fix: Update your code to handle the new properties:
      foreach ($user->roleAssignments as $assignment) {
          if (property_exists($assignment, 'source')) {
              $source = $assignment->source;
          }
      }
      
  5. Magic Auth Restoration:

    • Gotcha: CreateMagicAuth logic was removed in v7.x but restored in v8.1.0
    • Fix: If you were using this feature before, ensure your code still works:
      $magicAuth = $workos->userManagement()->createMagicAuth(
          email: 'user@example.com',
          redirectUri: 'https://your-app.com/callback'
      );
      

Debugging Tips

  1. 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
    );
    
  2. 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
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata