Showing posts with label integration. Show all posts
Showing posts with label integration. Show all posts

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);
    }
}

?>

Thursday, July 19, 2012

iContact API Integration on PHP

This post will teach you how to integrate your app with iContact. The API requires JSON for doing requests and responses. On this implementation, I used CURL which I commonly use when doing API call.

First thing we need to do is to register on iContact then get an API credential. Register your app and get your application id, folder id, username and password - https://app.icontact.com/icp/core/registerapp

Once we have all the credentials, we are now ready to start building our codes.

First, we need to create a function that we will commonly use such as the headers, please see function I created for setting the headers.

function set_headers($app_id, $user, $pass) {
        $headers = array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Api-Version: 2.0',
                'Api-AppId: ' . $app_id,
                'Api-Username: ' . $user,
                'Api-Password: ' . $pass
        );

        return $headers;


Next is to get information from our iContact account. Since we need the account id for all our API call, we will first request for our account information.

This function will return JSON response which we need to parse to get the information we need.

$app_id = '<put your app id>';
$user = '<put your username/email address>';
$pass = '<put your password>';
$folder_id = '<put your folder id>';

$data = get_account_info($app_id, $user, $pass);
var_dump($data);

function get_account_info($app_id, $user, $pass) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}


Sample output will be like this, which is a JSON response.

string(582) "{"accounts":[{"billingStreet":"","billingCity":"","billingState":"","billingPostalCode":"","billingCountry":"","city":"Caloocan","accountId":"#######","companyName":"Hotshots Point of View","country":"Philippines","email":"paulgonzaga80@gmail.com","enabled":"1","fax":"","firstName":"Paul","lastName":"Gonzaga","multiClientFolder":"0","multiUser":"0","phone":"639213189673","postalCode":"1421","state":"NCR","street":"#409 B1 L5, Bagumbong Itaas, Progressive Village, Novaliches Caloocan City1","title":"","accountType":"1","subscriberLimit":"500"}],"total":1,"limit":20,"offset":0}"

This will return our account information which we will use for other API call. Once we have the Account ID, we can call now our client folders, though we get it already upon registration but just for the benefit of this post, we will try to get it via API call. The parameters we passed on this function is came from above call and credentials.

$data = json_decode($data);
$account_id = $data->accounts[0]->accountId;

$data = get_client_folders($app_id, $user, $pass, $account_id);
var_dump($data);

function get_client_folders($app_id, $user, $pass, $account_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}


Sample output will be like this which is the same folder id when we do our registration.

string(69) "{"clientfolders":[{"clientFolderId":"####","logoId":null}],"total":1}"

After this, we can now proceed adding contact, getting contact information, list all our contacts, subscriptions, etc..

The sample script I made below will help you be able to move forward with other functions. Happy coding!!

<?php

$app_id = '<put your app id>';
$user = '<put your username/email address>';
$pass = '<put your password>';
$folder_id = '<put your folder id>';

$data = get_account_info($app_id, $user, $pass);
var_dump($data);

$data = json_decode($data);
$account_id = $data->accounts[0]->accountId;

$data = get_client_folders($app_id, $user, $pass, $account_id);
var_dump($data);


function set_headers($app_id, $user, $pass) {
        $headers = array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Api-Version: 2.0',
                'Api-AppId: ' . $app_id,
                'Api-Username: ' . $user,
                'Api-Password: ' . $pass
        );

        return $headers;
}

