LaunchKey SDK for PHP

Use this SDK to interact with the LaunchKey API in your PHP application.

Before you can begin using the LaunchKey API, you need a service. If you have not created a service yet, you can use our Getting Started Guide to create one.

Installation

Clone Source

$ git clone https://github.com/LaunchKey/launchkey-php.git

Packagist

LaunchKey PHP SDK on Packagist

$ php composer.phar require launchkey/launchkey

Add LaunchKey SDK To Your Project

The preferred way to install the LaunchKey SDK for PHP is to use Composer, the PHP package manager. If you do not use Composer, you will need to use an auto-loader. The LaunchKey SDK adheres to the PSR-4 auto-loader standard.

Create A LaunchKey SDK Client

Instantiate the \LaunchKey\SDK\Client object with your service key and private key from the Service details page of your LaunchKey Service. Additional configuration details can also be added via a Config object.

Definition

\LaunchKey\SDK\Client::factory($appKey, $privateKey=null, Config $config=null)

Parameters

Note

This method is overloaded. A Config object can be substituted for any parameter in the factory method. All subsequent parameters will be ignored. All parameters before the Config object will override values in the Config object.

appKey:integer|LaunchKeySDKConfig Unique 10-digit Service key from your Service details page in dashboard
privateKey:string|LaunchKeySDKConfig|null Private key of the RSA key pair for your Service (optional)
config:LaunchKeySDKConfig|null Config object with client configuration data (optional)

Return

The factory returns a \LaunchKey\SDK\Client object that is ready to make API calls.

No Config Example

$client = \LaunchKey\SDK\Client::factory(
    "1234567890",
    "SuperSecretAndWayRandomSecretKey",
    file_get_contents("/usr/local/etc/launchkey-app-private-key.pem")
);

Config Object

Using the config object allows you to set many configuration items:

Service Key:Unique 10-digit Service key from your Service details page in dashboard.
Private Key:The actual value of the private key from private.key
Private Key Location:Specify the location of the private key file instead of loading it yourself
Private Key Password:Encrypted RSA private keys will need a password to use them
Cache:The LaunchKey public key is cached to improve performance. The default is local memory cache. The config allows you to specify a different LaunchKeySDKCacheCache implementation.
Public Key TTL:The number of seconds the LaunchKey public key will live in the public key cache. The default is 60.
Event Dispatcher:Events are dispatched by the SDK client. The default Event Dispatcher is a local synchronous dispatcher.
Logger:Log debug and error messages with context using a PSR-3 compliant logger. By default, no logger is implemented.
API Base URL:If you are using a premise based LaunchKey Engine or are participating in a special preview test, you would specify the URL of the LaunchKey Engine API here.
API Request Timeout:How long the cURL client will wait for the remote API to respond before timing out. The default is 0 (infinite).
API Connect Timeout:How long the cURL client will wait while connecting to the remote API before timing out. The default is 0 (infinite).

Config Example

$config = new \LaunchKey\SDK\Config();
$config->setAppKey("1234567890")
    ->setPrivateKeyLocation("/usr/local/etc/launchkey-app-private-key.pem");
$client = \LaunchKey\SDK\Client::factory($config);

Authentication vs. Authorization

Authentication means that a user has been requested to create a persistent state within a service, resulting in an active session. Authentication can be remotely revoked by a user from a linked device or the dashboard.

Authorization either refers to approval for a singular action at a point in time such as a transaction, or it can mean a secondary authentication factor. It does not refer to creation of a persistent session via login.

User Authentication

To authenticate a user, use the authenticate() method with the user's LaunchKey username, user push ID, or white label internal identifier.

Definition

LaunchKey\SDK\Client::auth()->authenticate($username)

Parameters

username:string LaunchKey username, user push ID, or end-user identifier for the user

Response

The response will be a AuthRequest object describing the request.

Events

This call will trigger a launchkey.auth.request event with an AuthRequestEvent object.

Example

$authRequest = $client->auth()->authenticate("LaunchKeyUserName");

User Authorization

To request user authorization, use the authorize() method with the user's LaunchKey username, user push ID, or white label internal identifier.

