Topic: how to import items from quickbook to my database using web connector

Hi Keith,

I am using quickbook enterprise solution: Manufacturing and wholesale 16.0 windows version. To import items i am using web connector.
My issue is it only imports those items which are updated/modified. But i want to import all items of quickbook into my database. Code i am using is given below. Please help me to figure this out.

<?php
//q = Queued up and waiting to be processed.
//i = In progress (If you see this, and the Web Connector is *not* currently processing requests, then something probably went wrong and this request failed because you have a PHP error or a qbXML request that doesn't validate.).
//s = Successfully processed.
//e = An error occurred while processing this request.
//h = An error occurred while processing this request, but an error handler handled the error successfully (note: QuickBooks will return an error code if you search for an object(s) and the object(s) is not found. Thus, if your code does searches, and then catches 500 or 1 error codes, you will see 'h' statuses. Thus, an 'h' status doesn't necessarily indicate a problem per se, it just indicates that QuickBooks threw an error and you caught it.)
//n = NoOp - this operation was skipped because the request handler returned a QUICKBOOKS_NOOP NoOp value.

//TRUNCATE `quickbooks_config`;TRUNCATE `quickbooks_log`;TRUNCATE `quickbooks_oauth`;TRUNCATE `quickbooks_queue`;TRUNCATE `quickbooks_recur`;TRUNCATE `quickbooks_ticket`;
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
if (function_exists('date_default_timezone_set'))
{
    // * MAKE SURE YOU SET THIS TO THE CORRECT TIMEZONE! *
    // List of valid timezones is here: http://us3.php.net/manual/en/timezones.php
    date_default_timezone_set('America/New_York');
}
require_once 'QuickBooks.php';
$user = 'admin';
$pass = 'webacc882o15';
/**
* Configuration parameter for the quickbooks_config table, used to keep track of the last time the QuickBooks sync ran
*/
define('QB_QUICKBOOKS_CONFIG_LAST', 'last');
/**
* Configuration parameter for the quickbooks_config table, used to keep track of the timestamp for the current iterator
*/
define('QB_QUICKBOOKS_CONFIG_CURR', 'curr');
/**
* Maximum number of customers/invoices returned at a time when doing the import
*/
define('QB_QUICKBOOKS_MAX_RETURNED', 10);
/**
*
*/
define('QB_PRIORITY_PURCHASEORDER', 4);
/**
* Request priorities, items sync first
*/
define('QB_PRIORITY_ITEM', 3);
/**
* Request priorities, customers
*/
define('QB_PRIORITY_CUSTOMER', 0);
/**
* Request priorities, salesorders
*/
define('QB_PRIORITY_SALESORDER', 1);
/**
* Request priorities, invoices last...
*/
define('QB_PRIORITY_INVOICE', 2);
/**
* Send error notices to this e-mail address
*/
define('QB_QUICKBOOKS_MAILTO', 'kunal.kumar@adaan.com');
$map = array(
    //QUICKBOOKS_IMPORT_CUSTOMER => array( '_quickbooks_customer_import_request', '_quickbooks_customer_import_response' ),
    ///QUICKBOOKS_QUERY_INVOICE => array( '_quickbooks_invoice_query_request', '_quickbooks_invoice_query_response' ),
    //QUICKBOOKS_QUERY_CUSTOMER => array( '_quickbooks_customer_query_request', '_quickbooks_customer_query_response', '_quickbooks_error_catchall' ),
    //QUICKBOOKS_ADD_INVOICE => array( '_quickbooks_invoice_add_request', '_quickbooks_invoice_add_response' ),
    //QUICKBOOKS_QUERY_DELETEDTXNS => array( '_quickbooks_invoice_del_request', '_quickbooks_invoice_del_response' ),
    //QUICKBOOKS_IMPORT_INVOICE => array( '_quickbooks_invoice_import_request', '_quickbooks_invoice_import_response' ),
    //QUICKBOOKS_ADD_RECEIVEPAYMENT => array( '_quickbooks_payment_add_request', '_quickbooks_payment_add_response' ),
    QUICKBOOKS_IMPORT_ITEM => array( '_quickbooks_item_import_request', '_quickbooks_item_import_response' ),
   
    );

