Skip to content

Freshbooks API Parser

Derek Jones edited this page Jul 5, 2012 · 3 revisions

This is a library that parses XML from the Freshbooks API. The only thing you need to update would be:

XML_POST_USER = Your Freshbooks Token XML_POST_URL = Your Freshbooks API URL

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Freshbooks {

    function loop($request)
    {
        // Define request, username, password, and api url
        define('XML_PAYLOAD',$request);
        define('XML_POST_USER','your_TOKEN');
        define('XML_POST_PASS', 'X');
        define('XML_POST_URL', 'https://example.freshbooks.com/api/2.1/xml-in');
        
        // cURL to make it rain
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
        curl_setopt($ch, CURLOPT_USERPWD, XML_POST_USER.":".XML_POST_PASS);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_TIMEOUT, 4); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
        
        // Run timer to see how long the total result takes.
        $start = array_sum(explode(' ', microtime()));
        $result = curl_exec($ch); 
        $stop = array_sum(explode(' ', microtime()));
        $totalTime = $stop - $start;
        
        // Check for errors
        if ( curl_errno($ch) ) {
            $result = 'cURL ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
        } else {
            $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            switch($returnCode){
                case 200:
                    break;
                default:
                    $result = 'HTTP ERROR -> ' . $returnCode;
                    break;
            }
        }
        
        // Close the cURL stuff that just rained
        curl_close($ch);
        
        // Return the result
        return $result;
        
        // Probably will need to delete this, because I'm not sure what it does...Google me baby.
        exit(0);
    }
}

?>

Then create a controller that send a request XML to the function:

<?

class Update_billing extends Controller {

    function Update_billing()
    {
        parent::Controller();
    }
    
    function index()
    {
        $this->load->library('freshbooks');
        
        $request = '&lt;?xml version="1.0" encoding="utf-8"?&gt;<request method="recurring.get"><recurring_id>1</recurring_id></request>';
        
        $result = $this->freshbooks->loop($request);
        
        echo $result;
    }
}
Clone this wiki locally