使用PHP从Quickbooks(借助API)获取发票

时间:2013-07-30 06:31:03

标签: php api quickbooks

这是我的情景。

  1. 将有一家公司在QuickBooks上拥有商业帐户。

  2. 公司会将客户/客户/用户添加到他们的帐户中。

  3. 现在公司将向这些客户/客户/用户开具发票。

  4. 我必须显示(列出)公司生成的发票,我将传递CustomerID(ClientID / UserID)作为参数,仅为该客户/用户/客户获取发票。

  5. 请注意,公司将向我们提供其凭据,以便获取其客户/客户/用户的发票。 我只需要显示发票,我不需要使用Quickbooks或Quickbooks API做任何其他事情。 另请注意,我已从Quickbooks Online和桌面版本(使用Web连接器)获取发票。

    先谢谢,

1 个答案:

答案 0 :(得分:4)

如果您正在构建SaaS服务(例如,您每月向客户收取费用以将QuickBooks连接到您的应用),那么您可以使用 IPP / IDS 来执行此操作。 如果您不按月收费,则可以使用 Web Connector / qbXML 进行此操作。

无论您使用哪种连接类型,这都没有任何意义:

  
      
  1. 我必须显示(列出)公司生成的发票,我将传递CustomerID(ClientID / UserID)作为参数来获取发票   仅限客户/用户/客户。
  2.   

OAuth令牌/连接是特定于QuickBooks的公司文件,并且没有此类字段“CustomerID”(或“ClientID”或“UserID”)。

对于SaaS / IPP / IDS示例,请下载:

看看这些脚本:

  • 文档/ example_ipp_config.php
  • 文档/ example_ipp_oauth.php
  • 文档/ example_ipp_ids_5.php

您必须在此注册才能获得自己的OAuth令牌:

docs / example_ipp_ids_5.php脚本显示了如何获取所有客户。您可以将其更改为使用QuickBooks_IPP_Service_Invoice来取代所有发票。

您的代码最终会看起来像这样:

$Service = new QuickBooks_IPP_Service_Invoice();

$perpage = 3;
for ($page = 1; $page <= 3; $page++)
{
    print('PAGE ' . $page . "\n\n");

    $list = $InvoiceService->findAll($Context, $realm, null, $page, $perpage);

    foreach ($list as $Invoice)
    {
        print('Internal ID [' . $Invoice->getId() . ' => ' . $Invoice->getHeader()->getDocNumber() . ']' . "\n\n");
    }

    print("\n\n\n");
}

对于Web连接器示例(QuickBooks桌面),请下载:

看看这个例子:

  • 文档/ example_web_connector_import.php

快速入门指南:

你最终会得到类似的东西:

/**
 * Build a request to import invoices already in QuickBooks into our application
 */
function _quickbooks_invoice_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">
                <InvoiceQueryRq ' . $attr_iterator . ' ' . $attr_iteratorID . ' requestID="' . $requestID . '">
                    <MaxReturned>' . QB_QUICKBOOKS_MAX_RETURNED . '</MaxReturned>
                    <ModifiedDateRangeFilter>
                        <FromModifiedDate>' . $last . '</FromModifiedDate>
                    </ModifiedDateRangeFilter>
                    <IncludeLineItems>true</IncludeLineItems>
                    <OwnerID>0</OwnerID>
                </InvoiceQueryRq>   
            </QBXMLMsgsRq>
        </QBXML>';

    return $xml;
}

/** 
 * Handle a response from QuickBooks 
 */