$errmap = array(
    500 => '_quickbooks_error_e500_notfound',             // Catch errors caused by searching for things not present in QuickBooks
    1 => '_quickbooks_error_e500_notfound',
    '*' => '_quickbooks_error_catchall',                 // Using a key value of '*' will catch any errors which were not caught by another error handler
    );

$hooks = array(
     QuickBooks_WebConnector_Handlers::HOOK_LOGINSUCCESS => '_quickbooks_hook_loginsuccess',     // call this whenever a successful login occurs
    );

// Logging level
//$log_level = QUICKBOOKS_LOG_VERBOSE;
$log_level = QUICKBOOKS_LOG_DEBUG;             
//$log_level = QUICKBOOKS_LOG_DEVELOP;        // Use this level until you're sure everything works!!!
$soapserver = QUICKBOOKS_SOAPSERVER_BUILTIN;        // A pure-PHP SOAP server (no PHP ext/soap extension required, also makes debugging easier)
$soap_options = array(
    );

$handler_options = array(
    'deny_concurrent_logins' => false,
    'deny_reallyfast_logins' => false,
    );

$driver_options = array(
    );

$callback_options = array(
);
$dsn = 'mysqli://root:@localhost/topimex';
define('QB_QUICKBOOKS_DSN', $dsn);

QuickBooks_WebConnector_Queue_Singleton::initialize($dsn);

//$handler_options = array(); $driver_options = array(); $callback_options = array();
$Server = new QuickBooks_WebConnector_Server($dsn, $map, $errmap, $hooks, $log_level, $soapserver, QUICKBOOKS_WSDL, $soap_options, $handler_options, $driver_options, $callback_options);
$response = $Server->handle(true, true);
//$fp = fopen('file.log', 'a+');
//fwrite($fp, htmlspecialchars_decode($response));
//fclose($fp);