Definition

LaunchKey\SDK\Client::auth()->authorize($username)

Parameters

username:string LaunchKey username, user push ID, or end-user identifier for the user

Response

The response will be a AuthRequest object describing the request.

Events

This call will trigger a launchkey.auth.request event with an AuthRequestEvent object.

Example

$authRequest = $client->auth()->authorize("LaunchKeyUserName");

Determine Status Of A Auth Request

Once you've sent an auth request to a user with either the php authenticate or php authorize method, You can check the status of that auth request with getStatus. Auth requests remain valid for 5 minutes.

Server Side Events vs. Polling

Although polling with getStatus can be used to complete the launch process, it is highly advised to use the php server side events methodology of implementing a callback endpoint and using the php handle callback method.

Definition

LaunchKey\SDK\Client::auth()->getStatus($authRequestId)

Parameters

authRequestId:string The authRequestId from the AuthRequest object returned from a previous php authorize or php authenticate call.

Response

The response will be an AuthResponse object describing the response.

Events

This call will trigger a launchkey.auth.response event with an AuthResponseEvent object.

Example

$authResponse = $client->auth()->getStatus("AuthRequestID");

When A User Logs Out

If a user logs out from within your service, you should inform our API so we can take your Service out of the user's authorization list.

Definition

LaunchKey\SDK\Client::auth()->clear($authRequestId)

Parameters

authRequestId:string The authRequestId from the AuthResponse object returned from a previous php authorize or php authenticate call.

Response

The will be no response.

Events

This call will trigger a launchkey.de-orbit.request event with a clearRequestEvent object.

Example

$client->auth()->clear("AuthRequestID");

Server Side Events (Callbacks)

Server side events, or callbacks, occur out of band as asynchronous events and are triggered by user interaction with a mobile authenticator App or Dashboard. The user interactions that are currently handled are Clear/Log Out and Launch Response. The LaunchKey PHP SDK Client provides a mechanism for dealing with all server side events in a single method. It determines which type of call is being executed and provides the proper response.

Definition

LaunchKey\SDK\Client::auth()->handleCallback($queryParameters)

Parameters

queryParameters:array Key/value pairs derived from the query string

Response

The response object will be either a clearCallback object if the server side event was based on a remote logout or an AuthResponse object if the server side event was based on a launch response.

Events

This call will trigger either a launchkey.callback.de-orbit event with a clearCallbackEvent object for a remote logout or a launchkey.callback.de-orbit event with an AuthResponse object for a launch response.

Example

$response = $client->auth()->handleCallback($_GET);

Extending With Event Subscribers

The LaunchKey SDK Client can be extended by subscribing to events through the event dispatcher. The events are triggered by the various method calls in the LaunchKey SDK Client.

Events

The event names are based on the NAME constant on each event class

launchkey.auth.request:Triggered when either the php authorize or php authenticate method is called.
launchkey.auth.response:Triggered when the getStatus method is called or during a php handle callback method call for a launch response.
launchkey.callback.de-orbit:Triggered during the php handle callback method call for a remote logout request from the user.
launchkey.de-orbit.request:Triggered when the clear method is called.
launchkey.whitelabel.user.created:Triggered when the createUser method is called.

Definition

LaunchKey\SDK\Client::eventDispatcher()->subscribe($eventName, $callable, $priority = 0)

Parameters

eventName:string Name of the event for which you wish to subscribe
callable:string|array|callable Callable to be executed when the event is dispatched. For more information on callable as related to your PHP version, see http://php.net/manual/en/language.types.callable.php
priority:integer (0) Priority of the callable for the event name. Higher priority will executed before lower priority. Callable items with the same priority cannot be guaranteed to execute in the order in which they are added.

Example

$client->eventDispatcher()->subscribe(
    \LaunchKey\SDK\Event\AuthResponseEvent::NAME,
    function (authResponseEvent) {
        $authorized = $authResponseEvent->getAuthResponse()->isAuthorized();
        if ($authorized !== null) {
            $stat = "login." . $authorized ? 'authorized' : 'denied';
            StatsD::getInstance()->increment($stat);
        }
    }
);