function _quickbooks_invoice_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_INVOICE, null, QB_PRIORITY_INVOICE, array( 'iteratorID' => $idents['iteratorID'] ));
    }

    // This piece of the response from QuickBooks is now stored in $xml. You 
    //  can process the qbXML response in $xml in any way you like. Save it to 
    //  a file, stuff it in a database, parse it and stuff the records in a 
    //  database, etc. etc. etc. 
    //  
    // The following example shows how to use the built-in XML parser to parse 
    //  the response and stuff it into a database. 

    // 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/InvoiceQueryRs');

        foreach ($List->children() as $Invoice)
        {
            $arr = array(
                'TxnID' => $Invoice->getChildDataAt('InvoiceRet TxnID'),
                'TimeCreated' => $Invoice->getChildDataAt('InvoiceRet TimeCreated'),
                'TimeModified' => $Invoice->getChildDataAt('InvoiceRet TimeModified'),
                'RefNumber' => $Invoice->getChildDataAt('InvoiceRet RefNumber'),
                'Customer_ListID' => $Invoice->getChildDataAt('InvoiceRet CustomerRef ListID'),
                'Customer_FullName' => $Invoice->getChildDataAt('InvoiceRet CustomerRef FullName'),
                'ShipAddress_Addr1' => $Invoice->getChildDataAt('InvoiceRet ShipAddress Addr1'),
                'ShipAddress_Addr2' => $Invoice->getChildDataAt('InvoiceRet ShipAddress Addr2'),
                'ShipAddress_City' => $Invoice->getChildDataAt('InvoiceRet ShipAddress City'),
                'ShipAddress_State' => $Invoice->getChildDataAt('InvoiceRet ShipAddress State'),
                'ShipAddress_PostalCode' => $Invoice->getChildDataAt('InvoiceRet ShipAddress PostalCode'),
                'BalanceRemaining' => $Invoice->getChildDataAt('InvoiceRet BalanceRemaining'),
                );

            QuickBooks_Utilities::log(QB_QUICKBOOKS_DSN, 'Importing invoice #' . $arr['RefNumber'] . ': ' . print_r($arr, true));

            foreach ($arr as $key => $value)
            {
                $arr[$key] = mysql_real_escape_string($value);
            }

            // Store the invoices in MySQL
            mysql_query("
                REPLACE INTO
                    qb_example_invoice
                (
                    " . implode(", ", array_keys($arr)) . "
                ) VALUES (
                    '" . implode("', '", array_values($arr)) . "'
                )") or die(trigger_error(mysql_error()));

            // Remove any old line items
            mysql_query("DELETE FROM qb_example_invoice_lineitem WHERE TxnID = '" . mysql_real_escape_string($arr['TxnID']) . "' ") or die(trigger_error(mysql_error()));

            // Process the line items
            foreach ($Invoice->children() as $Child)
            {
                if ($Child->name() == 'InvoiceLineRet')
                {
                    $InvoiceLine = $Child;

                    $lineitem = array( 
                        'TxnID' => $arr['TxnID'], 
                        'TxnLineID' => $InvoiceLine->getChildDataAt('InvoiceLineRet TxnLineID'), 
                        'Item_ListID' => $InvoiceLine->getChildDataAt('InvoiceLineRet ItemRef ListID'), 
                        'Item_FullName' => $InvoiceLine->getChildDataAt('InvoiceLineRet ItemRef FullName'), 
                        'Descrip' => $InvoiceLine->getChildDataAt('InvoiceLineRet Desc'), 
                        'Quantity' => $InvoiceLine->getChildDataAt('InvoiceLineRet Quantity'),
                        'Rate' => $InvoiceLine->getChildDataAt('InvoiceLineRet Rate'), 
                        );

                    foreach ($lineitem as $key => $value)
                    {
                        $lineitem[$key] = mysql_real_escape_string($value);
                    }

                    // Store the lineitems in MySQL
                    mysql_query("
                        INSERT INTO
                            qb_example_invoice_lineitem
                        (
                            " . implode(", ", array_keys($lineitem)) . "
                        ) VALUES (
                            '" . implode("', '", array_values($lineitem)) . "'
                        ) ") or die(trigger_error(mysql_error()));
                }
            }
        }
    }

    return true;
}

对于通过qbXML示例 QuickBooks Online (QuickBooks Online),请下载:

看看这个例子:

  • 文档/ example_online_edition.php

你最终会得到类似的东西:

// Register in DESKTOP mode to get these. Docs: 
//  http://www.consolibyte.com/docs/index.php/QuickBooks_Online_via_qbXML#Connecting_with_the_.27Desktop.27_model_of_communication
$application_id = '134476472';
$application_login = 'qboe.test.test.com';
$connection_ticket = 'TGT-47-1sRm2nXMVfm$n8hb2MZfVQ';

// Create our new gateway instance 
$Gateway = new QuickBooks_Gateway_OnlineEdition(
    $application_id,
    $application_login,
    $connection_ticket);

$xml = '<QBXMLMsgsRq onError="stopOnError">
            <InvoiceQueryRq>

            </InvoiceQueryRq>
        </QBXMLMsgsRq>';

// Send the request
$resp = $Gateway->qbxml($xml);

print($resp);