function _quickbooks_error_e500_notfound($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
    $Queue = QuickBooks_WebConnector_Queue_Singleton::getInstance();
   
    if ($action == QUICKBOOKS_IMPORT_ITEM)
    {
        return true;
    }
    else if ($action == QUICKBOOKS_MOD_CUSTOMER)
    {
        return true;
    }
    //$fp = fopen('myText.txt', 'a+');
    //fwrite($fp, $errmsg);
    //fclose($fp);
    $fp = fopen('file.log', 'a+');
    fwrite($fp, $errmsg);
    fclose($fp);
    return false;
}
function _quickbooks_error_catchall($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
    /*
    $message = '';
        $message .= 'Request ID: ' . $requestID . "\r\n";
        $message .= 'User: ' . $user . "\r\n";
        $message .= 'Action: ' . $action . "\r\n";
        $message .= 'ID: ' . $ID . "\r\n";
        $message .= 'Extra: ' . print_r($extra, true) . "\r\n";
        //$message .= 'Error: ' . $err . "\r\n";
        $message .= 'Error number: ' . $errnum . "\r\n";
        $message .= 'Error message: ' . $errmsg . "\r\n";
       
        mail(QB_QUICKBOOKS_MAILTO,
            'QuickBooks error occured!',
            $message);*/
    if ($action == QUICKBOOKS_ADD_CUSTOMER and $errnum == 3100)
    {
           return true; // Ignore this error, all is OK - customer already exists
    }
    if ($action == QUICKBOOKS_QUERY_CUSTOMER)
    {
        $Queue = new QuickBooks_WebConnector_Queue('mysqli://root:@localhost/topimex');
           $Queue->enqueue(QUICKBOOKS_ADD_CUSTOMER, $ID);
    }
    $content = "##########################################################\r\n";
    //$content .= $idents;
    $content .= "##########################################################\r\n";
    $content .= $xml;
    $content .= "##########################################################\r\n";
    $content .= $errmsg;
    $fp = fopen('file.log', 'a+');
    fwrite($fp, $content);
    fclose($fp);
    $message = '';
    $message .= 'Request ID: ' . $requestID . "\r\n";
    $message .= 'User: ' . $user . "\r\n";
    $message .= 'Action: ' . $action . "\r\n";
    $message .= 'ID: ' . $ID . "\r\n";
    $message .= 'Extra: ' . print_r($extra, true) . "\r\n";
    //$message .= 'Error: ' . $err . "\r\n";
    $message .= 'Error number: ' . $errnum . "\r\n";
    $message .= 'Error message: ' . $errmsg . "\r\n";
    $fp = fopen('file.log', 'a+');
    fwrite($fp, $message);
    fclose($fp);
   
    return true;       
   
}
function _quickbooks_get_last_run($user, $action)
{
    $type = null;
    $opts = null;
    return QuickBooks_Utilities::configRead(QB_QUICKBOOKS_DSN, $user, md5(__FILE__), QB_QUICKBOOKS_CONFIG_LAST . '-' . $action, $type, $opts);
}
function _quickbooks_set_last_run($user, $action, $force = null)
{
    $value = date('Y-m-d') . 'T' . date('H:i:s');
   
    if ($force)
    {
        $value = date('Y-m-d', strtotime($force)) . 'T' . date('H:i:s', strtotime($force));
    }
   
    return QuickBooks_Utilities::configWrite(QB_QUICKBOOKS_DSN, $user, md5(__FILE__), QB_QUICKBOOKS_CONFIG_LAST . '-' . $action, $value);
}
function _quickbooks_get_current_run($user, $action)
{
    $type = null;
    $opts = null;
    return QuickBooks_Utilities::configRead(QB_QUICKBOOKS_DSN, $user, md5(__FILE__), QB_QUICKBOOKS_CONFIG_CURR . '-' . $action, $type, $opts);   
}
function _quickbooks_set_current_run($user, $action, $force = null)
{
    $value = date('Y-m-d') . 'T' . date('H:i:s');
   
    if ($force)
    {
        $value = date('Y-m-d', strtotime($force)) . 'T' . date('H:i:s', strtotime($force));
    }
   
    return QuickBooks_Utilities::configWrite(QB_QUICKBOOKS_DSN, $user, md5(__FILE__), QB_QUICKBOOKS_CONFIG_CURR . '-' . $action, $value);   
}

function _quickbooks_hook_loginsuccess($requestID, $user, $hook, &$err, $hook_data, $callback_config)
{
    $Queue = QuickBooks_WebConnector_Queue_Singleton::getInstance();
    $date = '2010-05-29 12:01:01';
    // Do the same for customers
    if (!_quickbooks_get_last_run($user, QUICKBOOKS_IMPORT_ITEM))
    {
        _quickbooks_set_last_run($user, QUICKBOOKS_IMPORT_ITEM, $date);
    }
    //$Queue->enqueue(QUICKBOOKS_IMPORT_ITEM, 1);
    $Queue->enqueue(QUICKBOOKS_IMPORT_ITEM, 1, QB_PRIORITY_ITEM);
}