Add Logging For Better Visibility

A PSR-3 compliant logger can be passed to the config object to obtain better visibility into the operations of the client.

Certain events will occur and log errors but not throw an exception. A specific example of this case would be errors related to the caching of the LaunchKey RSA public key. If the cache provider throws an exception while either storing or retrieving a public key from cache, it will log the exception and continue on as the process can continue and complete successfully.

Providing a logger will allow for insight into cases where an error occurs and no Exception is thrown. A logger will also provide the ability to enable debug logging when unexpected results are occurring and more information is needed.

Definition

LaunchKey\SDK\Config->setLogger($logger)

Parameters

logger:PsrLogLoggerInterface \Psr\Log\LoggerInterface implementation to perform logging.

Example

$logger = new \Monolog\Logger('launchkey', new \Monolog\Handler\ErrorLogHandler());

$config = new \LaunchKey\SDK\Config();
$config->setAppKey("1234567890")
    ->setSecretKey("SuperSecretAndWayRandomSecretKey")
    ->setPrivateKeyLocation("/usr/local/etc/launchkey-app-private-key.pem")
    ->setLogger($logger);

$client = \LaunchKey\SDK\Client::factory($config);

Domain Objects

AuthRequest Object

The LaunchKey\SDK\Domain\AuthRequest object is used to describe an php authenticate/php authorize request.

Constructor

LaunchKey\SDK\Domain\AuthRequest($username, $userSession, $authRequestId)

Parameters

username:string LaunchKey username, user push ID, or end-user identifier for the user
userSession:boolean Is the request for a user session as opposed to a transaction.
authRequestId:string auth_request value from LaunchKey API v1 "auths" post

Getters

getUsername():string LaunchKey username, user push ID, or end-user identifier for the user
isUserSession():boolean Is the request for a user session as opposed to a transaction.
getAuthRequestId():string auth_request value from LaunchKey API v1 "auths" post

AuthResponse Object

The LaunchKey\SDK\Domain\AuthResponse object is used to describe an php authenticate/php authorize response.

Constructor

LaunchKey\SDK\Domain\AuthResponse($completed, $authRequestId, $userHash, $organizationUserId, $userPushId, $deviceId, $authorized)

Parameters

completed:boolean (false) Has the request completed. The request is considered completed when the user as accepted or rejected the auth request.
authRequestId:string auth_request value from LaunchKey API v1 "auths" post
userHash:string Permanent and unique user hash that identifies the user. The user hash will be used by php server side events to identify the user when a logout request has been made by the user from either the dashboard or a linked device.
organizationUserId:string Identifies a user across an organization. This will be NULL for developer Services as they do not belong to an organization.
userPushId:string Identifies the user with the Service. This can be used for future php authenticate/php authorize calls.
deviceId:string Unique identifier for the device with which the user responded to the request.
authorized:boolean Has the request been authorized by the user. Will be NULL if the request has not been completed.

Getters

getAuthRequestId():string auth_request value from LaunchKey API v1 "auths" post
isCompleted():boolean Has the request completed. The request is considered completed when the user as accepted or rejected the auth request.
isAuthorized():boolean Has the request been authorized by the user. Will be NULL if the request has not been completed.
getUserHash():string Permanent and unique user hash that identifies the user. The user hash will be used by php server side events to identify the user when a logout request has been made by the user from either the dashboard or a linked device.
getOrganizationUserId():string Get the ID which identifies a user across an organization. This will be NULL for subscriber Services as they do not belong to an organization.
getUserPushId():string Get the identifier which identifies the user with the Service. This can be used for future php authenticate/php authorize requests for the Service that was used in the php authenticate/php authorize request.
getDeviceId():string Get the unique identifier for the device with which the user responded to the request.

clearRequest Object

The LaunchKey\SDK\Domain\clearRequest object is used to describe a logout request.

Constructor

LaunchKey\SDK\Domain\clearRequest($authRequestId)

Parameters

authRequestId:string authRequestId from the AuthRequest object returned from a previous php authorize/php authenticate call that should now be cleared.

Getters

getAuthRequestId():string authRequestId from the AuthRequest object returned from a previous php authorize/php authenticate call that should now be cleared.

