Подтвердить что ты не робот

Интеграция API QuickBooks API (php)

Я очень новичок в QuickBooks. Я создал пробную учетную запись в Quick Books, и я хочу добавить клиентов, создать счета-фактуры или подобные вещи для своей учетной записи. Я загрузил php SDK из github. Теперь у меня нет идеи, как начать, с чего начать добавлять клиента в свою учетную запись после того, как клиент сделает заказ с моего сайта. Может ли кто-нибудь помочь мне с подробной документацией или некоторыми примерами, чтобы я мог двигаться вперед. Я не знаю о коннекторе веб-приложений. Я совершенно новый. Спасибо..

4b9b3361

Ответ 1

Это будет двухчастный ответ, потому что вы не указали, используете ли вы QuickBooks ONLINE или QuickBooks для WINDOWS.

Процесс будет РАЗЛИЧНЫМ, в зависимости от того, что вы используете, поэтому обратите внимание на жирные заголовки ниже:

Для QuickBooks ONLINE:

Если вы используете openBook QuickBooks PHP DevKit от GitHub, то лучшим местом для начала является QuickBooks Онлайн с быстрым запуском PHP.

Самое первое, что вам нужно сделать, это зарегистрировать свое приложение с Intuit. Когда вы это сделаете, Intuit предоставит вам следующие переменные:

  • токен приложения
  • секрет пользователя
  • потребительский ключ

Вы замените эти переменные на config.php файл, который включен в пример. Вы также обновите эти значения, чтобы указать на свое приложение:

  • oauth url (например, your-site.com/path/to/example/oauth.php)
  • URL-адрес успеха (например, your-site.com/path/to/example/success.php)
  • URL-адрес меню (например, your-site.com/path/to/example/menu.php)
  • dsn (ваша резервная копия базы данных для хранилища токенов OAuth)

Кроме того, вы можете оставить все остальные переменные в config.php по умолчанию.

Если вы затем посетите файл index.php, вам будет предложено подключиться к QuickBooks. Вы можете подключиться, а затем посетить файлы примеров. Вот несколько примеров добавления клиентов/заказов в QuickBooks Online:

В результате код выглядит примерно так:

    $CustomerService = new QuickBooks_IPP_Service_Customer();

    $Customer = new QuickBooks_IPP_Object_Customer();
    $Customer->setTitle('Mr');
    $Customer->setGivenName('Keith');
    $Customer->setMiddleName('R');
    $Customer->setFamilyName('Palmer');
    $Customer->setDisplayName('Keith R Palmer Jr ' . mt_rand(0, 1000));

    // Phone #
    $PrimaryPhone = new QuickBooks_IPP_Object_PrimaryPhone();
    $PrimaryPhone->setFreeFormNumber('860-532-0089');
    $Customer->setPrimaryPhone($PrimaryPhone);

    // Bill address
    $BillAddr = new QuickBooks_IPP_Object_BillAddr();
    $BillAddr->setLine1('72 E Blue Grass Road');
    $BillAddr->setLine2('Suite D');
    $BillAddr->setCity('Mt Pleasant');
    $BillAddr->setCountrySubDivisionCode('MI');
    $BillAddr->setPostalCode('48858');
    $Customer->setBillAddr($BillAddr);

    if ($resp = $CustomerService->add($Context, $realm, $Customer))
    {
            print('Our new customer ID is: [' . $resp . ']');
    }

Чтобы реализовать дополнительные функции, вы найдете другие примеры, включенные в код.

Доступные объекты/методы также отображают документацию Intuit, поэтому вы захотите посмотреть на это.

Для QuickBooks для WINDOWS:

Для QuickBooks для Windows вы будете использовать веб-коннектор. Опять же, начните с с открытым исходным кодом QuickBooks PHP DevKit от GitHub. Используйте вместо этого QuickBooks for Windows + PHP.

Это поможет вам создать простой сервис Web Connector, который добавит тестовых клиентов в QuickBooks.

