Skip to content

jamiemonksuk/frontegg-php-sdk

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Frontegg PHP SDK

alt text

Frontegg is a web platform where SaaS companies can set up their fully managed, scalable and brand aware - SaaS features and integrate them into their SaaS portals in up to 5 lines of code.

Installation

Use the package manager Composer to install Frontegg SDK for PHP.

composer require frontegg/php-sdk

Usage

Frontegg offers multiple components for integration with the Frontegg's scalable back-end and front-end libraries.

Simple Examples

Minimal configuration:

<?php

require_once './vendor/autoload.php';
require_once './src/Frontegg/autoload.php';

use Frontegg\Frontegg;
use Psr\Http\Message\RequestInterface;

$config = [
    'clientId' => 'YOUR_CLIENT_ID',
    'clientSecret' => 'YOUR_SECRET_API_KEY',
    'contextResolver' => function(RequestInterface $request) {
        return [
            'tenantId' => 'THE-TENANT-ID',
            'userId' => 'test-user-id',
            'permissions' => [],
        ];
    },
];

$frontegg = new Frontegg($config);
$frontegg->init();

Advanced configuration:

<?php

require_once './vendor/autoload.php';
require_once './src/Frontegg/autoload.php';

use Frontegg\Frontegg;
use Frontegg\HttpClient\FronteggCurlHttpClient;
use Psr\Http\Message\RequestInterface;

$config = [
    'clientId' => 'YOUR_CLIENT_ID',
    'clientSecret' => 'YOUR_SECRET_API_KEY',
    'apiBaseUrl' => 'https://api.frontegg.com/',
    'authenticationBaseUrl' => 'https://api.frontegg.com/',
    'apiUrls' => [
        'authentication' => '/auth/vendor',
        'audits' => '/audits',
    ],
    'contextResolver' => function(RequestInterface $request) {
        return [
            'tenantId' => 'THE-TENANT-ID',
            'userId' => 'test-user-id',
            'permissions' => [],
        ];
    },
    'disableCors' => false, // You can enable/disable CORS headers for Middleware Proxy.
    'httpClientHandler' => new FronteggCurlHttpClient(), // You can provide custom HTTP client.
];

$frontegg = new Frontegg($config);
$frontegg->init();

Configuration

Option Name Type Default Value Note
clientId string None Client Id. Required
clientSecret string None API Key. Required
contextResolver callable None Callback to provide context info. Required
apiBaseUrl string https://api.frontegg.com Base API URL
authenticationBaseUrl string https://api.frontegg.com Base URL used for authentication
vendorBaseUrl string https://my-domain.frontegg.com Base URL used for 'self service' endpoints
apiUrls array [] List of URLs of the API services
disableCors bool false Disabling CORS headers for Middleware Proxy
throwOnError bool false Throw exceptions on error. Otherwise use $frontegg->getXxxxxClient()->getApiError();
httpClientHandler special interface* Curl client** Custom HTTP client
apiVersion string 'v1' Not used yet. API version

*special interface - Frontegg\HttpClient\FronteggHttpClientInterface,

**Curl client - Frontegg\HttpClient\FronteggCurlHttpClient


Hosted Login Flow

This handles the hosted login workflow, which is the fastest way to get up and running.

The example endpoints /login and /callback can be configured as you like. The $redirect_uri should point to your callback location.

For loocal development, you may wish to fire up an Ngrok server to allow 2-way communication wih the platform.

/login

$code_verifier = mySecurityStringFunction();
$_SESSION['code_verifier'] = $code_verifier;
$auth_url = $frontegg->getGeneralAuthClient()->getLoginRedirectUrl($code_verifier, $redirect_uri);

header("Location: $auth_url");
exit();

/callback

$response_data = $frontegg->getGeneralAuthClient()->verifyCallback($_SESSION['code_verifier'], $redirect_uri, $_GET['code']);

Refresh token This would be done in the background, not via a specific endpoint. It would be best practive to never expose this to the client in a PHP implementation.

$response_data = $frontegg->getGeneralAuthClient()->refreshAccessToken($refresh_token);