clearCallback Object

The LaunchKey\SDK\Domain\clearCallback object is used to describe a logout callback from a server side event triggered by a linked mobile device or the Dashboard.

Constructor

LaunchKey\SDK\Domain\clearCallback($clearTime, $userHash)

Parameters

clearTime:DateTime Date/time when the de-orbit server side event occurred. This can be used to validate a request and prevent replay attacks.
userHash:string User hash for the user that requested to log out.

Getters

getclearTime():DateTime Date/time when the logout server side event occurred. This can be used to validate a request and prevent replay attacks.
getUserHash():string User hash for the user that requested to log out.

WhiteLabelUser Object

The LaunchKey\SDK\Domain\WhiteLabelUser object is used to describe the data necessary to link a device with a new or existing end-user.

Constructor

LaunchKey\SDK\Domain\WhiteLabelUser($qrCodeUrl, $code)

Parameters

qrCodeUrl:string The URL for a QR code image to be used by the authenticator mobile service for the purpose of automatically linking a device with the end-user.
code:string The code to to be used by the authenticator mobile service for the purpose of manually linking a device with the end-user.

Getters

getQrCodeUrl():string The URL for a QR code image to be used by the LaunchKey mobile service for the purpose of automatically linking a device with the end-user.
getCode():string The code to to be used by the LaunchKey mobile service for the purpose of manually linking a device with the end-user.

Events

AuthRequestEvent Object

The LaunchKey\SDK\Event\AuthRequestEvent object is used to describe events around user php authorize and php authenticate requests.

Constructor

LaunchKey\SDK\Event\AuthRequestEvent($authRequest)

Parameters

authRequest:LaunchKeySDKDomainAuthRequest AuthRequest object associated with the event.

Getters

getAuthRequest():LaunchKeySDKDomainAuthRequest AuthRequest object associated with the event.

AuthResponseEvent Object

The LaunchKey\SDK\Event\AuthResponseEvent object is used to describe events around user php authorize and php authenticate responses.

Constructor

LaunchKey\SDK\Event\AuthResponseEvent($authResponse)

Parameters

authResponse:LaunchKeySDKDomainAuthResponse AuthResponse object associated with the event.

Getters

getAuthResponse():LaunchKeySDKDomainAuthResponse AuthResponse object associated with the event.

clearRequestEvent Object

The LaunchKey\SDK\Event\clearRequestEvent object is used to describe events around clear requests.

Constructor

LaunchKey\SDK\Event\clearRequestEvent($clearRequest)

Parameters

clearRequest:LaunchKeySDKDomainclearRequest clearRequest object associated with the event.

Getters

getclearRequest():LaunchKeySDKDomainclearRequest clearRequest object associated with the event.

clearCallbackEvent Object

The LaunchKey\SDK\Event\clearCallbackEvent object is used to describe server side remote logout events.

Constructor

LaunchKey\SDK\Event\clearCallbackEvent($clearCallback)

Parameters

clearCallback:LaunchKeySDKDomainclearCallback clearCallback object associated with the event.

Getters

getclearCallback():LaunchKeySDKDomainclearCallback clearCallback object associated with the event.

WhiteLabelUserCreatedEvent Object

The LaunchKey\SDK\Event\WhiteLabelUserCreatedEvent object is used to describe events end-user creation events.

Constructor

LaunchKey\SDK\Event\WhiteLabelUserCreatedEvent($whiteLabelUser)

Parameters

whiteLabelUser:LaunchKeySDKDomainWhiteLabelUser WhiteLabelUser object associated with the event.

Getters

getWhiteLabelUser():LaunchKeySDKDomainWhiteLabelUser WhiteLabelUser object associated with the event.

User Contributed

LaunchKey links to user contributed code as a resource to its community. LaunchKey does not in any way guarantee or warrant the quality and security of these code bases. User contributed code is supported by the creators. If you do find a link from the site to user contributed code that is malicious or inappropriate in any way, please report that link to LaunchKey immediately and we will investigate the claim. Submit any issue to LaunchKey support at https://launchkey.com./support. ×