Showing posts with label client. Show all posts
Showing posts with label client. 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);
    }
}

?>

Sunday, October 23, 2011

Net::UCP::Client SMSC Protocol in PERL

This post will teach you how to create an SMSC UCP client in Perl.

1. First, you will need Perl libraries that needs to be installed in your server. Libraries are as follows:
  • POSIX
  • Time::HiRes
  • File::Copy
  • Encode
  • Net::UCP
  • Data::Dumper
2. Initialize the script by creating SMSC object passing the smsc ip, smsc port, and smsc profile.

my $emi = Net::UCP->new (
        SMSC_HOST   => $smsc_ip,
        SMSC_PORT   => $smsc_port,
        SENDER_TEXT => $profile,
        SRC_HOST    => $source_ip,            # optional
        SRC_PORT    => $source_port,          # optional
        WARN        => 1,

        FAKE        => 0
) or die("Failed to create SMSC object");

$emi->open_link() or die($!);

3. Login to SMSC by supplying smsc id, smsc password, and smsc access code.

my ($acknowledge, $error_number, $error_text) = $emi->login(
        SMSC_ID    => $smsc_id,
        SMSC_PW    => $smsc_pw,
        SHORT_CODE => $smsc_ac,
        OTON       => $ton,       # optional
        ONPI       => '5',        # optional
        VERS       => '0100',     # optional
);

die ("Login to SMSC failed. Error nbr: $error_number, Error txt: $error_text\n") unless($acknowledge);

4. Loop in to fetch SMSC messages. Please take note that we need to have a call-back function to call whenever it reaches timeout. All messages can be parsed by using parse_message() function that will return hash data.

$message = $emi->wait_in_loop(
        timeout => $timeout,
        clear => 1,
        action => \&timedout
);

if (defined($message)) {
        print "wait_in_loop: $message\n";
        $hshmsg = $emi->parse_message($message);

        $chksum = $hshmsg->{checksum};
        $rpid = $hshmsg->{rpid};
        $dcs = $hshmsg->{dcs};
        $type = $hshmsg->{type};
        $len = $hshmsg->{len};
        $xser = $hshmsg->{xser};
        $mt = $hshmsg->{mt};
        $trn = $hshmsg->{trn};
        $ot = $hshmsg->{ot};
        $srcmin = $hshmsg->{oadc};
        $dstmin = $hshmsg->{adc};
        $smsmsg = $hshmsg->{amsg};
        $tstamp = $hshmsg->{scts};
}

sub timedout {
        print "timeout reached...";
        exit 0;
}

5. Lastly, you need to acknowledge the receipt of messages by transmitting back the transaction id from the message you received.

$ucp_string = $emi->make_52(
        result => 1,
        trn => $trn,
        ack => 'A'
);

if ( defined($ucp_string) ) {
        ($acknowledge, $error_number, $error_text) = $emi->transmit_msg( $ucp_string, 10, 0 );
        print "transmit_msg: $error_text\n";
}


Please see below for the complete code with log and dump feature. Hope you like it.

#!/usr/bin/perl

use POSIX qw(strftime);
use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
use File::Copy;

use Encode;
use Net::UCP;
use Data::Dumper;

my ($message, $tstamp, $srcmin, $dstmin, $type, $xser, $mt, $trn, $ot, $smsmsg, $hshmsg, $ucp_string, $rpid, $chksum, $dcs, $len);

my $timeout = 120; # set timeout when fetching messages in secs

my $ton = 6; # set your TON from the SMSC server.
print "ton: $ton\n";

my $smsc_id = 'xxxx'; # set your SMSC ID
print "smsc id: $smsc_id\n";

my $smsc_pw = 'xxxxxxx'; # set your SMSC Password
print "smsc pw: $smsc_pw\n";

my $smsc_ac = 'xxxx'; # set your SMSC Access Code
print "smsc ac: $smsc_ac\n";

my $smsc_ip = 'xxx.xxx.xxx.xx'; # set the SMSC Destination IP
print "smsc ip: $smsc_ip\n";

my $smsc_port = 'xxxx'; # set the SMSC Destination Port
print "smsc port: $smsc_port\n";