В принципе вы создаете файл .QWC, который вы загрузите в веб-коннектор QuickBooks ( "Пуск" > "Все программы" > "QuickBooks" > "Веб-коннектор" ). Этот файл .QWC укажет на PHP script, который согласовывает соединение между QuickBooks и PHP. Все, что вам нужно сделать в этом примере script, - это замена этой переменной:

  • $dsn (укажите его в свою собственную базу данных)

Для каждой новой функциональности, которую вы хотите добавить, вы в конце концов напишите новую функцию запроса и ответа, как описано в QuickBooks Web Connector + PHP docs.

Ваш код будет выглядеть примерно так:

function _quickbooks_customer_add_request($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale)
{
        // You'd probably do some database access here to pull the record with 
        //        ID = $ID from your database and build a request to add that particular 
        //        customer to QuickBooks. 
        //        
        // So, when you implement this for your business, you'd probably do 
        //        something like this...: 

        /*
        // Fetch your customer record from your database
        $record = mysql_fetch_array(mysql_query("SELECT * FROM your_customer_table WHERE your_customer_ID_field = " . (int) $ID));

        // Create and return a qbXML request
        $qbxml = '<?xml version="1.0" encoding="utf-8"?>
                <?qbxml version="2.0"?>
                <QBXML>
                        <QBXMLMsgsRq onError="stopOnError">
                                <CustomerAddRq requestID="' . $requestID . '">
                                        <CustomerAdd>
                                                <Name>' . $record['your_customer_name_field'] . '</Name>
                                                <CompanyName>' . $record['your_customer_company_field'] . '</CompanyName>

                                                ... lots of other customer related fields ...

                                        </CustomerAdd>
                                </CustomerAddRq>
                        </QBXMLMsgsRq>
                </QBXML>';

        return $qbxml;
        */

        // But we're just testing, so we'll just use a static test request:

        $xml = '<?xml version="1.0" encoding="utf-8"?>
                <?qbxml version="2.0"?>
                <QBXML>
                        <QBXMLMsgsRq onError="stopOnError">
                                <CustomerAddRq requestID="' . $requestID . '">
                                        <CustomerAdd>
                                                <Name>ConsoliBYTE, LLC (' . mt_rand() . ')</Name>
                                                <CompanyName>ConsoliBYTE, LLC</CompanyName>
                                                <FirstName>Keith</FirstName>
                                                <LastName>Palmer</LastName>
                                                <BillAddress>
                                                        <Addr1>ConsoliBYTE, LLC</Addr1>
                                                        <Addr2>134 Stonemill Road</Addr2>
                                                        <City>Mansfield</City>
                                                        <State>CT</State>
                                                        <PostalCode>06268</PostalCode>
                                                        <Country>United States</Country>
                                                </BillAddress>
                                                <Phone>860-634-1602</Phone>
                                                <AltPhone>860-429-0021</AltPhone>
                                                <Fax>860-429-5183</Fax>
                                                <Email>[email protected]</Email>
                                                <Contact>Keith Palmer</Contact>
                                        </CustomerAdd>
                                </CustomerAddRq>
                        </QBXMLMsgsRq>
                </QBXML>';

        return $xml;
}

Дополнительную ссылку qbXML можно найти с помощью QuickBooks OSR.

Мы также предоставляем wiki с примерами примеров qbXML, которые вы можете использовать.

Ответ 2

В SDK используйте example_ipp_ids_6.php для добавления клиентов.

Вот ссылка на полный код GitHub:

И руководство по быстрому запуску:

example_ipp_ids_6.php

 <?php

// Turn on some error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: text/plain');

/**
 * Require the QuickBooks library
 */
require_once dirname(__FILE__) . '/../QuickBooks.php';

/**
 * Require some IPP/OAuth configuration data
 */
require_once dirname(__FILE__) . '/example_ipp_config.php';


// Set up the IPP instance
$IPP = new QuickBooks_IPP($dsn);