function _quickbooks_item_import_request($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale)
{
    // Iterator support (break the result set into small chunks)
    $attr_iteratorID = '';
    $attr_iterator = ' iterator="Start" ';
    if (empty($extra['iteratorID']))
    {
        // This is the first request in a new batch
        $last = _quickbooks_get_last_run($user, $action);
        _quickbooks_set_last_run($user, $action);            // Update the last run time to NOW()
       
        // Set the current run to $last
        _quickbooks_set_current_run($user, $action, $last);
    }
    else
    {
        // This is a continuation of a batch
        $attr_iteratorID = ' iteratorID="' . $extra['iteratorID'] . '" ';
        $attr_iterator = ' iterator="Continue" ';
       
        $last = _quickbooks_get_current_run($user, $action);
    }
   
    // Build the request
    $xml = '<?xml version="1.0" encoding="utf-8"?>
        <?qbxml version="' . $version . '"?>
        <QBXML>
            <QBXMLMsgsRq onError="stopOnError">
                <ItemQueryRq ' . $attr_iterator . ' ' . $attr_iteratorID . ' requestID="' . $requestID . '">
                    <MaxReturned>' . QB_QUICKBOOKS_MAX_RETURNED . '</MaxReturned>
                    <FromModifiedDate>' . $last . '</FromModifiedDate>
                    <OwnerID>0</OwnerID>
                </ItemQueryRq>   
            </QBXMLMsgsRq>
        </QBXML>';
       
    return $xml;
}
function _quickbooks_item_import_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{   
    if (!empty($idents['iteratorRemainingCount']))
    {
        // Queue up another request
        $Queue = QuickBooks_WebConnector_Queue_Singleton::getInstance();
        $Queue->enqueue(QUICKBOOKS_IMPORT_ITEM, null, QB_PRIORITY_ITEM, array( 'iteratorID' => $idents['iteratorID'] ));
    }
   
    // Import all of the records
    $errnum = 0;
    $errmsg = '';
    $Parser = new QuickBooks_XML_Parser($xml);
    if ($Doc = $Parser->parse($errnum, $errmsg))
    {
        $Root = $Doc->getRoot();
        $List = $Root->getChildAt('QBXML/QBXMLMsgsRs/ItemQueryRs');
        foreach ($List->children() as $Item)
        {
            $type = substr(substr($Item->name(), 0, -3), 4);
            $ret = $Item->name();
           
            $arr = array(
                'ListID' => $Item->getChildDataAt($ret . ' ListID'),
                'TimeCreated' => $Item->getChildDataAt($ret . ' TimeCreated'),
                'TimeModified' => $Item->getChildDataAt($ret . ' TimeModified'),
                'Name' => $Item->getChildDataAt($ret . ' Name'),
                'FullName' => $Item->getChildDataAt($ret . ' FullName'),
                'Type' => $type,
                'Parent_ListID' => $Item->getChildDataAt($ret . ' ParentRef ListID'),
                'Parent_FullName' => $Item->getChildDataAt($ret . ' ParentRef FullName'),
                'ManufacturerPartNumber' => $Item->getChildDataAt($ret . ' ManufacturerPartNumber'),
                'UnitOfMeasureSetRef' => $Item->getChildDataAt($ret . ' UnitOfMeasureSetRef'),
                'SalesTaxCode_ListID' => $Item->getChildDataAt($ret . ' SalesTaxCodeRef ListID'),
                'SalesTaxCode_FullName' => $Item->getChildDataAt($ret . ' SalesTaxCodeRef FullName'),
                'BuildPoint' => $Item->getChildDataAt($ret . ' BuildPoint'),
                'ReorderPoint' => $Item->getChildDataAt($ret . ' ReorderPoint'),
                'QuantityOnHand' => $Item->getChildDataAt($ret . ' QuantityOnHand'),
                'AverageCost' => $Item->getChildDataAt($ret . ' AverageCost'),
                'QuantityOnOrder' => $Item->getChildDataAt($ret . ' QuantityOnOrder'),
                'QuantityOnSalesOrder' => $Item->getChildDataAt($ret . ' QuantityOnSalesOrder'), 
                'TaxRate' => $Item->getChildDataAt($ret . ' TaxRate'), 
                );
            foreach ($Item->children() as $Node)
            {
                // Be careful! Custom field names are case sensitive!
                if ($Node->name() === 'DataExtRet' and $Node->getChildDataAt('DataExtRet DataExtName') == 'Category')
                {
                    $arr['CATEGORY'] = $Node->getChildDataAt('DataExtRet DataExtValue');
                }
                if ($Node->name() === 'DataExtRet' and $Node->getChildDataAt('DataExtRet DataExtName') == 'Sub-Category')
                {
                    $arr['SUBCATEGORY'] = $Node->getChildDataAt('DataExtRet DataExtValue');
                }
                if ($Node->name() === 'DataExtRet' and $Node->getChildDataAt('DataExtRet DataExtName') == 'Stock Location')
                {
                    $values['Stock Location'] = $Node->getChildDataAt('DataExtRet DataExtValue');
                }
            }   
            $look_for = array(
                'SalesPrice' => array( 'SalesOrPurchase Price', 'SalesAndPurchase SalesPrice', 'SalesPrice' ),
                'SalesDesc' => array( 'SalesOrPurchase Desc', 'SalesAndPurchase SalesDesc', 'SalesDesc' ),
                'PurchaseCost' => array( 'SalesOrPurchase Price', 'SalesAndPurchase PurchaseCost', 'PurchaseCost' ),
                'PurchaseDesc' => array( 'SalesOrPurchase Desc', 'SalesAndPurchase PurchaseDesc', 'PurchaseDesc' ),
                'PrefVendor_ListID' => array( 'SalesAndPurchase PrefVendorRef ListID', 'PrefVendorRef ListID' ),
                'PrefVendor_FullName' => array( 'SalesAndPurchase PrefVendorRef FullName', 'PrefVendorRef FullName' ),
                );
            foreach ($look_for as $field => $look_here)
            {
                if (!empty($arr[$field]))
                {
                    break;
                }
               
                foreach ($look_here as $look)
                {
                    $arr[$field] = $Item->getChildDataAt($ret . ' ' . $look);
                }
            }
            $db = new mysqli('localhost','root','','topimex');
            $result = $db->query("select product_id from products where sku='".$arr['FullName']."'");
            if($result->num_rows){
                $res = $result->fetch_assoc();
                $result = $db->query("UPDATE products SET price ='".$arr['SalesPrice']."',quantity='".$arr['QuantityOnHand']."' WHERE product_id='".$res['product_id']."'");
                $cat_sql = $db->query("select category_id from categories where category_name='".$arr['CATEGORY']."'");
                if($cat_sql->num_rows){
                    $cat_res = $cat_sql->fetch_assoc();
                    $cat_del_query = $db->query("delete from prod_cat WHERE prod_id='".$res['product_id']."'");
                    $result = $db->query("insert into prod_cat(`cat_id`,`prod_id`) values('".$cat_res['category_id']."','".$res['product_id']."')");
                }
                $sub_cat_sql = $db->query("select category_id from categories where category_name='".$arr['SUBCATEGORY']."'");
                if($sub_cat_sql->num_rows){
                    $sub_cat_res = $sub_cat_sql->fetch_assoc();
                    $result = $db->query("insert into prod_cat(`cat_id`,`prod_id`) values('".$sub_cat_res['category_id']."','".$res['product_id']."')");
                }
            }else{
                $mascode = str_shuffle($arr['FullName']);
                $result = $db->query("insert into products(`product_name`,`product_slug`,`short_desc`,`sku`,`mascode`,`price`,`quantity`) values('".$mascode."','".$mascode."','".$arr['SalesDesc']."','".$arr['FullName']."','".$mascode."','".$arr['SalesPrice']."','".$arr['QuantityOnHand']."')");
                $product_id = $db->insert_id;
                $cat_sql = $db->query("select category_id from categories where category_name='".$arr['CATEGORY']."'");
                if($cat_sql->num_rows){
                    $cat_res = $cat_sql->fetch_assoc();
                    $result = $db->query("insert into prod_cat(`cat_id`,`prod_id`) values('".$cat_res['category_id']."','".$product_id."')");
                }
                $sub_cat_sql = $db->query("select category_id from categories where category_name='".$arr['SUBCATEGORY']."'");
                if($sub_cat_sql->num_rows){
                    $sub_cat_res = $sub_cat_sql->fetch_assoc();
                    $result = $db->query("insert into prod_cat(`cat_id`,`prod_id`) values('".$sub_cat_res['category_id']."','".$product_id."')");
                }
            }
            //QuickBooks_Utilities::log(QB_QUICKBOOKS_DSN, 'Importing ' . $type . ' Item ' . $arr['FullName'] . ': ' . print_r($arr, true));
            //$fp = fopen('file.log', 'a+');
            //fwrite($fp,  'Importing ' . $type . ' Item ' . $arr['FullName'] . ': ' . print_r($arr, true));
            //fwrite($fp,$kk);
            //fclose($fp);
        }
    }
   
    return true;
}