my $source_ip = 'xxx.xxx.xxx.xx'; # set your SMSC Source IP
print "source ip: $source_ip\n";

my $source_port = 'xxxx'; # set your SMSC Source Port
print "source port: $source_port\n";

my $profile = 'xxxx'; # set your profile for logging
print "profile: $profile\n";

my $dumpdir = '/home/your/smsc/ucp/dump/directory'; # set your incoming dump directory
system "mkdir -p $dumpdir" if (!-e $dumpdir);
print "dump dir: $dumpdir\n";

my $logdir = '/home/your/smsc/ucp/log/directory'; # set your incoming log directory
system "mkdir -p $logdir" if (!-e $logdir);
print "log dir: $logdir\n";


# initialization... creating smsc object...
my $emi = Net::UCP->new (
  SMSC_HOST   => $smsc_ip,
  SMSC_PORT   => $smsc_port,
  SENDER_TEXT => $profile,
  SRC_HOST    => $source_ip,            # optional
  SRC_PORT    => $source_port,          # optional
  WARN        => 1,
  FAKE        => 0
) or die("Failed to create SMSC object");

$emi->open_link() or die($!);

# login to smsc...
my ($acknowledge, $error_number, $error_text) = $emi->login(
  SMSC_ID    => $smsc_id,
  SMSC_PW    => $smsc_pw,
  SHORT_CODE => $smsc_ac,
  OTON       => $ton,        # optional
  ONPI       => '5',        # optional
  VERS       => '0100',     # optional
);

die ("Login to SMSC failed. Error nbr: $error_number, Error txt: $error_text\n") unless($acknowledge);


while (1)
{
  # start fetching here..
  $message = $emi->wait_in_loop(
        timeout => $timeout,
        clear   => 1,
        action  => \&timedout
  );

  if (defined($message)) {
        &logme_raw($message);

        print "wait_in_loop: $message\n";
        $hshmsg = $emi->parse_message($message);

        $chksum = $hshmsg->{checksum};
        $rpid   = $hshmsg->{rpid};
        $dcs    = $hshmsg->{dcs};
        $type   = $hshmsg->{type};
        $len    = $hshmsg->{len};
        $xser   = $hshmsg->{xser};
        $mt     = $hshmsg->{mt};
        $trn    = $hshmsg->{trn};
        $ot     = $hshmsg->{ot};
        $srcmin = $hshmsg->{oadc};
        $dstmin = $hshmsg->{adc};
        $smsmsg = $hshmsg->{amsg};
        $tstamp = $hshmsg->{scts};

        &dumpme($profile, $srcmin, $dstmin, $type, $tstamp, $mt, $trn, $ot, $smsmsg);

        $ucp_string = $emi->make_52(
                  result => 1,
                  trn    => $trn,
                  ack    => 'A'
                  );

        if ( defined($ucp_string) ) {
                &logme_raw($ucp_string);

                ($acknowledge, $error_number, $error_text) = $emi->transmit_msg( $ucp_string, 10, 0 );
                print "transmit_msg: $error_text\n";
        }
  }
  else
  {
        print "no message from smsc\n";
  }
}

sub timedout {
  print "timeout reached...";

  exit 0;
}

sub logme
{
  my ($logdata) = @_;
  my ($logdate, $logtime);

  $logdate = strftime "%Y%m%d", localtime();
  $logtime = strftime "%H%M%S", localtime();

  open FLOG, ">> $logdir/$logdate-$profile.log";
  print FLOG "$logdate-$logtime -- $logdata\n";
  close FLOG;

  return 1;
}

sub logme_raw
{
  my ($logdata) = @_;
  my ($logdate, $logtime);

  $logdate = strftime "%Y%m%d", localtime();
  $logtime = strftime "%H%M%S", localtime();

  open FLOG, ">> $logdir/$logdate-$profile.raw";
  print FLOG "$logdate-$logtime -- $logdata\n";
  close FLOG;

  return 1;
}

