Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, February 14, 2019

Parsing CSV on PHP

This is a PHP function that you can use in parsing CSV that will return an array.

This will parse even a non Windows CSV format which is difficult to parse with hidden new lines.

Hope this helps a lot!

public function csvToArray($filename='', $delimiter=',') { 
  if (!file_exists($filename) || !is_readable($filename)) return FALSE;
  $header = ''; 
  $data = array(); 

  if (($handle = fopen($filename, 'r')) !== FALSE) :
    $tmpfile = fopen("$filename.tmp", 'w+');
    while(!feof($handle)) {
      $line = trim(fgets($handle));
      $lines = preg_split("(\r|\n|\r\n)", $line);
      foreach ($lines as $row) : 
        fwrite($tmpfile, "$row\n");
      endforeach; 
    }
    fclose($tmpfile);
    fclose($handle);
  endif;

  if (($handle = fopen("$filename.tmp", 'r')) !== FALSE) : 
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
      if (!@$row[0]) continue; if (!$header) : 
        $header = $row;
      else :
        $data[] = array_combine($header, $row);
      endif;
    }
    fclose($handle);
  endif;

  unlink("$filename.tmp");
  return $data;
}

Monday, October 5, 2015

Code URL to shorten your links


I just recently launched my new app - codeurl.net which is very useful for people who wants to shorten links.

One of the key features of this app which is not on the other app like this is the QR Code which you can use to post on your site, etc.. I also have a share functionality for you to share the links from the app itself. There is also a simple analytics to see the number of clicks been made with your links, and more improvements in the future.

You can also customize your links by putting the code that you want using your FREE credits which you can earn by simply register to the app - codeurl.net/register and earn more by inviting friends to sign up - codeurl.net/invite/create

Registration is totally FREE!

Hope you like it and would like to hear comments for improvements.

Wednesday, April 8, 2015

Download files from URL and save it to the server.

This is a simple script that will download files from a URL then will save it to your own PC or server. Hope this helps a lot.

<?php

$source = 'http://dev.axonitconsulting.com/digitalwallet/images/logo-blue-pink.png';
$destination = './logo-blue-pink.png';

dloadSave($file_source, $file_target);

function dloadSave($source='', $destination='./') {
        $rh = fopen($source, 'rb');
        $wh = fopen($destination, 'wb');
        if ($rh===false || $wh===false) {
           // can't read files
           return false;
        }
        while (!feof($rh)) {
            if (fwrite($wh, fread($rh, 1024)) === FALSE) {
                   // can't write to file
                   return false;
               }
        }
        fclose($rh);
        fclose($wh);
        return true;
    }
?>

Tuesday, May 27, 2014

How to get the total facebook friends in PHP

This is just a simple script that will retrieve the total facebook friends of specific user using the graph api. We will be using graph api along with the FQL to get the friend count of the user and by doing that we need the facebook id which we can retrieve by authorizing our app with facebook API.

The output is on JSON which we can decode via PHP, please see sample below.
{ "data": [ { "friend_count": 740 } ] }

<?php 
$fbUserId = <your facebook id>;
$json = file_get_contents("https://graph.facebook.com/fql?q=SELECT%20friend_count%20FROM%20user%20WHERE%20uid=$fbUserId");
$json = json_decode($json);
echo @$json->data[0]->friend_count;
?>


Hope this helps, please leave a comment if you like this post.

Saturday, February 22, 2014

How to save data url into file on PHP

I have a simple script below written on PHP that will save the data url in a file. The example below will save the file on PDF and PNG file. You will notice here that the only difference are the file type and the file name which should comply with the file type you are saving. From the script below, you should be able to figure out how to save the other file types.

This is for saving an image file "PNG", you can also try "JPEG" and other image files.

<?php

$base_url = 'http://www.example.com/';
$file_type = 'image/png';
$file_base = $_POST['dataurl'];
$file_name = "file-".time().".png";

$file_base = str_replace('data:'.$file_type.';base64,', '', $file_base);
$file_base = str_replace('[removed]', '', $file_base);

file_put_contents(getcwd()."/files/$file_name", base64_decode($file_base));
echo $base_url."files/$file_name";

?>


The script below is for saving an application data "PDF" file.

<?php

$base_url = 'http://www.example.com/';
$file_type = 'application/pdf';
$file_base = $_POST['dataurl'];
$file_name = "file-".time().".pdf";

$file_base = str_replace('data:'.$file_type.';base64,', '', $file_base);
$file_base = str_replace('[removed]', '', $file_base);