function get_account_info($app_id, $user, $pass) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function get_client_folders($app_id, $user, $pass, $account_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function add_contact($app_id, $user, $pass, $account_id, $folder_id, $email, $fname, $lname, $status='normal') {
        $headers = set_headers($app_id, $user, $pass);

        $data = array(
                'contact' => array(
                        'email'         => $email,
                        'firstName'     => $fname,
                        'lastName'      => $lname,
                        'status'        => $status
                )
        );

        $data = json_encode($data);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function get_contact_info($app_id, $user, $pass, $account_id, $folder_id, $email) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/?email=".urlencode($email));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function get_contact_info_by_id($app_id, $user, $pass, $account_id, $folder_id, $contact_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/?contactId=".urlencode($contact_id));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function list_contacts($app_id, $user, $pass, $account_id, $folder_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function subscribe($app_id, $user, $pass, $account_id, $folder_id, $email, $list_id) {
        $json = get_contact_info($app_id, $user, $pass, $account_id, $folder_id, $email);
        $obj = json_decode($json);
        $contact_id = $obj->contacts[0]->contactId;

        $headers = set_headers($app_id, $user, $pass);

        $data = array(
                'subscription' => array(
                        'contactId'     => $contact_id,
                        'listId'        => $list_id,
                        'status'        => 'normal'
                )
        );

        $data = json_encode($data);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/subscriptions/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function unsubscribe($app_id, $user, $pass, $account_id, $folder_id, $email, $list_id) {
        $json = get_contact_info($app_id, $user, $pass, $account_id, $folder_id, $email);
        $obj = json_decode($json);
        $contact_id = $obj->contacts[0]->contactId;

        $headers = set_headers($app_id, $user, $pass);

        $data = array(
                'subscription' => array(
                        'contactId'     => $contact_id,
                        'listId'        => $list_id,
                        'status'        => 'unsubscribed'
                )
        );

        $data = json_encode($data);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/subscriptions/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function list_subscribers($app_id, $user, $pass, $account_id, $folder_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/subscriptions/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}


?>

Thursday, July 12, 2012

Freshbooks API Integration on PHP

This post will teach you how to integrate your website with Freshbooks API. There is actually two ways of integrating with Freshbooks, one is via OAuth and the other one is Token-Based method.

For the Token-Based method, this is very simple. You only need to compose an XML request, use your API url and Token from Freshbooks - http://developers.freshbooks.com, then use curl to execute the request. You can check out below on how I do it by calling create client and list clients request.

<?php

$apiurl = 'https://sample.freshbooks.com/api/2.1/xml-in';
$token = '<your token here>';

create_client($apiurl, $token);
list_clients($apiurl, $token);

function create_client($apiurl='', $token='') {
        $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                <request method=\"client.create\">
                <client>
                        <first_name>Jane</first_name>
                        <last_name>Doe</last_name>
                        <organization>ABC Corp5</organization>
                        <email>janedoe@freshbooks.com</email>
                </client>
                </request>";

        $output = xml_request($apiurl, $token, $xmldata);
        var_dump($output);
}

function list_clients($apiurl='', $token='') {
        $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                <request method=\"client.list\">
                        <folder>active</folder>
                </request>";

        $output = xml_request($apiurl, $token, $xmldata);
        var_dump($output);
}

function xml_request($apiurl='', $token='', $xmldata='') {
        $output = '';

        system("curl -u $token:X $apiurl -d '$xmldata'", $output);
        return $output;
}

?>


For the OAuth method, this is pretty much complex than the Token-Based method. Please see below on the implementation I did. I also use plaintext signature method, the same method I used on my previous post - Dropbox OAuth API Integration on PHP

The first and important thing we need to have is the App key and App secret which we will use for authentication. I believed you will need an approval from Freshbooks to be able to get this information.

Once we have these credentials, we are now ready to start the coding part.

To start with, since we will be posting request to API url, I created a function in doing post request. We will be using this for request token and access token process.

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}


Now we can start requesting for a token. On this request, we need the callback url for freshbooks to redirect after the authorization was made. Once we get the token, we will submit it to authorization url for users to authorize our application.

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// call request token here and pass the App key and App secret
request_token($key, $secret);

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
                $key = $this->data['key'];
                $secret = $this->data['secret'];
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url
        $url = "https://$key.freshbooks.com/oauth/oauth_request.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_callback=$callback";

        $output = $this->post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];



        // redirect to authorize url
        authorize($key);
}


After getting a token from request token url, we can redirect the users to authorize url with the oauth token we get from request token.

function authorize($key='') {
        $oauth_token = $_SESSION['oauth_token'];

        $url = "https://$key.freshbooks.com/oauth/oauth_authorize.php";
        $param = "oauth_token=$oauth_token";

        header("Location: $url?$param");
}


Once the user allow the application to access the users information, Freshbooks will redirect the users to the callback url we put in our request token function. The callback url should be our access token function to get the access token that we can use moving forward.

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// call access token request passing the App key and App secret parameters
access_token($key, $secret);

function access_token($key='', $secret='') {
        $oauth_token = ($_GET['oauth_token']) ? $_GET['oauth_token'] : $_SESSION['oauth_token'];
        $oauth_verifier = $_GET['oauth_verifier'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://$key.freshbooks.com/oauth/oauth_access.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_verifier=$oauth_verifier";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];
}


We need to save the oauth token and oauth token secret for api call. Please watch out for my next post, I'll be posting on how to do the API call using OAuth method. Check out below script for the full implementation of the freshbooks authentication.

<?php

session_start();

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
                $key = $this->data['key'];
                $secret = $this->data['secret'];
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url
        $url = "https://$key.freshbooks.com/oauth/oauth_request.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_callback=$callback";

        $output = $this->post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize($key);
}

function authorize($key='') {
        $oauth_token = $_SESSION['oauth_token'];

        $url = "https://$key.freshbooks.com/oauth/oauth_authorize.php";
        $param = "oauth_token=$oauth_token";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = ($_GET['oauth_token']) ? $_GET['oauth_token'] : $_SESSION['oauth_token'];
        $oauth_verifier = $_GET['oauth_verifier'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://$key.freshbooks.com/oauth/oauth_access.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_verifier=$oauth_verifier";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        var_dump($_SESSION);
}

?>

Saturday, July 7, 2012

Dropbox OAuth API Integration on PHP

This post will teach you how to integrate with Dropbox OAuth using PHP platform. Please take note that I'm not using any library to perform this integration nor special coding or whatsoever.

This is basically built from scratch which I want to share with you all, who wish to integrate with Dropbox.

To start with, you need an API credentials which you can get by logging in to your Dropbox account and create an app on this url - https://www.dropbox.com/developers/apps

We need the credentials below to proceed:
  • App key
  • App secret
We also need to understand the 3 url's that we need to access to complete the authentication process as listed below.
The request token url will be use to get a token which will be use to authorize your app to access users information in their behalf.

The authorization url will be the page for users to allow our application to access the users credential.

The access token url will be use to get an access token which will be use to access users credentials in their behalf.

Another thing that we need to understand is how to create signature. We need this in performing oauth request.

For the sake of this post, we will use the PLAINTEXT signature method, which is the simplest signature method.

Once we have the credentials and the api url's, we are now ready to start by just following the simple steps below.

1. Lets request for a token from the request token url - https://api.dropbox.com/1/oauth/request_token. Since we are using plaintext signature method, the signature will be your app secret plus "%26". Please see below.

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26";
$method = "PLAINTEXT";


2. Once we have all the parameters, lets compose the post request.

$url = "https://api.dropbox.com/1/oauth/request_token";
$param = "oauth_consumer_key=$key".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


3. Execute post request using curl, which is the basic command in performing post request.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


4. Parse the output and you will get the "oauth_token" and "oauth_token_secret" below which will be use to perform authorization. You can save these information in your session so that you will retrieve it later when performing access token.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


5. From the step #4, we only need the "oauth_token" to request for authorization. For this process, we need to define our callback url in which Dropbox will redirect the users after allowing the access.

$oauth_token = $_SESSION['oauth_token'];
$callback = '<your callback url>';

$url = "https://www.dropbox.com/1/oauth/authorize";
$param = "oauth_token=$oauth_token".
                "&oauth_callback=$callback";

header("Location: $url?$param");


6. After the user allows our application, Dropbox will redirect the user to our callback url we specify on step #5. We need to submit post request to access token url with the parameter "oauth_token" from step #4. This will also require signature, the same way we did on request token process, but this time with extra parameter "oauth_token_secret" from step #4.

$oauth_token = $_SESSION['oauth_token'];
$token_secret = $_SESSION['token_secret'];

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26".$token_secret;
$method = "PLAINTEXT";


7. Lets compose the url and parameter with "oauth_token" as part of the request.

$url = "https://api.dropbox.com/1/oauth/access_token";
$param = "oauth_consumer_key=$key".
                "&oauth_token=$oauth_token".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


8. Execute the post request using curl.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


9. Parse the output and we will get an access token which we will use to do the api request. You can save these information in your database so that you won't need to request for authorization when doing api request.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


You can try the full script below I made with a live API account and a basic API request. I optimized the script as well for better coding.

<?php

session_start();

$key = 'vh096l7q9m5m8tv'; // put here your app key
$secret = 'omri1uakcak8zqz'; // put here your app secret

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/request_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize();
}

function authorize() {
        $oauth_token = $_SESSION['oauth_token'];
        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url

        $url = "https://www.dropbox.com/1/oauth/authorize";
        $param = "oauth_token=$oauth_token".
                 "&oauth_callback=$callback";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/access_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        folders($key, $secret);
}

function folders($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/metadata/dropbox";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = file_get_contents($url."?".$param);
        $jsondata = json_decode($output);

        foreach ($jsondata->contents as $contents) {
                echo $contents->path."<br/>";
        }
}

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}