sub dumpme
{
  my ($profile, $srcmin, $dstmin, $type, $tstamp, $mt, $trn, $ot, $smsmsg) = @_;
  my ($date, $time, $fname, $data);

  $date = strftime "%Y%m%d", localtime();
  $time = strftime "%H%M%S", localtime();

  $fname = "$date.$time.$tstamp";
  $data = "$profile|$srcmin|$dstmin|$type|$xser|$mt|$trn|$ot|$smsmsg";

  print "$data\n";
  &logme($data);

  open FILE, ">> $dumpdir/.$fname";
  print FILE "$data\n";
  close FILE;

  move("$dumpdir/.$fname","$dumpdir/$fname");
  return 1;
}

$emi->close_link();
print "done!";



1;


- Great leaders see the need, seize the opportunity, and serve without expecting anything in return. follow me on twitter @paulgonzaga

Wednesday, January 12, 2011

Setting up a web service CLIENT script in native PHP

For this post, we will be using a native PHP to create a web service client. please follow the steps below and you we're able to connect and transact in a web service.

1. first thing you have to do is to get the end-point URL of the web service server. let say the end-point wsdl - http://mydomain.com/wservice.wsdl use it to initialize SoapClient with parameters: trace and exceptions.

$this->client = new SoapClient('http://mydomain.com/wservice.wsdl', array('trace' => 1, 'exceptions' => 1));

2. once you have a client object, call the method the same as calling a usual object. let say the method name is helloWorld then passing the parameter 'world', your code should be like this.

$this->client->helloWorld('world');

3. please see the simple code below using class.

<?php
class wservice_client
{
    private $endpoint = "http://mydomain.com/wservice.wsdl";   
    private $client;

    function wservice_client() {
            $param = array (
                            'trace' => 1,
                   'exceptions' => 1
            );

            $this->client = new SoapClient($this->endpoint, $param);
    }

    function helloWorld ( $world ) {
        try {
                $response = $this->client->helloWorld($world);
        } catch (Exception $e) {
                return $response;
        }

        return (array)$response;
    }
}

?>

Saturday, January 8, 2011

Creating a socket client in PHP

Hey!! Good thing that PHP supported SOCKET extension on PHP 5.0.0. It really help us developers to develop a socket server and client using only PHP libraries.

First, your server should be able to connect to socket server ip and port. a socket port was provision for client to connect in socket.

Once you have established your connection, you can now follow the simple steps below for you to be able to develop a socket client in PHP.

1. Define the socket server ip and port.

$socket_port = '<socket server port>';
$socket_ip = '<socket server ip>';


2. Create a TCP/IP socket. to get the error, you can use socket_sterror() function passing the error code parameter using socket_last_error().

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo socket_sterror(socket_last_error());


3. After the socket was successfully created, you can now send input data request using socket_write() function, parameters are the created socket object, the input data request, and the input data length.

$in = "<input data request>";
$len = strlen($in);
socket_write($socket, $in, $len);


4. To get the return data of the socket server request from no.3, you can use socket_read() function, parameters are the socket and the maximum length of the binary data.

$out = socket_read($socket, 2048);


5. And lastly, closing the socket by socket_close() function.

socket_close($socket);


Hope you were able to follow the steps above, you can try the complete code below, just define the socket server ip and port with a valid input data request.

<?php
error_reporting(E_ALL);

/* define socket server ip and port here.. */
$socket_port = '<socket server port>';
$socket_ip = '<socket server ip>';

/* create a tcp/ip socket.. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
   $error = socket_strerror(socket_last_error());
   echo "socket_create() failed: [$result] $error\n";
} else {
   echo "socket_create() ok.\n";
}

/* connect to socket server ip and port */
$result = socket_connect($socket, $socket_ip, $socket_port);
if ($result === false) {
   $error = socket_strerror(socket_last_error($socket));
   echo "socket_connect() failed: [$result] $error\n";
} else {
   echo "socket_connect() ok.\n";
}

$in = "<input data request>";
$len = strlen($in);

echo "sending input data request.\n";
socket_write($socket, $in, $len);
echo "socket_write() ok.\n";

echo "reading return data.\n";
while ($out = socket_read($socket, 2048)) {
   echo "socket_read() : $out";
}

echo "closing the socket.";
socket_close($socket);
echo "socket_close() ok.\n\n";
?>

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.