General explanation

To use Y8 Account API and request user information, application needs user access token. You can reed more about obtaining tokens on the appropriate page. In this tutorial we’re going to cover basic obtaining logic and provide code examples for this routines.

This diagram presents basic user-application interaciton.

Wide arrow represent what is happening with user-agent. In our example we will assume that it is browser, but it may be anything - mobile or desktop application, for example.

Narrow arrows represent server-to-server interaction and represent internal application requests to Y8 Account.

Step 1. Preparing your database

We assume that you have php-json, php-mysql and php-curl extensions installed to use following examples.

To log users in, you have to set your database up to store user data. Y8 Account presents a variety of fields that identify user, but in this tutorial we will use following schema:

Attribute Type Description
id int Unique identifier for user in your application
pid int Y8 Account unique identifier for a user
nickname string User nickname
access_token string Aceess token for user to get Y8 Account information
refresh_token string Refresh token that will be used in case access token is expired

Here’s example of creating database and table with php (warning: you’ll need DB server running to do this):

<?php
  $sql_conn = mysqli_connect("server_address", "db_user", "db_password");
  // Put your credentials above
  $create_db_query = "CREATE DATABASE idnet_php_example";
  if ($sql_conn->query($create_db_query)) {
    $create_table_query = <<<EOT
      CREATE TABLE accounts
      (
        id int auto_increment primary key,
        pid char(24),
        nickname varchar(40),
        access_token char(32),
        refresh_token char(32)
      );
EOT;
    if ($sql_conn->query($create_table_query)) {
      echo "You have successfully created table";
    } else {
      die "Could not create accounts table";
    }
  } else {
    die "Could not create database";
  }
?>

You should put this or similar script into your setup sequence to create account storage.

Step 2. Using the Javascript SDK

To use Y8 Account authorization, your application has to present user an Y8 Account window, that will create new user’s account (or log him in, if user already has one) and then ask him to give your application access to one of his identities.

To read about it in detail, you can visit JavaScript page.

First and foremost, you have to integrate Y8 Account javascript sdk into your page:

<script type="text/javascript">
  window.idAsyncInit = function() {
    // Triggered when Y8 Account SDK has finished initialization
    ID.Event.subscribe('id.init', function(){
      // When user clicks on the link it will open the authentication modal
      jQuery('#idnet-connect').on('click', function(){
        ID.register();
      })
    );

    ID.init({
        appId         : 'YOUR_APP_ID',                              // App ID from the app dashboard
        status        : true,                                       // Check Y8 Account Login status
        responseType  : 'code',                                     // 'token' by default
        redirectUri   : 'https://mysite.com/auth/idnet/callback'    // default redirect_uri
      });
    };

  (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src =  document.location.protocol == 'https:' ? "https://cdn.y8.com/api/sdk.js" : "http://cdn.y8.com/api/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'id-jssdk'));
</script>

Then, you have to add your link that will display Y8 Account popup when user clicks on it:

<a href="#" id="idnet-connect">
  Connect with Y8 Account
</a>

Step 3. User logs in and comes back to your application

After clicking the link above, an Y8 Account frame will be presented to user, where he will go through all login routines. After this, he will be redirected to the URI that you’ve provided during previous request.

This URI will have authorization code, as one of the GET parameters. You’ll have to use this code to exchange it for access token afterwards.

<?php
  $APP_ID = "your_app_id_obtained_from_y8_account";
  $APP_SECRET = "your_app_secret_obtained_from_y8_account";
  $code = $_GET["code"];

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://account.y8.com/oauth/token");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, "idnet-php-example");
  curl_setopt($ch, CURLOPT_POSTFIELDS, array(
      "grant_type" => "authorization_code",
      "client_id" => $APP_ID,
      "client_secret" => $APP_SECRET,
      "code" => $code
    )
  );
  $result = curl_exec($ch);
  curl_close($ch);
?>

Result may have one of the following JSONs:

{
  "access_token":"b2c8f5309589b90132750cd83ed4e519ec8b9a62dce22c2f43e340c06b4921b1",
  "refresh_token":"a3f3d78db4caacb8157624b5050485f70159ba11be08f1876e45fb1c743b7280",
  "token_type":"bearer",
  "expires_in":31536000,
  "scope":"[]"
}

If everything is ok. And in case of error you will get someghing like this:

{
  "error": "invalid_grant",
  "error_description": "The provided access grant is invalid, expired, or revoked (e.g. invalid assertion, expired authorization token, bad end-user password credentials, or mismatching authorization code and redirection URI)."
}

To parse the token, you may use the following code:

<?php
  $token_info = json_decode($result, true);
  if (isset($token_info["error"])) {
    //error processing
  } else {
    $access_token = $token_info["access_token"];
  }
?>

It is up to you to decide, how you are going to process the error or access token, but we highly recommend you to store tokens to use it for further API requests.

Step 4. Use access token to obtain user information

After receiving access token, you can use it to call different APIs.

<?php
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://account.y8.com/api/v1/json/profile");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer ".$access_token));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, 'idnet-php-example');
  $result = curl_exec($ch);
  curl_close($ch);
  $profile = json_decode($result, true);
?>

This request will return a list of user-information fields, needed to identify user.

Step 5. Finding or creating user in your application

Now you have to check, whether user has already used your application, you can do this by selecting users from your database with just received unique pid. If user already exists - you have to update his information (for example, if nickname has changed). If he does not exist - you have to insert new record for him in the database.

<?php
  $sql_conn = mysqli_connect("server_address", "db_user", "db_password", "idnet_php_example");
  // Put your credentials above

  $results = $sql_conn->query("SELECT * FROM accounts WHERE pid = '".$profile["pid"]."'");
  $user = $result->fetch_assoc();

  if ($user == NULL) {
    $first_time_login = true;
    $user = array("pid" => $profile["pid"]);
  }

  $user["access_token"] = $token_info["access_token"];
  $user["refresh_token"] = $token_info["refresh_token"];
  $user["nickname"] = $profile["nickname"];

  if ($first_time_login) {
    $user_query = "INSERT INTO accounts VALUES (NULL, ".$user["pid"].", '".$user["nickname"];
    $user_query.= "','".$user["access_token"]."','".$user["refresh_token"]."'";

    $sql_conn->query($user_query);

    $user["id"] = $sql_conn->insert_id;
  } else {
    $user_query = "UPDATE accounts SET nickname = '".$user["nickname"];
    $user_query.= "', access_token = '".$user["access_token"]."', refresh_token = '";
    $user_query.= $user["refresh_token"]."' WHERE id = ".$user["id"];

    $sql_conn->query($user_query);
  }
?>

Step 6. Remembering login

After user is obtained and saved into database - the easiest way to remember him between requests is to store his id in session variable:

<?php
  $_SESSION["user_id"] = $user["id"];
?>

And then, prepend following code to each of your site pages:

<?php
  $sql_conn = mysqli_connect("server_address", "db_user", "db_password", "idnet_php_example");
  // Put your credentials above

  if ($_SESSION["user_id"]) {
    $select = $sql_conn->query("SELECT * FROM accounts WHERE id = '".$_SESSION["user_id"]."'");
    $user = $select->fetch_assoc();
  } else {
    // Display Y8 Account login/register button
  }
?>

This information is enough to create basic Y8 Account authorization in your application. To find out about various ways to enhance user experience, consult APIs reference.