?>


Sunday, July 1, 2012

Integration with Paypal on PHP

This post will teach you how to to integrate your website with paypal and hope I was able to guide you well.

To start with, you need to apply for a Paypal account. If you just want a test account, you can register for a sandbox account - http://www.sandbox.paypal.com

We need the following account details below:
  • Username
  • Password
  • API Signature
Once you have all the details, we can now do the coding part. Aside from account details, you also need to know the endpoint url and the paypal callback url. Please see details below.

Live:
  • Endpoint - https://api-3t.paypal.com/nvp
  • Callback - https://www.paypal.com/webscr&cmd=_express-checkout&token=
Sandbox:
  • Endpoint - https://api-3t.sandbox.paypal.com/nvp
  • Callback - https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
Just to get us going, please see below code snippet for checking the environment and initiate the details.

// set up your environment - live or sandbox
$live = "true";

if ($live == "true") {
        // live account details
        $username = 'paypal live username';
        $password = 'paypal live password';
        $signature = 'paypal live api signature';
        $endpoint = "https://api-3t.paypal.com/nvp";
        $url = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
} else {
        // sandbox account details
        $username = 'paypal sandbox username';
        $password = 'paypal sandbox password';
        $signature = 'paypal sandbox api signature';
        $endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        $url = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
}