// Set up our IntuitAnywhere instance
$IntuitAnywhere = new QuickBooks_IPP_IntuitAnywhere($dsn, $encryption_key, $oauth_consumer_key, $oauth_consumer_secret);

// Get our OAuth credentials from the database
$creds = $IntuitAnywhere->load($the_username, $the_tenant);

// Tell the framework to load some data from the OAuth store
$IPP->authMode(
    QuickBooks_IPP::AUTHMODE_OAUTH, 
    $the_username, 
    $creds);

// Print the credentials we're using
//print_r($creds);

// This is our current realm
$realm = $creds['qb_realm'];

// Load the OAuth information from the database
if ($Context = $IPP->context())
{
    // Set the DBID
    $IPP->dbid($Context, 'something');

    // Set the IPP flavor
    $IPP->flavor($creds['qb_flavor']);

    // Get the base URL if it QBO
    if ($creds['qb_flavor'] == QuickBooks_IPP_IDS::FLAVOR_ONLINE)
    {
        $IPP->baseURL($IPP->getBaseURL($Context, $realm));
    }

    print('Base URL is [' . $IPP->baseURL() . ']' . "\n\n");

    $CustomerService = new QuickBooks_IPP_Service_Customer();

    $Customer = new QuickBooks_IPP_Object_Customer();
    $Customer->setName('Willy Wonka #' . mt_rand(0, 1000));
    $Customer->setGivenName('Willy');
    $Customer->setFamilyName('Wonka');

    $resp = $CustomerService->add($Context, $realm, $Customer);

    print_r($Customer);
    print('New customer is [' . $resp . ']' . "\n\n");

    print("\n\n\n\n");
    print('Request [' . $IPP->lastRequest() . ']');
    print("\n\n\n\n");
    print('Response [' . $IPP->lastResponse() . ']');
    print("\n\n\n\n");
}
else
{
    die('Unable to load a context...?');
}

Настройте свои ключи и имя пользователя в example_ipp_config.php

<?php

/**
 * Intuit Partner Platform configuration variables
 * 
 * See the scripts that use these variables for more details. 
 * 
 * @package QuickBooks
 * @subpackage Documentation
 */

// Your OAuth token (Intuit will give you this when you register an Intuit Anywhere app)
$token = 'c640731cb411db4132b8475b4198a7efae08';

// Your OAuth consumer key and secret (Intuit will give you both of these when you register an Intuit app)
// 
// IMPORTANT:
//  To pass your tech review with Intuit, you'll have to AES encrypt these and 
//  store them somewhere safe. 
// 
// The OAuth request/access tokens will be encrypted and stored for you by the 
//  PHP DevKit IntuitAnywhere classes automatically. 
$oauth_consumer_key = 'qyprdzUiOLX60UK4cMwYhg1QVGfOGT';
$oauth_consumer_secret = '32mIB75pqqPreOADcxRvryC0fBduJhnRr52JfUdf';

// This is the URL of your OAuth auth handler page
$this_url = 'http://localhost/quick/docs/example_ipp_oauth.php';

// This is the URL to forward the user to after they have connected to IPP/IDS via OAuth
$that_url = 'http://localhost/quick/docs/example_ipp_ids_6.php';

// This is a database connection string that will be used to store the OAuth credentials 
// $dsn = 'pgsql://username:[email protected]/database';
// $dsn = 'mysql://username:[email protected]/database';
$dsn = 'mysql://root:@localhost/quickbooks';        

// You should set this to an encryption key specific to your app
$encryption_key = 'abcd1234';

// The user that logged in
$the_username = '[email protected]';

// The tenant that user is accessing within your own app
$the_tenant = 12345;

// Initialize the database tables for storing OAuth information
if (!QuickBooks_Utilities::initialized($dsn))
{
    // Initialize creates the neccessary database schema for queueing up requests and logging
    QuickBooks_Utilities::initialize($dsn);
}