phphtmlmysqlsquare-connectsquare

How to use Square API to get the items sold data in a business day from the Order Object and insert it into MySQL database


So right now I am trying to get the different items sold per day from the Order API from Square. However, I do not know how to get the name of the item sold, the catalog_id of it and the quantity sold into a three different array for me to insert it into MySQL db. I have replaced my accessToken and locationId as 'XXXX'.

<?php
require_once(__DIR__ . '/vendor/autoload.php');

use Square\SquareClient;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
use Square\Orders;

$client = new SquareClient([
    'accessToken' => 'XXXX',
    'environment' => Environment::PRODUCTION,
]);

SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('XXXX');

$body = new Square\Models\SearchOrdersRequest;
$ordersApi = $client->getOrdersApi();
$apiResponse = $ordersApi->searchOrders($body);

$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-04-10T00:00:00+08:00');
$created_at->setEndAt('2021-04-10T23:59:59+08:00'); 

$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);

$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);

$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');

$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);

$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(500);
$body->setReturnEntries(false);

$api_response = $client->getOrdersApi()->searchOrders($body);

if ($api_response->isSuccess()) {
    $result = $api_response->getResult();
    //print_r($result);
    var_export($result);
} else {
    $errors = $api_response->getErrors();
}

?>

This is the output of the above code :

