PHP code example of slashid / php

1. Go to this page and download the library: Download slashid/php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

slashid / php example snippets


use SlashId\Php\SlashIdSdk;

$sdk = new SlashIdSdk(SlashIdSdk::ENVIRONMENT_PRODUCTION, '412edb57-ae26-f2aa-9999-770021ed52d1', 'z0dlY-nluiq8mcvm8YTolSkJV6e9');

// GET https://api.slashid.com/persons
$response = $sdk->get('/persons');

// $response:
[
    ['person_id' => '1111-1111-1111', 'handles' => [...]],
    ['person_id' => '2222-2222-2222', 'handles' => [...]],
]

// GET https://api.slashid.com/persons/1111-1111-1111?fields=handles,groups,attributes
$response = $sdk->get('/persons/1111-1111-1111', [
    'fields' => ['handles', 'groups', 'attributes'],
]);

// $response:
['person_id' => '1111-1111-1111', 'handles' => [...]]

// POST https://api.slashid.com/persons
$response = $sdk->post('/persons', [
    'active' => true,
    'handles' => [
        [
            'type' => 'email_address',
            'value' => '[email protected]'
        ],
    ],
]);

// $response:
['person_id' => '1111-1111-1111', 'handles' => [...]]

// PATCH https://api.slashid.com/persons/1111-1111-1111
$response = $sdk->patch('/persons/1111-1111-1111', [
    'active' => true,
    'handles' => [
        [
            'type' => 'email_address',
            'value' => '[email protected]'
        ],
    ],
]);

// $response:
['person_id' => '1111-1111-1111', 'handles' => [...]]

// PUT https://api.slashid.com/persons/1111-1111-1111
$response = $sdk->put('/persons', [
    'active' => true,
    'handles' => [
        [
            'type' => 'email_address',
            'value' => '[email protected]'
        ],
    ],
]);

// $response:
['person_id' => '1111-1111-1111', 'handles' => [...]]

// DELETE https://api.slashid.com/persons/1111-1111-1111
$sdk->delete('/persons/1111-1111-1111');

$sdk->delete('/organizations/webhooks/99999-99999-99999/triggers', [
    'trigger_type' => 'event',
    'trigger_name' => 'PersonCreated_v1',
]);

$response = $sdk->getClient()->request('GET', '/persons/bulk-import', [
    'headers' => [
        'Accept' => 'text/csv',
    ],
]);

$csvContents = (string) $response->getBody();

// Gets an informative message about the error.
$exception->getMessage();

// Gets the request object, with information about the endpoint and the data in the request.
$request = $exception->getRequest();

// Gets the response object, with HTTP response code and the response contents.
$response = $exception->getResponse();

// Gets the response as text.
$responseText = (string) $exception->getResponse()->getBody();

// Gets the response as a parsed array.
$responseData = \json_decode((string) $exception->getResponse()->getBody(), true);

use SlashId\Php\Exception\IdNotFoundException;
use SlashId\Php\Person;
use SlashId\Php\PersonInterface;

function getPerson($identifier): ?PersonInterface
    try {
        $response = $this->sdk->get('/persons/' . $identifier, [
            'fields' => ['handles', 'groups', 'attributes'],
        ]);

        return Person::fromValues($response);
    } catch (IdNotFoundException $exception) {
        return null;
    }
}

// The ID, such as 9999-9999-9999. It can be null if the $person is created with `new Person()`.
$person->getPersonId();

// Whether the person is active.
$person->isActive();

// The email addresses associated with the account, such as ['[email protected]', '[email protected]'].
$person->getEmailAddresses();

// The phone numbers associated with the account, such as ['+199999999', '+44999999999'].
$person->getPhoneNumbers();

// The region, one of "us-iowa", "europe-belgium", "asia-japan", "europe-england", "australia-sydney".
$person->getRegion();

// The groups of the person, e.g. ['Admin', 'Editor'].
$person->getGroups();

// Overrides whether the user is active.
$person->setActive(false);

// Adds one email address to the list.
$person->addEmailAddress(string $emailAddress): static

// Overrides the full list of email addresses.
$person->setEmailAddresses(array $emailAddresses): static

// Adds one phone number to the list.
$person->addPhoneNumber(string $phoneNumber): static

// Overrides the full list of phone numbers.
$person->setPhoneNumbers(array $phoneNumbers): static

// Overrides the region.
$person->setRegion(string $region): static

// Overrides the list of groups.
$person->setGroups(array $groups): static

// Lists all attributes, grouped by bucket name.
$person->getAllAttributes();

// Response:
[
    PersonInterface::BUCKET_ORGANIZATION_END_USER_READ_WRITE => ['first_name' => 'John'],
    PersonInterface::BUCKET_ORGANIZATION_END_USER_NO_ACCESS => ['secret_key' => 'aaa-aaa-aaa'],
];

// Gets attributes in a bucket.
$person->getBucketAttributes(PersonInterface::BUCKET_ORGANIZATION_END_USER_READ_WRITE);

// Response:
['first_name' => 'John'];

// Gets one specific attribute.
$person->getAttribute(PersonInterface::BUCKET_ORGANIZATION_END_USER_READ_WRITE, 'first_name');

// Response:
'John';

// Overrides ALL attributes.
$person->setAllAttributes([
    PersonInterface::BUCKET_ORGANIZATION_END_USER_READ_WRITE => ['first_name' => 'John'],
    PersonInterface::BUCKET_ORGANIZATION_END_USER_NO_ACCESS => ['secret_key' => 'aaa-aaa-aaa'],
]);

// Overrides attributes in a bucket.
$person->setBucketAttributes(PersonInterface::BUCKET_ORGANIZATION_END_USER_NO_ACCESS, ['secret_key' => 'aaa-aaa-aaa']);

// Deletes the attributes in a bucket.
$person->deleteBucketAttributes(PersonInterface::BUCKET_ORGANIZATION_END_USER_NO_ACCESS);

// Overrides one attribute.
$person->setAttribute(PersonInterface::BUCKET_ORGANIZATION_END_USER_READ_WRITE, 'last_name', 'Smith');

// Deletes one attribute.
$person->deleteAttribute(PersonInterface::BUCKET_ORGANIZATION_END_USER_READ_WRITE, 'first_name');

if ($person->hasGroup('Editor')) {
    // Do things that only an "Editor" user can do.
}

if ($person->hasAnyGroup(['Admin', 'Editor', 'Reviewer'])) {
    // Do things that someone in the group "Admin", OR in the group "Editor", OR
    // in the group "Reviewer" can do.
}

if ($person->hasAllGroups(['Admin', 'Editor'])) {
    // Do things that only someone that is in *both* "Admin" and "Editor" groups
    // can do.
}

$person = (new \SlashId\Php\Person())
    ->setRegion('europe-england')
    ->addEmailAddress('[email protected]')
    ->addPhoneNumber('+33999999999')
    ->setGroups(['Admin', 'Editor'])
    // Define a password hash with one of the supported encryptions.
    ->setLegacyPasswordToMigrate('$2y$12$YKpfgBJpginFYyUfdAcAHumQKfJsEzJJz9d0oQgg0zoEsRSz6sXty');

$persons = [$person];

$response = $sdk->migration()->migratePersons($persons);

if ($sdk->token()->validateToken($token)) {
    // Token is valid.
}

$personId = $sdk->token()->getSubFromToken($token);

// $personId will be something such as "903c1ff9-f2cc-435c-b242-9d8a690fcf0a".

$sdk->webhook();

foreach ($sdk->webhook()->findAll() as $webhook) {
    // each $webhook:
    [
        'id' => '065de68b-cce0-7285-ab00-6f34a56b585d',
        'name' => 'prod_webhook',
        'description' => 'Some description...',
        'target_url' => 'https://example.com/slashid/webhook',
        'custom_headers' => [
            'X-Extra-Check' => ['Value for the header'],
        ],
        'timeout' => '30s',
    ]
}

$webhook = $sdk->webhook()->findById('065de68b-cce0-7285-ab00-6f34a56b585d');

// $webhook:
[
    'id' => '065de68b-cce0-7285-ab00-6f34a56b585d',
    'name' => 'prod_webhook',
    'description' => 'Some description...',
    'target_url' => 'https://example.com/slashid/webhook',
    'custom_headers' => [
        'X-Extra-Check' => ['Value for the header'],
    ],
    'timeout' => '30s',
]

$webhook = $sdk->webhook()->findByUrl('https://example.com/slashid/webhook');

// $webhook:
[
    'id' => '065de68b-cce0-7285-ab00-6f34a56b585d',
    'name' => 'prod_webhook',
    'description' => 'Some description...',
    'target_url' => 'https://example.com/slashid/webhook',
    'custom_headers' => [
        'X-Extra-Check' => ['Value for the header'],
    ],
    'timeout' => '30s',
]

$webhook = $sdk->webhook()->register('https://example.com/slashid/webhook', 'a_unique_name_for_the_webhook', [
    'PersonCreated_v1',
    'PersonDeleted_v1',
]);

// $webhook:
[
    'id' => '065de68b-cce0-7285-ab00-6f34a56b585d',
    'name' => 'a_unique_name_for_the_webhook',
    'description' => '',
    'target_url' => 'https://example.com/slashid/webhook',
    'custom_headers' => [],
    'timeout' => '0s',
]

[
    'description' => 'Some description...',
    'custom_headers' => [
        'X-Extra-Check' => ['Value for the header'],
    ],
    'timeout' => '30s',
]

// Creates a new webhook.
$webhook = $sdk->webhook()->register('https://example.com/slashid/webhook', 'a_unique_name_for_the_webhook', [
    'PersonCreated_v1',
    'PersonDeleted_v1',
], [
    'timeout' => '18s',
]);

// $webhook:
[
    'id' => '065de68b-cce0-7285-ab00-6f34a56b585d',
    'name' => 'a_unique_name_for_the_webhook',
    'description' => '',
    'target_url' => 'https://example.com/slashid/webhook',
    'custom_headers' => [],
    'timeout' => '18s',
]

// Lists triggers the webhook has.
$triggers = $sdk->webhook()->getWebhookTriggers($webhook['id']);

// $triggers:
[
    'PersonCreated_v1',
    'PersonDeleted_v1',
]

// Now we update the webhook, with a different option AND different triggers.
$webhook = $sdk->webhook()->register('https://example.com/slashid/webhook', 'a_unique_name_for_the_webhook', [
    'AuthenticationSucceeded_v1',
    'PersonCreated_v1',
], [
    'custom_headers' => [
        'X-Custom-Header' => ['Value for the header'],
    ],
]);

// Note that the "custom_header" has been updated, but the value for the "timeout" is unchanged.
// $webhook:
[
    'id' => '065de68b-cce0-7285-ab00-6f34a56b585d',
    'name' => 'a_unique_name_for_the_webhook',
    'description' => '',
    'target_url' => 'https://example.com/slashid/webhook',
    'custom_headers' => [
        'X-Custom-Header' => ['Value for the header'],
    ],
    'timeout' => '18s',
]

// As for the triggers, note that "PersonDeleted_v1" is no longer a trigger.
$triggers = $sdk->webhook()->getWebhookTriggers($webhook['id']);

// $triggers:
[
    'AuthenticationSucceeded_v1',
    'PersonCreated_v1',
]

$sdk->webhook()->setWebhookTriggers('065de68b-cce0-7285-ab00-6f34a56b585d', [
    'PersonCreated_v1',
    'PersonDeleted_v1',
]);

// Triggers in the webhook: PersonCreated_v1, PersonDeleted_v1

$sdk->webhook()->addWebhookTrigger('065de68b-cce0-7285-ab00-6f34a56b585d', 'VirtualPageLoaded_v1');

// Triggers in the webhook: PersonCreated_v1, PersonDeleted_v1, VirtualPageLoaded_v1

$sdk->webhook()->deleteWebhookTrigger('065de68b-cce0-7285-ab00-6f34a56b585d', 'PersonDeleted_v1');

// Triggers in the webhook: PersonCreated_v1, VirtualPageLoaded_v1

$sdk->webhook()->setWebhookTriggers('065de68b-cce0-7285-ab00-6f34a56b585d', []);

// Triggers in the webhook: none

$sdk->webhook()->deleteById('065de68b-cce0-7285-ab00-6f34a56b585d');
$sdk->webhook()->deleteByUrl('https://example.com/slashid/webhook');

// The JWT from the request.
$encodedJwt = $request->getContent();

// $encodedJwt:
// eyJhbGciOiJFUzI1NiIsICJraWQiOiJuTGtxV1EifQ.eyJhdWQiOiI0MTJlZGI1Ny1hZTI2LWYyYWEtMDY5OC03NzAwMjFlZDUyZDEiLCAiZXhwIjx...

// Note the use of `app('cache.psr6')` to fetch the cache backend.
$decoded = $sdk->webhook()->decodeWebhookCall($encodedJwt, app('cache.psr6'));

// Dispatch an event using Laravel's API.
WebhookEvent::dispatch(
    $decoded['trigger_content']['event_metadata']['event_name'],
    $decoded['trigger_content']['event_metadata']['event_id'],
    $decoded['trigger_content'],
);

composer