How to parse the result from getOrders

Hello,

below is an example of list locations from the dev site and from my live site. I am using the php sdk and trying to figure out how to get a JSON response like the site shows. I feel like this should obvious.

When running queries on the site they return normal json response

{
  "locations": [
    {
      "id": "L12H47G7MB9CV",
      "name": "Default Test Account",
      "address": {
        "address_line_1": "1600 Pennsylvania Ave NW",
        "locality": "Washington",
        "administrative_district_level_1": "DC",
        "postal_code": "20500",
        "country": "US"
      },
      "timezone": "UTC",
      "capabilities": [
        "CREDIT_CARD_PROCESSING",
        "AUTOMATIC_TRANSFERS"
      ],
      "status": "ACTIVE",
      "created_at": "2024-09-09T00:39:56.529Z",
      "merchant_id": "ML2FMC6D5MT66",
      "country": "US",
      "language_code": "en-US",
      "currency": "USD",
      "business_name": "Default Test Account",
      "type": "PHYSICAL",
      "business_hours": {},
      "mcc": "7299"
    }
  ]
}

but when running them via the SDK getting a totally different reponse

object(Square\Models\ListLocationsResponse)#176 (2) {
  ["errors":"Square\Models\ListLocationsResponse":private]=>
  NULL
  ["locations":"Square\Models\ListLocationsResponse":private]=>
  array(1) {
    [0]=>
    object(Square\Models\Location)#179 (27) {
      ["id":"Square\Models\Location":private]=>
      string(13) "xxxxxx"
      ["name":"Square\Models\Location":private]=>
      array(1) {
        ["value"]=>
        string(25) "xxxxx"
      }
      ["address":"Square\Models\Location":private]=>
      object(Square\Models\Address)#245 (14) {
        ["addressLine1":"Square\Models\Address":private]=>
        array(1) {
          ["value"]=>
          string(13) 'xxxxx"
        }
        ["addressLine2":"Square\Models\Address":private]=>

Thanks for any help
Don

The PHP SDK for Square returns objects, and you can easily convert these objects to JSON using PHP’s built-in functions. Here’s a step-by-step guide on how to achieve this:

Step 1: Fetch Locations Using the PHP SDK

First, ensure you have the PHP SDK set up and you are correctly fetching the locations:

require 'vendor/autoload.php';

use Square\SquareClient;
use Square\Exceptions\ApiException;
use Square\Environment;

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

$locationsApi = $client->getLocationsApi();

try {
    $response = $locationsApi->listLocations();
    if ($response->isSuccess()) {
        $locations = $response->getResult()->getLocations();
    } else {
        $errors = $response->getErrors();
        // Handle errors
    }
} catch (ApiException $e) {
    // Handle API exceptions
}

Step 2: Convert Locations to JSON

Once you have the locations, you can convert them to JSON. The SDK objects can be converted to arrays using the jsonSerialize method, and then you can use json_encode to convert the array to a JSON string.

Here’s an example of how to do this:

if (isset($locations)) {
    $locationsArray = array_map(function ($location) {
        return $location->jsonSerialize();
    }, $locations);

    $jsonResponse = json_encode(['locations' => $locationsArray], JSON_PRETTY_PRINT);
    echo $jsonResponse;
}

Full Example

Combining everything, here is the full example:

require 'vendor/autoload.php';

use Square\SquareClient;
use Square\Exceptions\ApiException;
use Square\Environment;

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

$locationsApi = $client->getLocationsApi();

try {
    $response = $locationsApi->listLocations();
    if ($response->isSuccess()) {
        $locations = $response->getResult()->getLocations();

        // Convert locations to JSON
        $locationsArray = array_map(function ($location) {
            return $location->jsonSerialize();
        }, $locations);

        $jsonResponse = json_encode(['locations' => $locationsArray], JSON_PRETTY_PRINT);
        echo $jsonResponse;
    } else {
        $errors = $response->getErrors();
        // Handle errors
        echo "Errors: " . json_encode($errors, JSON_PRETTY_PRINT);
    }
} catch (ApiException $e) {
    // Handle API exceptions
    echo "Exception: " . $e->getMessage();
}

:slightly_smiling_face:

Thanks for the quick response! It helped me get to where I was going. Is there a better way to access the individual properties of the returned class with php that I don’t know of?

Thanks
Don

There are indeed ways to make this process more straightforward. The Square PHP SDK uses getter methods to access the properties of the returned objects.

Each class in the Square PHP SDK has getter methods for its properties. These methods follow a standard naming convention, typically starting with get followed by the property name in camel case.

Example: Accessing Properties of a Location Object

Here’s how you can access individual properties of a Location object returned by the listLocations method:

require 'vendor/autoload.php';

use Square\SquareClient;
use Square\Exceptions\ApiException;
use Square\Environment;

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

$locationsApi = $client->getLocationsApi();

try {
    $response = $locationsApi->listLocations();
    if ($response->isSuccess()) {
        $locations = $response->getResult()->getLocations();

        foreach ($locations as $location) {
            // Accessing individual properties using getter methods
            $locationId = $location->getId();
            $locationName = $location->getName();
            $locationAddress = $location->getAddress();
            $locationTimezone = $location->getTimezone();
            $locationCapabilities = $location->getCapabilities();
            $locationStatus = $location->getStatus();
            $locationCreatedAt = $location->getCreatedAt();
            $locationMerchantId = $location->getMerchantId();
            $locationCountry = $location->getCountry();
            $locationLanguageCode = $location->getLanguageCode();
            $locationCurrency = $location->getCurrency();
            $locationBusinessName = $location->getBusinessName();
            $locationType = $location->getType();
            $locationBusinessHours = $location->getBusinessHours();
            $locationMcc = $location->getMcc();

            // Print the properties
            echo "Location ID: $locationId\n";
            echo "Name: $locationName\n";
            echo "Address: " . json_encode($locationAddress->jsonSerialize(), JSON_PRETTY_PRINT) . "\n";
            echo "Timezone: $locationTimezone\n";
            echo "Capabilities: " . json_encode($locationCapabilities, JSON_PRETTY_PRINT) . "\n";
            echo "Status: $locationStatus\n";
            echo "Created At: $locationCreatedAt\n";
            echo "Merchant ID: $locationMerchantId\n";
            echo "Country: $locationCountry\n";
            echo "Language Code: $locationLanguageCode\n";
            echo "Currency: $locationCurrency\n";
            echo "Business Name: $locationBusinessName\n";
            echo "Type: $locationType\n";
            echo "Business Hours: " . json_encode($locationBusinessHours->jsonSerialize(), JSON_PRETTY_PRINT) . "\n";
            echo "MCC: $locationMcc\n";
        }
    } else {
        $errors = $response->getErrors();
        // Handle errors
        echo "Errors: " . json_encode($errors, JSON_PRETTY_PRINT);
    }
} catch (ApiException $e) {
    // Handle API exceptions
    echo "Exception: " . $e->getMessage();
}
  1. Getter Methods: Each property of the Location object has a corresponding getter method. For example, the id property can be accessed using getId(), and the name property can be accessed using getName().
  2. Address Property: The address property is itself an object (of type Square\Models\Address), so you can use its own getter methods to access its properties.
  3. Capabilities Property: The capabilities property is an array, so you can directly access and manipulate it as needed.

If you prefer a more dynamic way to access properties, you can use PHP’s magic methods like __get and __set. However, this approach is not recommended for accessing SDK objects as it might bypass some of the validation and encapsulation provided by the SDK.

Using the getter methods provided by the Square PHP SDK is the recommended way to access individual properties of the returned objects. This approach ensures that you are accessing the properties correctly and leveraging the SDK’s built-in methods. :slightly_smiling_face:

Thanks so much for the quick response again and for your help.

Thanks
Don