Square\Models\SearchOrdersResponse::__set_state(array( 'orderEntries' => NULL, 'orders' => array ( 0 => Square\Models\Order::__set_state(array( 'id' => 'rOWGPV4K7Zoctgv1qRNPcH5eV', 'locationId' => 'XXXX', 'referenceId' => NULL, 'source' => NULL, 'customerId' => NULL, 'lineItems' => array ( 0 => Square\Models\OrderLineItem::__set_state(array( 'uid' => '0bb50124-0732-4382-9733-40dea49ae8b5', 'name' => 'Rojak $3.50 罗惹', 'quantity' => '2', 'quantityUnit' => NULL, 'note' => NULL, 'catalogObjectId' => 'LHXXXX4VXLMQ3SHRUBWN32QA', 'variationName' => 'Regular', 'metadata' => NULL, 'modifiers' => NULL, 'appliedTaxes' => NULL, 'appliedDiscounts' => NULL, 'basePriceMoney' => Square\Models\Money::__set_state(array( 'amount' => 350, 'currency' => 'SGD', )), 'variationTotalPriceMoney' => Square\Models\Money::__set_state(array( 'amount' => 700, 'currency' => 'SGD', )), 'grossSalesMoney' => Square\Models\Money::__set_state(array( 'amount' => 700, 'currency' => 'SGD', )), 'totalTaxMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'totalDiscountMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'totalMoney' => Square\Models\Money::__set_state(array( 'amount' => 700, 'currency' => 'SGD', )), 'pricingBlocklists' => NULL, )), ), 'taxes' => NULL, 'discounts' => NULL, 'serviceCharges' => NULL, 'fulfillments' => NULL, 'returns' => NULL, 'returnAmounts' => Square\Models\OrderMoneyAmounts::__set_state(array( 'totalMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'taxMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'discountMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'tipMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'serviceChargeMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), )), 'netAmounts' => Square\Models\OrderMoneyAmounts::__set_state(array( 'totalMoney' => Square\Models\Money::__set_state(array( 'amount' => 700, 'currency' => 'SGD', )), 'taxMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'discountMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'tipMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'serviceChargeMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), )), 'roundingAdjustment' => NULL, 'tenders' => array ( 0 => Square\Models\Tender::__set_state(array( 'id' => '9S81AplaU3qfu65tljyTvqiNvaB', 'locationId' => 'XXXX', 'transactionId' => 'rOWGPV4K7Zoctgv1qRNPcH5eV', 'createdAt' => '2021-04-10T10:43:42Z', 'note' => NULL, 'amountMoney' => Square\Models\Money::__set_state(array( 'amount' => 700, 'currency' => 'SGD', )), 'tipMoney' => NULL, 'processingFeeMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'customerId' => NULL, 'type' => 'CASH', 'cardDetails' => NULL, 'cashDetails' => Square\Models\TenderCashDetails::__set_state(array( 'buyerTenderedMoney' => Square\Models\Money::__set_state(array( 'amount' => 800, 'currency' => 'SGD', )), 'changeBackMoney' => Square\Models\Money::__set_state(array( 'amount' => 100, 'currency' => 'SGD', )), )), 'additionalRecipients' => NULL, 'paymentId' => NULL, )), ), 'refunds' => NULL, 'metadata' => NULL, 'createdAt' => '2021-04-10T10:43:42Z', 'updatedAt' => '2021-04-10T10:43:42Z', 'closedAt' => '2021-04-10T10:43:42Z', 'state' => 'COMPLETED', 'version' => NULL, 'totalMoney' => Square\Models\Money::__set_state(array( 'amount' => 700, 'currency' => 'SGD', )), 'totalTaxMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'totalDiscountMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'totalTipMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'totalServiceChargeMoney' => Square\Models\Money::__set_state(array( 'amount' => 0, 'currency' => 'SGD', )), 'pricingOptions' => NULL, 'rewards' => NULL, )), ), 'cursor' => 'QYBs4K60vfdftVQa4hjeBXqmIGHFjKaXIEWHdD2qKrscX8LUwY95QN4abLC1A8ARzG081WckPLHa6jmgWWwRpS6u8eyXZiWcUGLYUBiiP2RPlDeuvo2qq19DJOhKsKWbXirv4neORr5ahFJeeTnvpxfBkTRr3J8MU6yI3it2cQyfPI34dOcm9Yh0TsdZk6gEdkNUs2LY9jOLVpdJ6yPZd2uFZ9S8SrQ08twBo7PT9p5Rxq81dlw8PZbFrbONhr9xQi1uxY9vXMsSllstKbmOcw0DXT7NRSimkrY0wvF5uAFRK352tSteU0enswtljUGgDxnZMNwUFxiMzewagb6iKvRaqPJ4ymu4lYMLvj6NMItEY9HJ1yjKlkXolYIksIvAFYG7Qdc3m', 'errors' => NULL, ))


Solution

  • <html>
    <?php
    require_once(__DIR__ . '/vendor/autoload.php');
    
    use Square\SquareClient;
    use Square\Exceptions\ApiException;
    use Square\Http\ApiResponse;
    use Square\Models\ListLocationsResponse;
    use Square\Environment;
    use Square\Orders;
    
    $client = new SquareClient([
        'accessToken' => 'XXXX',
        'environment' => Environment::PRODUCTION,
    ]);
    
    SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('XXXX');
    
    $location_ids = ['XXXX'];
    $created_at = new \Square\Models\TimeRange();
    $created_at->setStartAt('2021-04-14T00:00:00+08:00');
    $created_at->setEndAt('2021-04-14T23:59:59+08:00'); 
    
    $date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
    $date_time_filter->setCreatedAt($created_at);
    
    $filter = new \Square\Models\SearchOrdersFilter();
    $filter->setDateTimeFilter($date_time_filter);
    
    $sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
    $sort->setSortOrder('DESC');
    
    $query = new \Square\Models\SearchOrdersQuery();
    $query->setFilter($filter);
    $query->setSort($sort);
    
    $body = new \Square\Models\SearchOrdersRequest();
    $body->setLocationIds($location_ids);
    $body->setQuery($query);
    $body->setLimit(500);
    $body->setReturnEntries(false);
    
    $api_response = $client->getOrdersApi()->searchOrders($body);
    
    if ($api_response->isSuccess()) {
        $result = $api_response->getResult();
        $orders = $result->getOrders();
        
        //INSERT INTO DB
           //include db connect class
           require_once __DIR__ . '/db_connect.php';
           // connecting to db
           $myConnection= new DB_CONNECT();
           $myConnection->connect();
           
           $sql="INSERT INTO sale_item(order_id, item_name, item_quantity) VALUES";
        
        foreach($orders as $x => $val) {
        $lineItems = $result->getOrders()[$x]->getLineItems();
        $orderid = $result->getOrders()[$x]->getId();
        
        foreach($lineItems as $q => $val2){
            //$lineItemsID = $lineItems[$q]->getUid();
            $itemName = $lineItems[$q]->getName();
            $itemQty = $lineItems[$q]->getQuantity();
            
            $sql .="('".$orderid."', '".$itemName."', '".$itemQty."'),";
        }   
        }
        
        $sql= rtrim( $sql, ',');
        $result =mysqli_query($myConnection->myconn, "$sql");
    
        // check if row inserted or not
        if ($result) {
         // successfully inserted into database
          echo "Product successfully created.";       
          }  
        else {
          // failed to insert row
          echo "Oops! An error occurred.";
        }
        
    } else {
        $errors = $api_response->getErrors();
    }
    
    
    
    ?>
    </html>