function _quickbooks_item_query_request($requestID , $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale){
        $db = new mysqli('localhost','root','','topimex');
       
        $xml = '<?xml version="1.0" encoding="utf-8"?>
                <?qbxml version="'.$version.'"?>
                <QBXML>
                  <QBXMLMsgsRq onError="continueOnError">
                    <ItemQueryRq requestID="' . $requestID . '">
                         <FullName>'.$extra[0].'</FullName>
                       
                    </ItemQueryRq>
                  </QBXMLMsgsRq>
                </QBXML>';
                return $xml;
       
        }

function _quickbooks_item_query_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents){
    $db = new mysqli('localhost','root','','topimex');
    $result = $db->query("UPDATE subjects SET ListID = '" . mysqli_real_escape_string($db,$idents['ListID']) . "',EditSequence = '" . mysqli_real_escape_string($db,$idents['EditSequence']) . "' WHERE subject_id = '".$ID."'");
   
}

Re: how to import items from quickbook to my database using web connector

My issue is it only imports those items which are updated/modified. But i want to import all items of quickbook into my database.

You told it to do this.

Fix your code so that you're not telling us to only import things added/modified since a given date:

// Build the request
    $xml = '<?xml version="1.0" encoding="utf-8"?>
        <?qbxml version="' . $version . '"?>
        <QBXML>
            <QBXMLMsgsRq onError="stopOnError">
                <ItemQueryRq ' . $attr_iterator . ' ' . $attr_iteratorID . ' requestID="' . $requestID . '">
                    <MaxReturned>' . QB_QUICKBOOKS_MAX_RETURNED . '</MaxReturned>
                    <FromModifiedDate>' . $last . '</FromModifiedDate>
                    <OwnerID>0</OwnerID>
                </ItemQueryRq>    
            </QBXMLMsgsRq>
        </QBXML>';

