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 interacting with the WorkOS API. Includes support for Single Sign-On, Directory Sync, Admin Portal, and Magic Link features. Configure via WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require workos/workos-php
    

    Ensure WORKOS_API_KEY and WORKOS_CLIENT_ID are set in your .env file.

  2. Initialize the Client:

    use WorkOS\WorkOS;
    
    $workos = new WorkOS(
        apiKey: env('WORKOS_API_KEY'),
        clientId: env('WORKOS_CLIENT_ID')
    );
    
  3. First Use Case: Fetch a User

    $user = $workos->userManagement()->getUser('user_123');
    

Where to Look First


Implementation Patterns

Core Workflow: SSO Integration

  1. Generate Auth URL:
    $authUrl = $workos->sso()->getAuthorizationUrl(
        redirectUri: 'https://your-app.com/callback',
        domain: 'your-org.example.com',
        state: json_encode(['return_to' => '/dashboard'])
    );
    
  2. Handle Callback:
    $profile = $workos->sso()->getProfileAndToken(
        code: $request->input('code'),
        clientId: env('WORKOS_CLIENT_ID'),
        clientSecret: env('WORKOS_API_KEY')
    );
    

Directory Sync

  1. List Connections:
    $connections = $workos->directorySync()->listConnections();
    
  2. Sync Users:
    $workos->directorySync()->syncUsers(
        connectionId: 'conn_123',
        users: [
            ['email' => 'user@example.com', 'status' => 'active']
        ]
    );
    

Admin Portal

  1. Create Portal:
    $portal = $workos->adminPortal()->createPortal(
        name: 'Admin Portal',
        domain: 'admin.your-app.com'
    );
    
  2. List Portals:
    $portals = $workos->adminPortal()->listPortals();
    

Pagination

$users = $workos->userManagement()->listUsers();
foreach ($users->autoPagingIterator() as $user) {
    // Process each user
}

Error Handling

try {
    $workos->userManagement()->createUser(email: 'user@example.com');
} catch (\WorkOS\Exception\BadRequestException $e) {
    // Handle validation errors
    dd($e->getErrors());
}

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement:

    • Gotcha: SDK requires PHP 8.2+. Older versions will fail.
    • Fix: Update your PHP environment or pin to a v4 SDK version.
  2. Static Methods Deprecated:

    • Gotcha: Avoid WorkOS::setApiKey() or WorkOS::getClientId(). Use the instantiated client.
    • Fix:
      $workos = new WorkOS(apiKey: env('WORKOS_API_KEY'));
      
  3. Named Arguments:

    • Gotcha: Positional arguments may break. Use named args:
      // ❌ Avoid
      $workos->userManagement()->createUser('user@example.com', 'active');
      
      // ✅ Prefer
      $workos->userManagement()->createUser(email: 'user@example.com', status: 'active');
      
  4. Session Handling:

    • Gotcha: UserManagement no longer handles sessions. Use SessionManager:
      $authResult = $workos->sessionManager()->authenticate(
          sessionData: $_COOKIE['wos-session'] ?? '',
          cookiePassword: env('SESSION_COOKIE_PASSWORD'),
          clientId: env('WORKOS_CLIENT_ID')
      );
      
  5. Pagination Changes:

    • Gotcha: PaginatedResourcePaginatedResponse. Access data via:
      $users = $page->data; // Instead of $page->users
      $after = $page->listMetadata['after'] ?? null;
      
  6. Resource Mutability:

    • Gotcha: Resources are now immutable. Avoid:
      $user->status = 'inactive'; // ❌ Fails
      
    • Fix: Use toArray() and recreate:
      $updatedUser = $workos->userManagement()->updateUser(
          userId: $user->id,
          status: 'inactive'
      );
      

Debugging Tips

  1. Enable Guzzle Debugging:

    $handler = \Http\Message\Mock\MockHandler::create();
    $stack = \Http\Message\Mock\MockClient::create($handler);
    $workos = new WorkOS(handler: $stack);
    
    • Useful for inspecting HTTP requests/responses during development.
  2. Check HTTP Headers:

    • Ensure Authorization: Bearer headers are included for protected endpoints.
    • Verify Content-Type: application/json for API requests.
  3. Rate Limits:

    • Catch RateLimitExceededException and implement retries with retryAfter:
      if ($e instanceof \WorkOS\Exception\RateLimitExceededException) {
          sleep($e->retryAfter);
          retry();
      }
      

Extension Points

  1. Custom HTTP Client:

    • Inject a Guzzle HandlerStack for middleware (e.g., logging, retries):
      $stack = \GuzzleHttp\HandlerStack::create();
      $stack->push(\GuzzleHttp\Middleware::retry());
      $workos = new WorkOS(handler: $stack);
      
  2. Webhook Verification:

    • Use WorkOS\Webhook for HMAC validation:
      $webhook = new \WorkOS\Webhook(
          secret: env('WORKOS_WEBHOOK_SECRET')
      );
      $valid = $webhook->verify($request->getContent(), $request->headers);
      
  3. Feature Flags:

    • Dynamically enable/disable features:
      $flags = $workos->featureFlags()->listFeatureFlags();
      if ($flags->data['new_ui'] === 'enabled') {
          // Enable new UI
      }
      

Configuration Quirks

  1. Environment Variables:

    • Default: SDK checks WORKOS_API_KEY and WORKOS_CLIENT_ID.
    • Override: Pass directly to constructor:
      $workos = new WorkOS(apiKey: 'custom_key', clientId: 'custom_id');
      
  2. Beta Features:

    • Pin to a specific beta version to avoid breaking changes:
      composer require workos/workos-php:5.0.0-beta.1
      
  3. Timeouts:

    • Configure via constructor:
      $workos = new WorkOS(timeout: 30); // 30 seconds
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope