Code Monkey home page Code Monkey logo

thisdata-php's Introduction

ThisData API Client Build Status

Consume the ThisData.com REST API using this client. Requires at least PHP5.5.

Install

Using composer:

composer require thisdata/api

Quick Start

Use the factory to return an instance of ThisData\Api\ThisData, configured with default settings.

use ThisData\Api\ThisData;

$apiKey = '<API_KEY>';

$thisData = ThisData::create($apiKey);

⚠️ Don't commit your API key to source control! Use an environment variable, or perhaps you have a configuration solution that allows you to store secrets in local configuration without being shared.

Each endpoint will have different methods, depending on the functionality the endpoint provides. For instance, the events endpoint can track successful login attempts.

API Documentation

Documentation for API endpoints can be found here:

Tracking Events

Use the $thisData instance to get an instance of the events endpoint.

$endpoint = $thisData->getEventsEndpoint();

Then track events:

$ip = $_SERVER['REMOTE_ADDR'];
$user = [
    'id' => 'johntitor',
    'name' => 'John Titor',
    'email' => '[email protected]',
    'mobile' => '+64270000001'
];
$userAgent = $_SERVER['HTTP_USER_AGENT'];

$endpoint->trackLogIn($ip, $user, $userAgent);

$verb = 'my-custom-verb';
$endpoint->trackEvent($verb, $ip, $user, $userAgent);

When the login attempt is unsuccessful:

$ip = $_SERVER['REMOTE_ADDR'];
$user = [
    'id' => 'johntitor',
    'authenticated' => false
];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$endpoint->trackEvent(EventsEndpoint::VERB_LOG_IN_DENIED, $ip, $user, $userAgent);

When you're using a multi-tenanted app:

$ip = $_SERVER['REMOTE_ADDR'];
$user = [
    'id' => 'johntitor'
];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$source = [
    'name' => 'SubCustomer 1'
]
$endpoint->trackLogIn($ip, $user, $userAgent, $source);

Verifying a User

When a sensitive action is about to occur, perhaps before finalizing the log-in process, you can verify that the user is who they say they are, and check the risk that their account is being impersonated by an attacker. If they present a medium or high risk, force them to provide a two-factor authentication code.

$endpoint = $thisData->getVerifyEndpoint();

$ip = $_SERVER['REMOTE_ADDR'];
$user = [
    'id' => 'johntitor'
];
$userAgent = $_SERVER['HTTP_USER_AGENT'];

$response = $endpoint->verify($ip, $user, $userAgent);

if ($response['risk_level'] != "green") {
    # Ask for Two Factor Authentication code
} else {
    # Everything is OK
}

Getting a list of Events (Audit Log)

You can fetch a paginated, filterable array of Events from the API. The method accepts any of the parameters described in the documentation: http://help.thisdata.com/docs/v1getevents

e.g. returning the 10 most recent log-in events for a user

$endpoint = $thisData->getEventsEndpoint();
$events = $endpoint->getEvents(["verb" => "log-in", "user_id" => 112233, "limit" => 10]);

Advanced

There are several configuration options that modify the way the library behaves. By using the Builder you can set these configuration options.

use ThisData\Api\Builder;
$builder = new Builder($apiKey);

// Configure the builder here. See below for more details.
// ...
// e.g. $builder->setAsync(false);
// $builder->setExpectJsCookie(true);
// ...

$thisData = $builder->build();

Synchronous Requests

By default, requests are sent to the server asynchronously. If this is not required, or synchronous communication is preferred, configure your builder to use synchronous requests.

$builder->setAsync(false);

ThisData's Javascript library

ThisData's Javascript tracking code is optional, but when included in a page will add a cookie called __tdli. If you're using the optional javascript library, this library will automatically pick up that cookie. You should also tell the API that each request should come with a cookie:

$builder->setExpectJsCookie(true);

Network Configuration

If you require more control of your network settings, such as using a proxy, configure the client settings when building.

$builder->setClientOption('proxy', 'tcp://localhost:8125');

If you want to see the verbose output of the HTTP request, enable debug mode in Guzzle.

$builder->setClientOption('debug', true);

All settings supported by the Guzzle HTTP Client can be configured here, including curl options.

Direct Access to the HTTP client

If you require access to directly interact with the Guzzle HTTP client to send custom requests, the configured instance can be retrieved from an endpoint.

/** @var GuzzleHttp\Client $guzzle */
$guzzle = $events->getClient();

Alternatively, you can instantiate the client manually, without the added endpoint abstration layers.

$client = new ThisData\Api\Client('<API_KEY>'); // An extension of the GuzzleHttp\Client class
$client->post('events', ['body' => '{"ip":"127.0.0.1"}']);

Contributing

Thanks for helping! Start by forking the repository. Then make sure the tests pass:

composer install
./vendor/bin/phpunit

Make your changes, add test coverage, and check the tests are still passing. Then open a PR! :)

thisdata-php's People

Contributors

emarref avatar richet avatar nickmalcolm avatar

Stargazers

Andrew Hedges avatar Nico Müller avatar

Watchers

Christian Pedersen avatar  avatar  avatar  avatar James Cloos avatar Dominick Caponi avatar

Forkers

jbelke

thisdata-php's Issues

Better error handling (catch by default, log if we can)

If I wanted to check that the API call worked, how would I do that?

The Guzzle HTTP library will throw an exception and halt PHP execution if the call fails (a 400-599 response). Wrap the tracking call in a try/catch block to handle the failure. This should probably be reflected in the docs. Will update.

The client should catch these automatically - we want people to be able to add this library in without worrying about an error on our end breaking their session flow.

is there a response variable I can call a method on, inspect errors, log to a console / that request profiler thing.

Given the nature of the asynchronous call, a callback would need to be provided to the promise's rejection handler. In this setup, there is no provision for acquiring the response, just to keep it simple. I could add that in if it's a deal breaker? My reasoning is that it's unlikely there will be anything worth using in the response.

Can we provide a quick code example in the readme to the effect of "if you're having trouble, add this snippet to this location, and it will log error messages received from the ThisData API Endpoint"?
The API does validate and return errors when the event is funky. (See the docs for example 400 / 401 responses).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.