PHPackages                             stytch/stytch-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. stytch/stytch-php

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

stytch/stytch-php
=================

Stytch PHP SDK

v2.0.0(2mo ago)76.2k↓27.6%[1 issues](https://github.com/stytchauth/stytch-php/issues)MITPHPPHP ^8.1CI passing

Since Aug 22Pushed 2mo agoCompare

[ Source](https://github.com/stytchauth/stytch-php)[ Packagist](https://packagist.org/packages/stytch/stytch-php)[ Docs](https://stytch.com)[ RSS](/packages/stytch-stytch-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (21)Used By (0)

Stytch PHP SDK
==============

[](#stytch-php-sdk)

The Stytch PHP SDK makes it simple to integrate Stytch into your PHP application.

Installation
------------

[](#installation)

Install the SDK using Composer:

```
composer require stytch/stytch-php
```

Usage
-----

[](#usage)

### Consumer (B2C) Client

[](#consumer-b2c-client)

```
use Stytch\Consumer\Client;

$client = new Client(
    projectId: 'project-test-12345678-1234-1234-1234-123456789012',
    secret: 'secret-test-12345678901234567890123456789012',
);

// Create a user
$response = $client->users->create([
    'email' => 'user@example.com'
]);
```

### B2B Client

[](#b2b-client)

```
use Stytch\B2B\Client;

$client = new Client(
    projectId: 'project-test-12345678-1234-1234-1234-123456789012',
    secret: 'secret-test-12345678901234567890123456789012',
);

// Create an organization
$response = $client->organizations->create([
    'organization_name' => 'Example Corp',
    'organization_slug' => 'example-corp'
]);
```

Environment
-----------

[](#environment)

The SDK supports both test and live environments:

- `test`: Uses `https://test.stytch.com`
- `live`: Uses `https://api.stytch.com`

If no environment is specified, the SDK will auto-detect based on your project ID.

Async API Support
-----------------

[](#async-api-support)

All SDK methods have async counterparts that return Guzzle Promises, allowing for non-blocking operations and concurrent requests.

### Basic Async Usage

[](#basic-async-usage)

```
use GuzzleHttp\Promise\Utils;

// Single async request
$promise = $client->users->getAsync(['user_id' => 'user-123']);
$user = $promise->wait(); // Block until response

// Or use promise chaining
$promise->then(function($user) {
    echo "User: " . $user->name->firstName;
})->otherwise(function($exception) {
    echo "Error: " . $exception->getMessage();
});
```

### Concurrent Requests

[](#concurrent-requests)

```
use GuzzleHttp\Promise\Utils;

// Send multiple requests concurrently
$promises = [
    'user1' => $client->users->getAsync(['user_id' => 'user-123']),
    'user2' => $client->users->getAsync(['user_id' => 'user-456']),
    'user3' => $client->users->getAsync(['user_id' => 'user-789']),
];

// Wait for all to complete
$responses = Utils::settle($promises)->wait();

foreach ($responses as $key => $response) {
    if ($response['state'] === 'fulfilled') {
        echo "User {$key}: " . $response['value']->name->firstName . "\n";
    } else {
        echo "Error for {$key}: " . $response['reason']->getMessage() . "\n";
    }
}
```

### Advanced Promise Usage

[](#advanced-promise-usage)

```
use GuzzleHttp\Promise\Utils;

// Chain multiple operations
$client->users->createAsync(['email' => 'user@example.com'])
    ->then(function($createResponse) use ($client) {
        // User created, now send magic link
        return $client->magic_links->email->sendAsync([
            'user_id' => $createResponse->userId,
            'email' => $createResponse->user->emails[0]->email,
        ]);
    })
    ->then(function($sendResponse) {
        echo "Magic link sent! Request ID: " . $sendResponse->requestId;
    })
    ->otherwise(function($exception) {
        echo "Error in chain: " . $exception->getMessage();
    });
```

Error Handling
--------------

[](#error-handling)

The SDK throws `StytchException` for API errors:

```
use Stytch\Core\StytchException;

try {
    $response = $client->users->create(['email' => 'invalid-email']);
} catch (StytchException $e) {
    echo 'Error: ' . $e->getMessage();
    echo 'Status Code: ' . $e->getCode();
    echo 'Error Type: ' . $e->getErrorType();
}
```

### Async Error Handling

[](#async-error-handling)

Async methods handle errors through promise rejection:

```
$client->users->getAsync(['user_id' => 'invalid-id'])
    ->then(function($user) {
        // Success handler
        return $user;
    })
    ->otherwise(function($exception) {
        // Error handler - $exception is a StytchException
        echo "Error: " . $exception->getMessage();
        echo "Status: " . $exception->getCode();
        return null; // Return fallback value
    });
```

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Guzzle HTTP client

Upgrading to 2.0
----------------

[](#upgrading-to-20)

### PHP 8.4 Compatibility

[](#php-84-compatibility)

Version 2.0 adds full support for PHP 8.4 by using explicit nullable type declarations. If you're using PHP 8.4 with strict deprecation handling (common in PHPUnit/Laravel test environments), you **must** upgrade to v2.0+ to avoid deprecation errors.

**Fixed in v2.0:**

```
// v1.x - Implicit nullable (deprecated in PHP 8.4)
function example(array $data = null) { }

// v2.0+ - Explicit nullable (PHP 8.4 compatible)
function example(?array $data = null) { }
```

### Breaking Changes

[](#breaking-changes)

#### WhatsApp OTP Namespace Change

[](#whatsapp-otp-namespace-change)

The WhatsApp OTP class has been renamed to fix capitalization:

```
// v1.x
use Stytch\Consumer\Api\OTPsWhatsapp;  // Old
$client->otps->whatsapp->send(...);   // Still works

// v2.0+
use Stytch\Consumer\Api\OTPsWhatsApp;  // New (capital A)
$client->otps->whatsapp->send(...);   // Still works
```

**Impact:** Only affects code that directly imports or type-hints the `OTPsWhatsapp` class. The property access `$client->otps->whatsapp` remains unchanged.

### New Features in 2.0

[](#new-features-in-20)

- **Local JWT Authentication**: Authenticate JWTs locally without making an API call
- **RBAC Organization Policies**: Set and retrieve organization-specific RBAC policies
- **External ID Management**: Delete external IDs for users and organization members
- **DFP Email Risk API**: New device fingerprinting email risk endpoint

Testing
-------

[](#testing)

The SDK includes a comprehensive test suite covering both Consumer and B2B functionality.

### Setup Tests

[](#setup-tests)

1. Set up environment variables:

```
export STYTCH_PROJECT_ID="your-consumer-project-id"
export STYTCH_PROJECT_SECRET="your-consumer-project-secret"
export STYTCH_B2B_PROJECT_ID="your-b2b-project-id"
export STYTCH_B2B_PROJECT_SECRET="your-b2b-project-secret"
```

2. Install test dependencies:

```
composer install
```

### Running Tests

[](#running-tests)

```
# Run all tests
vendor/bin/phpunit

# Run Consumer tests only
vendor/bin/phpunit --testsuite Consumer

# Run B2B tests only
vendor/bin/phpunit --testsuite B2B

# Run with coverage
vendor/bin/phpunit --coverage-html coverage-html
```

### Test Coverage

[](#test-coverage)

The test suite covers:

**Consumer API:**

- Users: create, get, update, delete, search (sync &amp; async)
- Passwords: create, authenticate, strength check, reset operations (sync &amp; async)
- Sessions: authenticate, get, revoke, exchange (sync &amp; async)
- Magic Links: send, authenticate, invite operations (sync &amp; async)

**B2B API:**

- Organizations: create, get, update, delete, search (sync &amp; async)
- Organization Members: create, get, update, delete, search, reactivate (sync &amp; async)
- Passwords: create, authenticate, strength check, reset operations, discovery (sync &amp; async)

**Async Functionality:**

- Core HTTP client async methods (GET, POST, PUT, DELETE)
- Promise chaining and error handling
- Concurrent request processing
- Integration with all API classes

See [tests/README.md](tests/README.md) for detailed testing documentation.

Development
-----------

[](#development)

### Project Structure

[](#project-structure)

```
src/
├── Consumer/           # Consumer (B2C) API client
│   ├── Api/           # API endpoint classes
│   ├── Models/        # Response models
│   └── Client.php     # Main consumer client
├── B2B/               # B2B API client
│   ├── Api/           # API endpoint classes
│   ├── Models/        # Response models
│   └── Client.php     # Main B2B client
├── Core/              # Shared core functionality
└── Shared/            # Shared utilities

tests/
├── Consumer/          # Consumer API tests
├── B2B/              # B2B API tests
├── Integration/      # Integration tests
└── TestCase.php      # Base test class

```

### Code Quality

[](#code-quality)

This project uses:

- **PHPStan** for static analysis
- **PHPUnit** for testing
- **PSR-4** autoloading
- **PSR-12** coding standards

Run code quality checks:

```
vendor/bin/phpstan analyse src tests
vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

Please see our [contribution guidelines](CONTRIBUTING.md) for details on how to contribute to this project.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance84

Actively maintained with recent releases

Popularity31

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 57.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~16 days

Recently: every ~32 days

Total

13

Last Release

68d ago

Major Versions

v1.9.0 → v2.0.0-alpha2026-01-13

### Community

Maintainers

![](https://www.gravatar.com/avatar/a8b1e6acf96714e41bb45d598b72a26f0b19d2d474039c2de97bbc6e3470545d?d=identicon)[lgore](/maintainers/lgore)

---

Top Contributors

[![ci-stytch](https://avatars.githubusercontent.com/u/72180218?v=4)](https://github.com/ci-stytch "ci-stytch (12 commits)")[![logan-stytch](https://avatars.githubusercontent.com/u/119902778?v=4)](https://github.com/logan-stytch "logan-stytch (9 commits)")

---

Tags

sdkAuthenticationstytch

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/stytch-stytch-php/health.svg)

```
[![Health](https://phpackages.com/badges/stytch-stytch-php/health.svg)](https://phpackages.com/packages/stytch-stytch-php)
```

###  Alternatives

[google/auth

Google Auth Library for PHP

1.4k272.7M162](/packages/google-auth)[ellaisys/aws-cognito

AWS Cognito package that allows Auth and other related features using the AWS SDK for PHP

120220.7k1](/packages/ellaisys-aws-cognito)[kinde-oss/kinde-auth-php

Kinde PHP SDK for authentication

2369.5k3](/packages/kinde-oss-kinde-auth-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
