Saturday, July 21, 2012

Setting up shadow boxes on your website.

This is just a short post for you to put shadow inside and outside of your website's page elements such as input text box, text area, buttons, images, etc..

Inside Shadows:

.in-shadow {
        box-shadow: inset 1px 1px 1px #a2a2a2;
        -moz-box-shadow: inset 1px 1px 1px #a2a2a2;
        -webkit-box-shadow: inset 1px 1px 1px #a2a2a2;
}


Outside Shadows:

.out-shadow {
        box-shadow: inset 1px 1px 1px #a2a2a2;
        -moz-box-shadow: inset 1px 1px 1px #a2a2a2;
        -webkit-box-shadow: inset 1px 1px 1px #a2a2a2;
}


Hope you like this. Happy coding!!

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

?>

HTML 101: Setting up tab index in your website

Setting up tab index is very useful if you want your text boxes, buttons, and any other elements be set in a specific order.

You can set it by using "tabindex" attribute to all your input elements. Please see sample below.

<input type="text" value="" name="text" tabindex="1"></input>
<input type="text" value="" name="text" tabindex="2"></input>
<input type="submit" value="submit" name="text" tabindex="3"></input>


You can also disable the tab index of an element by setting the value to "-1". This is very useful if you have an element that is hide or you set the opacity to be not visible. Please see sample below.

<input type="text" value="" name="text" style="opacity:0;" tabindex="1"></input>
<input type="text" value="" name="text" tabindex="-1"></input>
<input type="submit" value="submit" name="text" tabindex="2"></input>


Hope this is helpful!

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.