User Admin

$response = $frontegg->getUsersClient()->getUserByEmail('jamie@pharosify.com');
$response = $frontegg->getUsersClient()->getUser('5c3eeac7-9b2b-9b2b-9b2b-6b25ed879093', $tenant_id);
$response = $frontegg->getUsersClient()->updateUserEmail('5c3eeac7-9b2b-9b2b-9b2b-6b25ed879093', 'jamie@pharosify.com');
$response = $frontegg->getUsersClient()->updateUserGlobally(
    '5c3eeac7-9b2b-9b2b-9b2b-6b25ed879093',
    '+61871207100',
    null,
    ['meta data' => 'this is so meta'],
    ['some data' => 'this is data'],
    true,
    'Person User'
);

Audits

Let your customers record the events, activities and changes made to their tenant.

Frontegg’s Managed Audit Logs feature allows a SaaS company to embed an end-to-end working feature in just several lines of code.

Sending audits

<?php

require_once './vendor/autoload.php';
require_once './src/Frontegg/autoload.php';

use Frontegg\Frontegg;
use Frontegg\HttpClient\FronteggCurlHttpClient;
use Psr\Http\Message\RequestInterface;

$config = [
    'clientId' => 'YOUR_CLIENT_ID',
    'clientSecret' => 'YOUR_SECRET_API_KEY',
    'apiBaseUrl' => 'https://api.frontegg.com/',
    'vendorBaseUrl' => 'https://my-domain.frontegg.com/',
    'apiUrls' => [
        'authentication' => '/auth/vendor',
        'audits' => '/audits',
    ],
    'contextResolver' => function(RequestInterface $request) {
        return [
            'tenantId' => 'THE-TENANT-ID',
            'userId' => 'test-user-id',
            'permissions' => [],
        ];
    },
    'disableCors' => false, // You can enable/disable CORS headers for Middleware Proxy.
    'throwOnError' => false, // Throw exceptions on error. Otherwise use $frontegg->getXxxxxClient()->getApiError();
    'httpClientHandler' => new FronteggCurlHttpClient(), // You can provide custom HTTP client.
    'apiVersion' => 'v1', // Not used yet. Coming soon.
];

$frontegg = new Frontegg($config);
$auditLog = $frontegg->sendAudit('THE-TENANT-ID', [
    'user' => 'testuser@t.com',
    'resource' => 'Portal',
    'action' => 'Login',
    'severity' => 'Info',
    'ip' => '123.1.2.3',
]);

Fetching audits

<?php

require_once './vendor/autoload.php';
require_once './src/Frontegg/autoload.php';

use Frontegg\Frontegg;
use Frontegg\HttpClient\FronteggCurlHttpClient;
use Psr\Http\Message\RequestInterface;

$config = [
    'clientId' => 'YOUR_CLIENT_ID',
    'clientSecret' => 'YOUR_SECRET_API_KEY',
    'contextResolver' => function(RequestInterface $request) {
        return [
            'tenantId' => 'THE-TENANT-ID',
            'userId' => 'test-user-id',
            'permissions' => [],
        ];
    },
    'apiBaseUrl' => 'https://api.frontegg.com/',
    'apiUrls' => [
        'authentication' => '/auth/vendor',
        'audits' => '/audits',
    ],
    'httpClientHandler' => new FronteggCurlHttpClient(), // You can provide custom HTTP client.
];

$frontegg = new Frontegg($config);
$auditsLog = $frontegg->getAudits(
    'THE-TENANT-ID',
    'Text to filter',
    0, // Offset
    10, // Count
    'action', // Field to sort by
    'ASC' // Sort direction ('ASC' or 'DESC')
    // ... Additional filters
);

Events

Events triggering is easy and maximum configurable for different notification channels.

require_once './vendor/autoload.php';
require_once './src/Frontegg/autoload.php';

use Frontegg\Events\Config\ChannelsConfig;
use Frontegg\Events\Config\DefaultProperties;
use Frontegg\Events\Config\TriggerOptions;
use Frontegg\Events\Channel\WebHookBody;
use Frontegg\Frontegg;
use Psr\Http\Message\RequestInterface;