Next, we need the details of transaction to be submitted to paypal api. For the benefit of this post, please see details below.

$itemamt = '40.00'; // item amount
$paymentamt = '50.00'; // total amount
$taxamt = '10.00'; // tax amount
$currencyid = 'CAD'; // 'GBP', 'EUR', 'JPY', 'USD', 'AUD'


Please make sure that $paymentamt = $itemamt + $taxamt

Also, we need the details below to perform payment transaction.

$startdate = urlencode('2012-07-01T18:10:40+08:00'); // payment start date
$billingfreq = '1' // number of months interval;
$paymenttype = 'Authorization'; // or 'Sale' or 'Order'
$description = urlencode('sample description'); // description of transaction


You also need to define your callback url. Please see below.

$returnurl = 'http://www.domain.com/callback/return.html'; // callback url for successful transaction
$cancelurl = 'http://www.domain.com/callback/cancel.html'; // callback url for failed transaction


After defining the parameters, compose the query string. Please see below.

$reqStr = "METHOD=SetExpressCheckout&VERSION=65.2&PWD=$password&USER=$username&SIGNATURE=$signature&RETURNURL=$returnurl&CANCELURL=$cancelurl&REQCONFIRMSHIPPING=0&NOSHIPPING=1&PAYMENTREQUEST_0_CURRENCYCODE=$currencyid&PAYMENTREQUEST_0_AMT=$paymentamt&PAYMENTREQUEST_0_ITEMAMT=$itemamt&PAYMENTREQUEST_0_TAXAMT=$taxamt&PAYMENTREQUEST_0_DESC=$description&PAYMENTREQUEST_0_PAYMENTACTION=$paymenttype&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_NAME0=$description&L_PAYMENTREQUEST_0_QTY0=1&L_PAYMENTREQUEST_0_AMT0=$itemamt&L_PAYMENTREQUEST_0_DESC0=$description&L_BILLINGAGREEMENTDESCRIPTION0=$description&L_BILLINGTYPE0=RecurringPayments&MAXFAILEDPAYMENTS='true'";

Setup the curl as below.

// set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

// set the method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqstr);
               
// execute curl
$response = curl_exec($ch);
if (!$response) exit("SetExpressCheckout failed: ".curl_error($ch).'('.curl_errno($ch).')');


Get and parse the http response.

// get and parse the response
$arr_response = explode("&", $response);

$http_response = array();
foreach ($arr_response as $key => $val) {
        $param = explode("=", $val);
        if (sizeof($param) > 1) $http_response[$param[0]] = $param[1];
}