file_put_contents(getcwd()."/files/$file_name", base64_decode($file_base));
echo $base_url."files/$file_name";

?>


Hope this will help a lot with your development. Happy coding guys!!

Tuesday, December 17, 2013

get_page_by_slug in wordpress

I'm developing a wordpress site and I need a function that will retrieve the page information from a given slug. I'd been looking into wordpress functions but I can't find it, what I saw are just get_page_by_path and get_page_by_title which are not the perfect function I need for the functionality I need for the site.

So, here's what I did. I checked out the existing functionality which is most likely the same of what I wanted to achieve get_page_by_title then from there I was able to arrived a new function get_page_by_slug that will retrieve the page information from a slug.

Please see below, hope this helps a lot on building your wordpress site and hopefully this would be included on the next version of wordpress.

/**
 * Retrieve a page given its slug.
 * @uses $wpdb
 *
 * @param string $page_slug Page slug
 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
 * @param string $post_type Optional. Post type. Default page.
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
    global $wpdb;
    $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) );
    if ( $page )
        return get_post( $page, $output );

    return null;
}


Please take note that you use this as well on retrieving post coz technically, page and post are the same but with different post type, you just need to pass on third parameter as "post". To make it much clearer with names, please see get_post_by_slug function below.

/**
 * Retrieve a post given its slug.
 * @uses $wpdb
 *
 * @param string $slug Post slug
 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
 * @param string $type Optional. Post type. Default page.
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_post_by_slug($slug, $output = OBJECT, $type = 'post' ) {
    global $wpdb;
    $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $slug, $type ) );
    if ( $post )
        return get_post( $post, $output );

    return null;
}

Thursday, November 7, 2013

Create login page in your wordpress site

You can use wordpress admin login functionality for your own website login page. It will use your wordpress table wp_users to validate credentials. Advantage here is that you can manage users via wordpress admin.

If you are using a script outside your template, you should require wp-load.php so you can use its functionality.

require_once( dirname(__FILE__) . '/wp-load.php' );

If your login page is inside your template say you have your page-login.php, then you don't need to require wp-load.php coz it's included already upon loading the page.

Once you have that in place, you can now call the functionality to validate login credential. You just simply call the function user_pass_ok() with parameters: username and password.

Please see sample usage below, you can either use it via GET or POST method, depends on how you handle your login page.

$username = @$_POST['username'];
$password = @$_POST['password'];

if (user_pass_ok($username, $password)) {
    echo 'login success';
} else {
    echo 'login failed';
}


This is just a simple post but hope this helps in a way. Please leave a comment if you like this post.

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

?>

Saturday, December 8, 2012

How to transfer files via SFTP in PHP

It's been a long time since my last post and good I'm back again. Anyway, below is my simple script to transfer files via SFTP in PHP. Hope this helps.

<?php

// set your sftp credential (host, port, username, password)
// local file (source file)
// remote file (destination file)


$host = '<host server to connect>';
$port = '<port to connect>';
$user = '<username to sftp>';
$pass = '<password to sftp>';
$lfile = '/path/to/local/file';
$rfile = '/path/to/remote/file';

// use ssh2 php module to connect

// if ssh2 is not installed/enable, please install/enable)
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $user, $pass);

// use sftp to connect
$sftp = ssh2_sftp($connection);

// open stream connection to remote server
$stream = @fopen('ssh2.sftp://'.$sftp.$rfile, 'w');

try {
    if (!$stream) throw new Exception("Could not open remote file: $rfile");

    // get data of the local file
    $data = @file_get_contents($lfile);
    if ($data === false) throw new Exception("Could not open local file: $lfile.");

    // write the data to stream remote file
    if (@fwrite($stream, $data) === false) throw new Exception("Could not send data from file: $lfile.");
    echo 'done!';

} catch (Exception $e) {
    // echo error message
    echo $e->getMessage();
}

// closing the stream
fclose($stream);

?>


Hope this helps and please leave a post if you like it. Thanks!!

Sunday, August 12, 2012

How to get Longitude / Latitude in PHP using Google Maps API

This post is just a simple script I did, built in PHP that will get the coordinates of specific location.

The script uses google maps web service that returns XML data in which we need parse to get the information we need.

Take note also of the URL I used, you just need to add your google maps key.
http://maps.google.com/maps/geo?output=xml&oe=utf-8&key=enter+your+key+here&q=enter+your+query+here

<?php

$key = 'AIzaSyCrPl5vXuNjPU1fgHF69YPxEopT_NziA4o'; // your google maps key
$param = 'T2G 0S7'; // the location you want to look for, this can be postal code, map id, address, etc.

$geoinfo = get_longlat($key, $param);
var_dump($geoinfo);

function get_longlat($key='', $param='') {
        $request_url = "http://maps.google.com/maps/geo?output=xml&key=$key&oe=utf-8&q=".urlencode($param);
        $xml = simplexml_load_file($request_url);

        $geoinfo = array();
        if (!empty($xml->Response)) {
                $point = $xml->Response->Placemark->Point;
                if (!empty($point)) {
                        $coordinates = explode(",", $point->coordinates);
                        $geoinfo = array(
                                'lon' => $coordinates[0],
                                'lat' => $coordinates[1]
                        );
                }
        }

        return $geoinfo;
}

?>

You can also get other information by parsing the XML returned by the google maps web service. Please see below for the sample XML return.

<kml>
<Response>
    <name>t2g 0s7</name>
    <Status>
        <code>200</code>
        <request>geocode</request>
    </Status>
    <Placemark id="p1">
        <address>Calgary, AB T2G 0S7, Canada</address>
        <AddressDetails Accuracy="5">
            <Country>
                <CountryNameCode>CA</CountryNameCode>
                <CountryName>Canada</CountryName>
                <AdministrativeArea>
                    <AdministrativeAreaName>AB</AdministrativeAreaName>
                    <Locality>
                        <LocalityName>Calgary</LocalityName>
                        <PostalCode>
                            <PostalCodeNumber>T2G 0S7</PostalCodeNumber>
                        </PostalCode>
                    </Locality>
                </AdministrativeArea>
            </Country>
        </AddressDetails>
        <ExtendedData>
            <LatLonBox north="51.0439997" south="51.0413017" east="-114.0367519" west="-114.0394858"/>
        </ExtendedData>
        <Point>
            <coordinates>-114.0380127,51.0426718,0</coordinates>
        </Point>
    </Placemark>
</Response>
</kml>

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

?>

Wednesday, April 25, 2012

How to setup cache pages in PHP

This post will teach you how to setup caching in your pages. This is recommended to setup if your pages is not that dynamic enough that changes frequently.

First, you need to create as to where you will put all your cache files, don't put it on the same directory where your files are in coz it might overwrite your pages. On this post, I created cache directory.

We can also set the cache expiry time by validating the time it was created. To check, we used time() and filemtime() functionality.

To make it work, we will put condition to check if the we have cache file and that it didn't expired yet. If okay, we will just include the file then display the contents. If not, it will capture the page then write to a file.

Please see below for the implementation. Happy coding!!

<?php
$cachefile = "cache/yourpage.html";
$cachetime = 30 * 60; // 30 minutes

// validate and check for existing cache file
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
        include($cachefile);
        exit;
}

// start the output stream
ob_start();
?>

<html>your page here to put into cache</html>

<?php
// save the contents to cache file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);


// end the output stream
ob_end_flush();

?>

Sunday, December 4, 2011

How to validate email address in PHP and jQuery.

PHP has a built in function where you can validate email address, but please take note that it only validates the format of the email address and not to check whether it is real or not.

To check whether the email address is real, you just have to put verification process to your application. Usually, verification process goes with registration process where user have to input their email address and other credentials. The application should send a confirmation link to the email address upon registration. The confirmation link must then be clicked by user to verify their registration or email address.

Anyway, for pre-validation, it's still better to put format validation of email address. This is for the application not to waste time of sending emails. Please see below for the quick and easy way in PHP.

<?php
$email = 'paul123@wideumbrella';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "valid";
} else {
        echo "invalid";
}

?>


You can also validate the email address using jQuery. Please see custom function and implementation I did for jQuery.

<html>
<head>
<title>Validate Email</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
        $.fn.validateEmail = function() {
                var email = $(this).val();
                var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

                return pattern.test(email);
        }

        $(document).ready(function() {
                $('.btnValidate').click(function() {
                        alert($('#email').validateEmail());
                });
        });
</script>
</head>
<body>
        <input type="text" value="" id="email"><a class="btnValidate" title="Validate" href="#">Validate</a>
</body>
</html>


Quote for the day: Perseverance is needed to release most of life's rewards. It's the last step in the race that counts the most. That is where the winner is determined. That is where the rewards come. If you run every step of the race well except the last one and you stop before the finish line, then the end result will be the the same if you never ran a step.

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.