$clientId = 'YOUR_CLIENT_ID';
$apikey = 'YOUR_API_KEY';
$config = [
    'clientId' => $clientId,
    'clientSecret' => $apikey,
    'contextResolver' => function(RequestInterface $request) {
        return [
            'tenantId' => 'THE-TENANT-ID',
            'userId' => 'test-user-id',
            'permissions' => [],
        ];
    },
];

$frontegg = new Frontegg($config);

$triggerOptions = new TriggerOptions(
    'eventKeyForTest',
    new DefaultProperties(
        'Default title',
        'Default description',
        [
            'name' => 'Policy 4',
            'id' => '11223456783245234',
        ]
    ),
    new ChannelsConfig(
        new WebHookBody([
            'title' => 'Test title!',
        ])
    ),
    'YOUR_TENANT_ID'
);
$response = $frontegg->triggerEvent($triggerOptions);

Middleware (Proxy)

The Frontegg Proxy forwards requests to the Frontegg API and pass back responses.

There is no Middleware (filters mechanism for HTTP request) in raw PHP, but in some frameworks it is. For example, in Laravel.

Here you can see example for raw PHP. You can easily adapt it for your framework with Middleware (for Laravel see https://github.com/frontegg/samples/tree/master/frontegg-laravel-starter).

<?php

require_once './vendor/autoload.php';
require_once './src/Frontegg/autoload.php';

use Frontegg\Frontegg;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\RequestInterface;

/**
 * Setup routing rule for "/frontegg" URIs.
 * Can be a part of middleware f.e. in Laravel.
 */
if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/frontegg') === 0) {
    $request = new Request('POST', $_SERVER['REQUEST_URI']);

    $response = handleFronteggUri($request);
}

// ...

function handleFronteggUri(RequestInterface $request)
{
    $clientId = 'YOUR_CLIENT_ID';
    $apikey = 'YOUR_API_KEY';
    $config = [
        'clientId' => $clientId,
        'clientSecret' => $apikey,
        'apiBaseUrl' => 'https://dev-api.frontegg.com/',
        'contextResolver' => function(RequestInterface $request) {
            return [
                'tenantId' => 'THE-TENANT-ID',
                'userId' => 'test-user-id',
                'permissions' => [],
            ];
        },
        'disableCors' => false,
    ];

    $frontegg = new Frontegg($config);
    $response = $frontegg->forward($request);

    return $response->getBody(); 
}

Another example of raw PHP and with adapting request parameters to Psr-7 Request object:

<?php

use Frontegg\Frontegg;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7\Request;

$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestUri = str_replace('/api/frontegg', '', $_SERVER['REQUEST_URI']);
$httpHeaders = getallheaders();
$body = http_build_query($requestMethod === 'GET' ? $_GET : $_POST);
// Here you can see how to setup Psr-7 Request object.
$adapterRequest = new Request($requestMethod, $requestUri, $httpHeaders, $body);

$clientId = 'CLIENT_ID';
$apikey = 'API_KEY';
$tenantId = 'THE_TENANT_ID';
$config = [
    'clientId' => $clientId,
    'clientSecret' => $apikey,
    'apiBaseUrl' => 'https://api.test.com/',
    'contextResolver' => function(RequestInterface $request) use ($tenantId) {
        return [
            'tenantId' => $tenantId,
            'userId' => 'test-user-id',
            'permissions' => [],
        ];
    },
    'disableCors' => false,
];

$frontegg = new Frontegg($config);

$response = $frontegg->forward($adapterRequest);

print $response->getBody();

Error Handling

This is applicable when throwOnError is set to false. Replace getUsersClient with whichever client you just used

$error = $frontegg->getUsersClient()->getApiError();
if ($error) {
    echo 'Request failed: ' . $error->getMessage();
    exit();
}

About

Frontegg PHP SDK

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages

  • PHP 99.4%
  • Other 0.6%