if ((sizeof($http_response) == 0) || !array_key_exists('ACK', $http_response)) {
        exit("SetExpressCheckout failed: " . print_r($arr_response, true));
}


Get the token and pass it to paypal for processing.

// get the token and pass to paypal for processing
if (strtoupper($http_response["ACK"]) == "SUCCESS" || strtoupper($httpParsedResponseAr["ACK"]) == "SUCCESSWITHWARNING") {
        // redirect to paypal to confirm and process transaction
        $token = urldecode($http_response["TOKEN"]);
        $paypalurl .= $token;

        if (isset($paypalurl)) redirect($paypalurl);
        exit;
} else  {
        exit('SetExpressCheckout failed: ' . print_r($http_response, true));
}


This is all for now. Next post will be processing after Paypal. You can also check out the full script below. Happy coding!!

<?php

// set up your environment - live or sandbox
$live = "true";

if ($live == "true") {
        // live account details
        $username = 'paypal live username';
        $password = 'paypal live password';
        $signature = 'paypal live api signature';
        $endpoint = "https://api-3t.paypal.com/nvp";
        $url = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
} else {
        // sandbox account details
        $username = 'paypal sandbox username';
        $password = 'paypal sandbox password';
        $signature = 'paypal sandbox api signature';
        $endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        $url = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
}

$itemamt = '40.00'; // item amount
$paymentamt = '50.00'; // total amount
$taxamt = '10.00'; // tax amount
$currencyid = 'CAD'; // or 'GBP', 'EUR', 'JPY', 'USD', 'AUD'

$startdate = urlencode('2012-07-01T18:10:40+08:00'); // payment start date - 2012-07-01T18:10:40+08:00
$billingfreq = '1' // number of months interval;
$paymenttype = 'Authorization'; // or 'Sale' or 'Order'
$description = urlencode('sample description'); // description of transaction

$returnurl = 'http://www.domain.com/callback/return.html'; // callback url for successful transaction
$cancelurl = 'http://www.domain.com/callback/cancel.html'; // callback url for failed transaction

$reqstr = "METHOD=SetExpressCheckout&VERSION=65.2&PWD=$password&USER=$username&SIGNATURE=$signature&RETURNURL=$returnurl&CANCELURL=$cancelurl&REQCONFIRMSHIPPING=0&NOSHIPPING=1&PAYMENTREQUEST_0_CURRENCYCODE=$currencyid&PAYMENTREQUEST_0_AMT=$paymentamt&PAYMENTREQUEST_0_ITEMAMT=$itemamt&PAYMENTREQUEST_0_TAXAMT=$taxamt&PAYMENTREQUEST_0_DESC=$description&PAYMENTREQUEST_0_PAYMENTACTION=$paymenttype&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_NAME0=$description&L_PAYMENTREQUEST_0_QTY0=1&L_PAYMENTREQUEST_0_AMT0=$itemamt&L_PAYMENTREQUEST_0_DESC0=$description&L_BILLINGAGREEMENTDESCRIPTION0=$description&L_BILLINGTYPE0=RecurringPayments&MAXFAILEDPAYMENTS='true'";

// set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

// set the method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqstr);

// execute curl
$response = curl_exec($ch);

if (!$response) exit("SetExpressCheckout failed: ".curl_error($ch).'('.curl_errno($ch).')');

// get and parse the response
$arr_response = explode("&", $response);

$http_response = array();
foreach ($arr_response as $key => $val) {
        $param = explode("=", $val);
        if (sizeof($param) > 1) $http_response[$param[0]] = $param[1];
}

if ((sizeof($http_response) == 0) || !array_key_exists('ACK', $http_response)) {
        exit("SetExpressCheckout failed: " . print_r($arr_response, true));
}

// get the token and pass to paypal for processing
if (strtoupper($http_response["ACK"]) == "SUCCESS" || strtoupper($httpParsedResponseAr["ACK"]) == "SUCCESSWITHWARNING") {
        // redirect to paypal to confirm and process transaction
        $token = urldecode($http_response["TOKEN"]);
        $paypalurl .= $token;

        if (isset($paypalurl)) redirect($paypalurl);
        exit;
} else  {
        exit('SetExpressCheckout failed: ' . print_r($http_response, true));
}

?>

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.