Remove the "FromModifiedDate" node.

Re: how to import items from quickbook to my database using web connector

Thanks a lot Keith for your quick response.

Re: how to import items from quickbook to my database using web connector

Buy Sinemet Canada Prezzo Cialis 5 Mg  tadalafil cialis from india Propecia 12 Weeks Como Comprar Cytotec Sin Receta Medica Keflex Doseage Strep Throat

Cyproheptadine Baclofene Temoignage  cialis vs viagra Cialis 33 Anos Prezzo Viagra Italia Was Ist Viagra Wikipedia

Re: how to import items from quickbook to my database using web connector

Buy Cheap Tegretol Uk  п»їcialis Amoxicillin Sun Exposure  &lt;a href=http://abuycialisb.com&gt;Cialis&lt;/a&gt; Commande De Furosemide 100 Mg Sur Site Securisee

Viagra Pfizer Acheter  Buy Cialis What Is Cephalexin Do For Dogs

Re: how to import items from quickbook to my database using web connector

Buy Cheap Tegretol Uk  п»їcialis Amoxicillin Sun Exposure  <a href=http://abuycialisb.com>Cialis</a> Commande De Furosemide 100 Mg Sur Site Securisee

Viagra Pfizer Acheter  Buy Cialis What Is Cephalexin Do For Dogs