clerkinc / backend-php
Installs: 1 433
Dependents: 0
Suggesters: 0
Security: 0
Stars: 15
Watchers: 2
Forks: 11
Open Issues: 3
Requires
- php: >=8.2
- brick/date-time: >=0.7.0
- brick/math: >=0.12.1
- firebase/php-jwt: ^6.10
- galbar/jsonpath: >=3.0
- guzzlehttp/guzzle: ^7.0
- phpdocumentor/type-resolver: >=1.8
- phpseclib/phpseclib: ^3.0
- speakeasy/serializer: ^4.0.3
Requires (Dev)
- laravel/pint: >=1.21.2
- phpstan/phpstan: >=2.1.0
- phpunit/phpunit: >=10
- roave/security-advisories: dev-latest
- dev-main
- v0.3.0
- v0.2.0
- v0.1.6
- v0.1.5
- dev-speakeasy-sdk-regen-1753403775
- dev-tm/update-inputs-to-latest
- dev-speakeasy-sdk-regen-1741825842
- dev-tm/pinned-version
- dev-speakeasy-sdk-regen-1739320134
- dev-speakeasy-sdk-regen-1738024123
- dev-vaggelis/regenerate-with-specified-version
- dev-vaggelis/fix-inconsistent-class-names
- dev-vaggelis/add-overlays
This package is auto-updated.
Last update: 2025-08-29 18:15:57 UTC
README
clerkinc/backend-php
Overview
Clerk is the easiest way to add authentication and user management to your application. To gain a better understanding of the Clerk Backend API, refer to the Backend API documentation.
Summary
Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.
Versions
When the API changes in a way that isn't compatible with older versions, a new version is released.
Each version is identified by its release date, e.g. 2025-04-10
. For more information, please see Clerk API Versions.
Please see https://clerk.com/docs for more information.
More information about the API can be found at https://clerk.com/docs
Table of Contents
SDK Installation
The SDK relies on Composer to manage its dependencies.
To install the SDK and add it as a dependency to an existing composer.json
file:
composer require "clerkinc/backend-php"
Usage
Retrieve your Backend API key from the API Keys screen in your Clerk dashboard and set it as an environment variable in a .env
file:
CLERK_PUBLISHABLE_KEY=pk_******* CLERK_SECRET_KEY=sk_******
SDK Example Usage
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Clerk\Backend; $sdk = Backend\ClerkBackend::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $response = $sdk->emailAddresses->get( emailAddressId: '<id>' ); if ($response->emailAddress !== null) { // handle response }
Request Authentication
Use the authenticateRequest method to authenticate a request from your app's frontend (when using a Clerk frontend SDK) to Clerk's Backend API. For example the following utility function checks if the user is effectively signed in:
use GuzzleHttp\Psr7\Request; use Clerk\Backend\Helpers\Jwks\AuthenticateRequestOptions; use Clerk\Backend\Helpers\Jwks\AuthenticateRequest; use Clerk\Backend\Helpers\Jwks\RequestState; class UserAuthentication { public static function isSignedIn(Request $request): bool { $options = new AuthenticateRequestOptions( secretKey: getenv("CLERK_SECRET_KEY"), authorizedParties: ["https://example.com"] ); $requestState = AuthenticateRequest::authenticateRequest($request, $options); return $requestState->isSignedIn(); } }
If the request is correctly authenticated, the token's payload is made available in $requestState->payload
. Otherwise the reason for the token verification failure is given by requestState->errorReason
.
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
Name | Type | Scheme |
---|---|---|
bearerAuth |
http | HTTP Bearer |
To authenticate with the API the bearerAuth
parameter must be set when initializing the SDK. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Clerk\Backend; $sdk = Backend\ClerkBackend::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $response = $sdk->miscellaneous->getPublicInterstitial( request: $request ); if ($response->statusCode === 200) { // handle response }
Available Resources and Operations
Available methods
actorTokens
allowlistIdentifiers
- list - List all identifiers on the allow-list
- create - Add identifier to the allow-list
- delete - Delete identifier from allow-list
awsCredentials
betaFeatures
- updateInstanceSettings - Update instance settings
updateProductionInstanceDomain- Update production instance domain ⚠️ Deprecated
blocklistIdentifiers
- list - List all identifiers on the block-list
- create - Add identifier to the block-list
- delete - Delete identifier from block-list
clients
commerce
- listPlans - List all commerce plans
- listSubscriptionItems - List all subscription items
- cancelSubscriptionItem - Cancel a subscription item
domains
- list - List all instance domains
- add - Add a domain
- delete - Delete a satellite domain
- update - Update a domain
emailAddresses
- create - Create an email address
- get - Retrieve an email address
- delete - Delete an email address
- update - Update an email address
emailAndSmsTemplates
upsert- Update a template for a given type and slug ⚠️ Deprecated
emailSMSTemplates
list- List all templates ⚠️ Deprecatedget- Retrieve a template ⚠️ Deprecatedrevert- Revert a template ⚠️ DeprecatedtoggleTemplateDelivery- Toggle the delivery by Clerk for a template of a given type and slug ⚠️ Deprecated
experimentalAccountlessApplications
- create - Create an accountless application [EXPERIMENTAL]
- complete - Complete an accountless application [EXPERIMENTAL]
instanceSettings
- get - Fetch the current instance
- update - Update instance settings
- updateRestrictions - Update instance restrictions
- changeDomain - Update production instance domain
- updateOrganizationSettings - Update instance organization settings
invitations
- create - Create an invitation
- list - List all invitations
- bulkCreate - Create multiple invitations
- revoke - Revokes an invitation
jwks
- getJWKS - Retrieve the JSON Web Key Set of the instance
jwtTemplates
- list - List all templates
- create - Create a JWT template
- get - Retrieve a template
- update - Update a JWT template
- delete - Delete a Template
m2m
- createToken - Create a M2M Token
- listTokens - Get M2M Tokens
- revokeToken - Revoke a M2M Token
- verifyToken - Verify a M2M Token
machines
- list - Get a list of machines for an instance
- create - Create a machine
- get - Retrieve a machine
- update - Update a machine
- delete - Delete a machine
- getSecretKey - Retrieve a machine secret key
- createScope - Create a machine scope
- deleteScope - Delete a machine scope
miscellaneous
- getPublicInterstitial - Returns the markup for the interstitial page
oauthAccessTokens
- verify - Verify an OAuth Access Token
oauthApplications
- list - Get a list of OAuth applications for an instance
- create - Create an OAuth application
- get - Retrieve an OAuth application by ID
- update - Update an OAuth application
- delete - Delete an OAuth application
- rotateSecret - Rotate the client secret of the given OAuth application
organizationDomains
- create - Create a new organization domain.
- list - Get a list of all domains of an organization.
- update - Update an organization domain.
- delete - Remove a domain from an organization.
- listAll - List all organization domains
organizationInvitations
- getAll - Get a list of organization invitations for the current instance
- create - Create and send an organization invitation
- list - Get a list of organization invitations
- bulkCreate - Bulk create and send organization invitations
listPending- Get a list of pending organization invitations ⚠️ Deprecated- get - Retrieve an organization invitation by ID
- revoke - Revoke a pending organization invitation
organizationMemberships
- create - Create a new organization membership
- list - Get a list of all members of an organization
- update - Update an organization membership
- delete - Remove a member from an organization
- updateMetadata - Merge and update organization membership metadata
organizations
- list - Get a list of organizations for an instance
- create - Create an organization
- get - Retrieve an organization by ID or slug
- update - Update an organization
- delete - Delete an organization
- mergeMetadata - Merge and update metadata for an organization
- uploadLogo - Upload a logo for the organization
- deleteLogo - Delete the organization's logo.
- getBillingSubscription - Retrieve an organization's billing subscription
phoneNumbers
- create - Create a phone number
- get - Retrieve a phone number
- delete - Delete a phone number
- update - Update a phone number
proxyChecks
- verify - Verify the proxy configuration for your domain
redirectUrls
- list - List all redirect URLs
- create - Create a redirect URL
- get - Retrieve a redirect URL
- delete - Delete a redirect URL
samlConnections
- list - Get a list of SAML Connections for an instance
- create - Create a SAML Connection
- get - Retrieve a SAML Connection by ID
- update - Update a SAML Connection
- delete - Delete a SAML Connection
sessions
- list - List all sessions
- create - Create a new active session
- get - Retrieve a session
- refresh - Refresh a session
- revoke - Revoke a session
- createToken - Create a session token
- createTokenFromTemplate - Create a session token from a jwt template
signInTokens
signUps
templates
preview- Preview changes to a template ⚠️ Deprecated
testingTokens
- create - Retrieve a new testing token
users
- list - List all users
- create - Create a new user
- count - Count users
- get - Retrieve a user
- update - Update a user
- delete - Delete a user
- ban - Ban a user
- unban - Unban a user
- bulkBan - Ban multiple users
- bulkUnban - Unban multiple users
- lock - Lock a user
- unlock - Unlock a user
- setProfileImage - Set user profile image
- deleteProfileImage - Delete user profile image
- updateMetadata - Merge and update a user's metadata
- getBillingSubscription - Retrieve a user's billing subscription
- getOAuthAccessToken - Retrieve the OAuth access token of a user
- getOrganizationMemberships - Retrieve all memberships for a user
- getOrganizationInvitations - Retrieve all invitations for a user
- verifyPassword - Verify the password of a user
- verifyTotp - Verify a TOTP or backup code for a user
- disableMfa - Disable a user's MFA methods
- deleteBackupCodes - Disable all user's Backup codes
- deletePasskey - Delete a user passkey
- deleteWeb3Wallet - Delete a user web3 wallet
- deleteTOTP - Delete all the user's TOTPs
- deleteExternalAccount - Delete External Account
- getInstanceOrganizationMemberships - Get a list of all organization memberships within an instance.
waitlistEntries
- list - List all waitlist entries
- create - Create a waitlist entry
- invite - Invite a waitlist entry
- reject - Reject a waitlist entry
webhooks
- createSvixApp - Create a Svix app
- deleteSvixApp - Delete a Svix app
- generateSvixAuthURL - Create a Svix Dashboard URL
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide an Options
object built with a RetryConfig
object to the call:
declare(strict_types=1); require 'vendor/autoload.php'; use Clerk\Backend; use Clerk\Backend\Utils\Retry; $sdk = Backend\ClerkBackend::builder()->build(); $response = $sdk->miscellaneous->getPublicInterstitial( request: $request, options: Utils\Options->builder()->setRetryConfig( new Retry\RetryConfigBackoff( initialInterval: 1, maxInterval: 50, exponent: 1.1, maxElapsedTime: 100, retryConnectionErrors: false, ))->build() ); if ($response->statusCode === 200) { // handle response }
If you'd like to override the default retry strategy for all operations that support retries, you can pass a RetryConfig
object to the SDKBuilder->setRetryConfig
function when initializing the SDK:
declare(strict_types=1); require 'vendor/autoload.php'; use Clerk\Backend; use Clerk\Backend\Utils\Retry; $sdk = Backend\ClerkBackend::builder() ->setRetryConfig( new Retry\RetryConfigBackoff( initialInterval: 1, maxInterval: 50, exponent: 1.1, maxElapsedTime: 100, retryConnectionErrors: false, ) ) ->build(); $response = $sdk->miscellaneous->getPublicInterstitial( request: $request ); if ($response->statusCode === 200) { // handle response }
Error Handling
Handling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.
By default an API error will raise a Errors\SDKException
exception, which has the following properties:
Property | Type | Description |
---|---|---|
$message |
string | The error message |
$statusCode |
int | The HTTP status code |
$rawResponse |
?\Psr\Http\Message\ResponseInterface | The raw HTTP response |
$body |
string | The response content |
When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the delete
method throws the following exceptions:
Error Type | Status Code | Content Type |
---|---|---|
Errors\ClerkErrors | 400, 401, 403, 404 | application/json |
Errors\SDKException | 4XX, 5XX | */* |
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Clerk\Backend; use Clerk\Backend\Models\Errors; $sdk = Backend\ClerkBackend::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); try { $response = $sdk->awsCredentials->delete( id: '<id>' ); if ($response->deletedObject !== null) { // handle response } } catch (Errors\ClerkErrorsThrowable $e) { // handle $e->$container data throw $e; } catch (Errors\SDKException $e) { // handle default exception throw $e; }
Server Selection
Override Server URL Per-Client
The default server can be overridden globally using the setServerUrl(string $serverUrl)
builder method when initializing the SDK client instance. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Clerk\Backend; $sdk = Backend\ClerkBackend::builder() ->setServerURL('https://api.clerk.com/v1') ->build(); $response = $sdk->miscellaneous->getPublicInterstitial( request: $request ); if ($response->statusCode === 200) { // handle response }
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Support
You can get in touch with us in any of the following ways:
- Join the official community Clerk Discord server
- Create a GitHub Discussion
- Contact options listed on Clerk Support page
Contributing
We're open to all community contributions!
Security
clerkinc/backend-php
follows good practices of security, but 100% security cannot be assured.
clerkinc/backend-php
is provided "as is" without any warranty. Use at your own risk.
For more information and to report security issues, please refer to the security documentation.
License
This project is licensed under the MIT license.
See LICENSE for more information.