Tuesday, November 5, 2013

Box API Integration on PHP

I'd been busy and not able to post anything here for a long time. Anyway, I wanted to post this integration I just did so that I will have a reference if ever I have to develop something with box.com.

First of all, you need to register an account on the link below. You can choose to have a FREE or personal account if you want to try it out.

https://app.box.com/pricing/

After the registration, you need to create an application that we will use for integration.
Go to http://developers.box.com then click "Get API Key" button to create an app.
The application you created will have client id and client secret, save it somewhere else coz we will use it later on.

Once we have the application and the credential for API access, we can now start the coding part, just follow the simple steps below.

We need to authorize our application to access our box account. We can either access the authorize URL via GET or POST method with response_type, state, client_id and redirect_uri parameter. The redirect uri might need to be on https but for localhost testing, you can use http. You can also set the redirect uri on your box application under oauth2 section.

https://www.box.com/api/oauth2/authorize?response_type=code&state=authenticated&client_id=<your client id>&redirect_uri=<your redirect uri>

The user will have to enter his/her credential and grant access to our application. After authorizing the app, box will redirect the user to the redirect uri parameter or the redirect uri set on your box application.

The box will redirect the user via GET method with the "code" parameter which we will use to get an access token. Once you have the code, you will need to submit POST request to box with the code, client_id, and client_secret parameter.

endpoint url:
https://www.box.com/api/oauth2/token

parameters:
grant_type = authorization_code
code = <this will be the code you get from box after authorize process>
client_id = <your box client id>
client_secret = <your box client secret>


The script below will get the "code" parameter from box in exchange with an access token and refresh token. The output will be the access token, refresh token and expiration. You need to store those information either via session or database to call API methods after.

$code = $_GET['code'];
if ($code) token($code);
function token($code='') {
    $client_id = '<your box client id>';
    $client_secret = '<your box client secret>';
        $url = "https://www.box.com/api/oauth2/token";
        $param = "grant_type=authorization_code&code=$code&client_id=".$client_id."&client_secret=".$client_secret;

        $curlcmd = "curl $url -d '$param' -X POST";
        $output = exec($curlcmd);
        $json = json_decode($output);

        $access_token = $json->access_token;
        $refresh_token = $json->refresh_token;
    }


For you to have an idea on how it works with a readily client API, please see below. Hope this will help you with your development. Leave a comment if you like this post.

<?php

$box = new wu_boxapi();
// this will set the redirect uri which is the same script
// you just need to put the name of you script here replacing "/box-client-api.php" which is my current file.
$box->set_redirect_uri(getcwd().'/box-client-api.php');

// get access token
$code = $_GET['code'];
if ($code) $box->token($code);

// list folders in your account
$folder_id = 0;
$box->list_folders($folder_id);

// search for files in your account
$keyword = '';
$box->search($keyword);

class boxapi {
    var $box_email = '<your box email account>';
    var $client_id = '<your box client id>';
    var $client_secret = '<your box client secret>';
    var $redirect_uri = '';
    var $access_token = '';
    var $refresh_token = '';
    var $force_refresh = false;

    function __construct() {
    //  nothing to do here...
    }

    function set_redirect_uri($uri='') {
        $this->redirect_uri = urlencode($uri);
    }

    function authorize() {
        $url = "https://www.box.com/api/oauth2/authorize?response_type=code&state=authenticated&client_id=".$this->client_id."&redirect_uri=".$this->redirect_uri;
        header("Location: $url");
    }

    function check_token() {
        $this->access_token = $_SESSION['access_token'];
        $this->refresh_token = $_SESSION['refresh_token'];
        $timediff = time() - $_SESSION['timestamp'];

        if (!@$this->access_token) $this->authorize();
        if ($timediff >= 3600 || $this->force_refresh) $this->refresh();
    }

    function token($code='') {
        $url = "https://www.box.com/api/oauth2/token";
        $param = "grant_type=authorization_code&code=$code&client_id=".$this->client_id."&client_secret=".$this->client_secret;

        $curlcmd = "curl $url -d '$param' -X POST";
        $output = exec($curlcmd);
        $json = json_decode($output);

        $this->access_token = $json->access_token;
        $this->refresh_token = $json->refresh_token;

        $_SESSION['access_token'] = $this->access_token;
        $_SESSION['refresh_token'] = $this->refresh_token;
        $_SESSION['timestamp'] = time();
    }

    function refresh() {
        $url = "https://www.box.com/api/oauth2/token";
        $param = "grant_type=refresh_token&refresh_token=".$this->refresh_token."&client_id=".$this->client_id."&client_secret=".$this->client_secret;

        $curlcmd = "curl $url -d '$param' -X POST";
        $output = exec($curlcmd);
        $json = json_decode($output);

        $this->access_token = $json->access_token;
        $this->refresh_token = $json->refresh_token;

        $_SESSION['access_token'] = $this->access_token;
        $_SESSION['refresh_token'] = $this->refresh_token;
        $_SESSION['timestamp'] = time();
    }

    function list_folders($folder_id=0) {
        $this->check_token();
        $url = "https://api.box.com/2.0/folders/$folder_id";

        $curlcmd = "curl $url -H 'Authorization: Bearer ".$this->access_token."'";
        $output = exec($curlcmd);
        $json = json_decode($output);

        var_dump(@$json);
    }

    function search($keyword='', $limit=30, $offset=0) {
        $this->check_token();
        $url = "https://api.box.com/2.0/search";
        $param = "query=$keyword&limit=$limit&offset=$offset";

        $curlcmd = "curl '$url?$param' -H 'Authorization: Bearer ".$this->access_token."'";
        $output = exec($curlcmd);
        $json = json_decode($output);

        var_dump(@$json);
    }
}

?>

4 comments:

  1. how can i write in curl

    $curlcmd = "curl $url -H 'Authorization: Bearer ".$this->access_token."'";

    ReplyDelete
    Replies
    1. Not sure what you are asking but you should be able to execute curl on your console or the curl should be enabled on your server. You have to install it.

      Delete
  2. No i don't want to execute it on console. I want to call the curl like that

    $ch = curl_init( $url );

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type:application/json"));

    curl_setopt( $ch, CURLOPT_POSTFIELDS, $param);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
    $response = curl_exec( $ch );
    curl_close($ch);

    So how can i write that
    $curlcmd = "curl $url -H 'Authorization: Bearer ".$this->access_token."'";

    into above curl form.

    ReplyDelete
    Replies
    1. Ahh, okay.. then you just have to add it as a header like below.. Let me know if that works.

      curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type:application/json","Authorization: Bearer ".$this->access_token));

      Delete

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.