Google Cloud Retail V2 Client - Class ProductServiceClient (1.6.3)

Reference documentation and code samples for the Google Cloud Retail V2 Client class ProductServiceClient.

Service Description: Service for ingesting Product information of the customer's website.

This class provides the ability to make remote calls to the backing service through method calls that map to API methods.

Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parseName method to extract the individual identifiers contained within formatted names that are returned by the API.

Namespace

Google \ Cloud \ Retail \ V2 \ Client

Methods

__construct

Constructor.

Parameters
Name Description
options array

Optional. Options for configuring the service API wrapper.

↳ apiEndpoint string

The address of the API remote host. May optionally include the port, formatted as "

↳ credentials string|array|FetchAuthTokenInterface|CredentialsWrapper

The credentials to be used by the client to authorize API calls. This option accepts either a path to a credentials file, or a decoded credentials file as a PHP array. Advanced usage: In addition, this option can also accept a pre-constructed Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.

↳ credentialsConfig array

Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .

↳ disableRetries bool

Determines whether or not retries defined by the client configuration should be disabled. Defaults to false.

↳ clientConfig string|array

Client method configuration, including retry settings. This option can be either a path to a JSON file, or a PHP array containing the decoded JSON data. By default this settings points to the default client config file, which is provided in the resources folder.

↳ transport string|TransportInterface

The transport used for executing network requests. May be either the string rest or grpc. Defaults to grpc if gRPC support is detected on the system. Advanced usage: Additionally, it is possible to pass in an already instantiated Google\ApiCore\Transport\TransportInterface object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.

↳ transportConfig array

Configuration options that will be used to construct the transport. Options for each supported transport type should be passed in a key for that transport. For example: $transportConfig = [ 'grpc' => [...], 'rest' => [...], ]; See the Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.

↳ clientCertSource callable

A callable which returns the client cert as a string. This can be used to provide a certificate and private key to the transport layer for mTLS.

addFulfillmentPlaces

It is recommended to use the ProductService.AddLocalInventories method instead of ProductService.AddFulfillmentPlaces.

ProductService.AddLocalInventories achieves the same results but provides more fine-grained control over ingesting local inventory data.

Incrementally adds place IDs to Product.fulfillment_info.place_ids.

This process is asynchronous and does not require the Product to exist before updating fulfillment information. If the request is valid, the update will be enqueued and processed downstream. As a consequence, when a response is returned, the added place IDs are not immediately manifested in the Product queried by ProductService.GetProduct or ProductService.ListProducts.

The returned Operations will be obsolete after 1 day, and GetOperation API will return NOT_FOUND afterwards.

If conflicting updates are issued, the Operations associated with the stale updates will not be marked as done until being obsolete.

The async variant is Google\Cloud\Retail\V2\Client\ProductServiceClient::addFulfillmentPlacesAsync() .

Parameters
Name Description
request Google\Cloud\Retail\V2\AddFulfillmentPlacesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\AddFulfillmentPlacesRequest;
use Google\Cloud\Retail\V2\AddFulfillmentPlacesResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Rpc\Status;

/**
 * @param string $formattedProduct Full resource name of [Product][google.cloud.retail.v2.Product],
 *                                 such as
 *                                 `projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
 *
 *                                 If the caller does not have permission to access the
 *                                 [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                                 exists, a PERMISSION_DENIED error is returned. Please see
 *                                 {@see ProductServiceClient::productName()} for help formatting this field.
 * @param string $type             The fulfillment type, including commonly used types (such as
 *                                 pickup in store and same day delivery), and custom types.
 *
 *                                 Supported values:
 *
 *                                 * "pickup-in-store"
 *                                 * "ship-to-store"
 *                                 * "same-day-delivery"
 *                                 * "next-day-delivery"
 *                                 * "custom-type-1"
 *                                 * "custom-type-2"
 *                                 * "custom-type-3"
 *                                 * "custom-type-4"
 *                                 * "custom-type-5"
 *
 *                                 If this field is set to an invalid value other than these, an
 *                                 INVALID_ARGUMENT error is returned.
 *
 *                                 This field directly corresponds to
 *                                 [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type].
 * @param string $placeIdsElement  The IDs for this
 *                                 [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], such as
 *                                 the store IDs for "pickup-in-store" or the region IDs for
 *                                 "same-day-delivery" to be added for this
 *                                 [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. Duplicate
 *                                 IDs will be automatically ignored.
 *
 *                                 At least 1 value is required, and a maximum of 2000 values are allowed.
 *                                 Each value must be a string with a length limit of 10 characters, matching
 *                                 the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an
 *                                 INVALID_ARGUMENT error is returned.
 *
 *                                 If the total number of place IDs exceeds 2000 for this
 *                                 [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] after
 *                                 adding, then the update will be rejected.
 */
function add_fulfillment_places_sample(
    string $formattedProduct,
    string $type,
    string $placeIdsElement
): void {
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $placeIds = [$placeIdsElement,];
    $request = (new AddFulfillmentPlacesRequest())
        ->setProduct($formattedProduct)
        ->setType($type)
        ->setPlaceIds($placeIds);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $productServiceClient->addFulfillmentPlaces($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var AddFulfillmentPlacesResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedProduct = ProductServiceClient::productName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]',
        '[PRODUCT]'
    );
    $type = '[TYPE]';
    $placeIdsElement = '[PLACE_IDS]';

    add_fulfillment_places_sample($formattedProduct, $type, $placeIdsElement);
}

addLocalInventories

Updates local inventory information for a Product at a list of places, while respecting the last update timestamps of each inventory field.

This process is asynchronous and does not require the Product to exist before updating inventory information. If the request is valid, the update will be enqueued and processed downstream. As a consequence, when a response is returned, updates are not immediately manifested in the Product queried by ProductService.GetProduct or ProductService.ListProducts.

Local inventory information can only be modified using this method. ProductService.CreateProduct and ProductService.UpdateProduct has no effect on local inventories.

The returned Operations will be obsolete after 1 day, and GetOperation API will return NOT_FOUND afterwards.

If conflicting updates are issued, the Operations associated with the stale updates will not be marked as done until being obsolete.

The async variant is Google\Cloud\Retail\V2\Client\ProductServiceClient::addLocalInventoriesAsync() .

Parameters
Name Description
request Google\Cloud\Retail\V2\AddLocalInventoriesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\AddLocalInventoriesRequest;
use Google\Cloud\Retail\V2\AddLocalInventoriesResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\LocalInventory;
use Google\Rpc\Status;

/**
 * @param string $formattedProduct Full resource name of [Product][google.cloud.retail.v2.Product],
 *                                 such as
 *                                 `projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
 *
 *                                 If the caller does not have permission to access the
 *                                 [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                                 exists, a PERMISSION_DENIED error is returned. Please see
 *                                 {@see ProductServiceClient::productName()} for help formatting this field.
 */
function add_local_inventories_sample(string $formattedProduct): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $localInventories = [new LocalInventory()];
    $request = (new AddLocalInventoriesRequest())
        ->setProduct($formattedProduct)
        ->setLocalInventories($localInventories);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $productServiceClient->addLocalInventories($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var AddLocalInventoriesResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedProduct = ProductServiceClient::productName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]',
        '[PRODUCT]'
    );

    add_local_inventories_sample($formattedProduct);
}

createProduct

Parameters
Name Description
request Google\Cloud\Retail\V2\CreateProductRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\Cloud\Retail\V2\Product
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\CreateProductRequest;
use Google\Cloud\Retail\V2\Product;

/**
 * @param string $formattedParent The parent catalog resource name, such as
 *                                `projects/*/locations/global/catalogs/default_catalog/branches/default_branch`. Please see
 *                                {@see ProductServiceClient::branchName()} for help formatting this field.
 * @param string $productTitle    Product title.
 *
 *                                This field must be a UTF-8 encoded string with a length limit of 1,000
 *                                characters. Otherwise, an INVALID_ARGUMENT error is returned.
 *
 *                                Corresponding properties: Google Merchant Center property
 *                                [title](https://support.google.com/merchants/answer/6324415). Schema.org
 *                                property [Product.name](https://schema.org/name).
 * @param string $productId       The ID to use for the [Product][google.cloud.retail.v2.Product],
 *                                which will become the final component of the
 *                                [Product.name][google.cloud.retail.v2.Product.name].
 *
 *                                If the caller does not have permission to create the
 *                                [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                                exists, a PERMISSION_DENIED error is returned.
 *
 *                                This field must be unique among all
 *                                [Product][google.cloud.retail.v2.Product]s with the same
 *                                [parent][google.cloud.retail.v2.CreateProductRequest.parent]. Otherwise, an
 *                                ALREADY_EXISTS error is returned.
 *
 *                                This field must be a UTF-8 encoded string with a length limit of 128
 *                                characters. Otherwise, an INVALID_ARGUMENT error is returned.
 */
function create_product_sample(
    string $formattedParent,
    string $productTitle,
    string $productId
): void {
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $product = (new Product())
        ->setTitle($productTitle);
    $request = (new CreateProductRequest())
        ->setParent($formattedParent)
        ->setProduct($product)
        ->setProductId($productId);

    // Call the API and handle any network failures.
    try {
        /** @var Product $response */
        $response = $productServiceClient->createProduct($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = ProductServiceClient::branchName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]'
    );
    $productTitle = '[TITLE]';
    $productId = '[PRODUCT_ID]';

    create_product_sample($formattedParent, $productTitle, $productId);
}

deleteProduct

Parameters
Name Description
request Google\Cloud\Retail\V2\DeleteProductRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\DeleteProductRequest;

/**
 * @param string $formattedName Full resource name of [Product][google.cloud.retail.v2.Product],
 *                              such as
 *                              `projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
 *
 *                              If the caller does not have permission to delete the
 *                              [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                              exists, a PERMISSION_DENIED error is returned.
 *
 *                              If the [Product][google.cloud.retail.v2.Product] to delete does not exist,
 *                              a NOT_FOUND error is returned.
 *
 *                              The [Product][google.cloud.retail.v2.Product] to delete can neither be a
 *                              [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]
 *                              [Product][google.cloud.retail.v2.Product] member nor a
 *                              [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY]
 *                              [Product][google.cloud.retail.v2.Product] with more than one
 *                              [variants][google.cloud.retail.v2.Product.Type.VARIANT]. Otherwise, an
 *                              INVALID_ARGUMENT error is returned.
 *
 *                              All inventory information for the named
 *                              [Product][google.cloud.retail.v2.Product] will be deleted. Please see
 *                              {@see ProductServiceClient::productName()} for help formatting this field.
 */
function delete_product_sample(string $formattedName): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $request = (new DeleteProductRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        $productServiceClient->deleteProduct($request);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = ProductServiceClient::productName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]',
        '[PRODUCT]'
    );

    delete_product_sample($formattedName);
}

getProduct

Parameters
Name Description
request Google\Cloud\Retail\V2\GetProductRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\Cloud\Retail\V2\Product
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\GetProductRequest;
use Google\Cloud\Retail\V2\Product;

/**
 * @param string $formattedName Full resource name of [Product][google.cloud.retail.v2.Product],
 *                              such as
 *                              `projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
 *
 *                              If the caller does not have permission to access the
 *                              [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                              exists, a PERMISSION_DENIED error is returned.
 *
 *                              If the requested [Product][google.cloud.retail.v2.Product] does not exist,
 *                              a NOT_FOUND error is returned. Please see
 *                              {@see ProductServiceClient::productName()} for help formatting this field.
 */
function get_product_sample(string $formattedName): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $request = (new GetProductRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        /** @var Product $response */
        $response = $productServiceClient->getProduct($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = ProductServiceClient::productName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]',
        '[PRODUCT]'
    );

    get_product_sample($formattedName);
}

importProducts

Bulk import of multiple Products.

Request processing may be synchronous. Non-existing items are created.

Note that it is possible for a subset of the Products to be successfully updated.

The async variant is Google\Cloud\Retail\V2\Client\ProductServiceClient::importProductsAsync() .

Parameters
Name Description
request Google\Cloud\Retail\V2\ImportProductsRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\ImportProductsRequest;
use Google\Cloud\Retail\V2\ImportProductsResponse;
use Google\Cloud\Retail\V2\ProductInputConfig;
use Google\Rpc\Status;

/**
 * @param string $formattedParent Required.
 *                                `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`
 *
 *                                If no updateMask is specified, requires products.create permission.
 *                                If updateMask is specified, requires products.update permission. Please see
 *                                {@see ProductServiceClient::branchName()} for help formatting this field.
 */
function import_products_sample(string $formattedParent): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $inputConfig = new ProductInputConfig();
    $request = (new ImportProductsRequest())
        ->setParent($formattedParent)
        ->setInputConfig($inputConfig);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $productServiceClient->importProducts($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var ImportProductsResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = ProductServiceClient::branchName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]'
    );

    import_products_sample($formattedParent);
}

listProducts

Parameters
Name Description
request Google\Cloud\Retail\V2\ListProductsRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\ListProductsRequest;
use Google\Cloud\Retail\V2\Product;

/**
 * @param string $formattedParent The parent branch resource name, such as
 *                                `projects/*/locations/global/catalogs/default_catalog/branches/0`. Use
 *                                `default_branch` as the branch ID, to list products under the default
 *                                branch.
 *
 *                                If the caller does not have permission to list
 *                                [Product][google.cloud.retail.v2.Product]s under this branch, regardless of
 *                                whether or not this branch exists, a PERMISSION_DENIED error is returned. Please see
 *                                {@see ProductServiceClient::branchName()} for help formatting this field.
 */
function list_products_sample(string $formattedParent): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $request = (new ListProductsRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $productServiceClient->listProducts($request);

        /** @var Product $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = ProductServiceClient::branchName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]'
    );

    list_products_sample($formattedParent);
}

removeFulfillmentPlaces

It is recommended to use the ProductService.RemoveLocalInventories method instead of ProductService.RemoveFulfillmentPlaces.

ProductService.RemoveLocalInventories achieves the same results but provides more fine-grained control over ingesting local inventory data.

Incrementally removes place IDs from a Product.fulfillment_info.place_ids.

This process is asynchronous and does not require the Product to exist before updating fulfillment information. If the request is valid, the update will be enqueued and processed downstream. As a consequence, when a response is returned, the removed place IDs are not immediately manifested in the Product queried by ProductService.GetProduct or ProductService.ListProducts.

The returned Operations will be obsolete after 1 day, and GetOperation API will return NOT_FOUND afterwards.

If conflicting updates are issued, the Operations associated with the stale updates will not be marked as done until being obsolete.

The async variant is Google\Cloud\Retail\V2\Client\ProductServiceClient::removeFulfillmentPlacesAsync() .

Parameters
Name Description
request Google\Cloud\Retail\V2\RemoveFulfillmentPlacesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\RemoveFulfillmentPlacesRequest;
use Google\Cloud\Retail\V2\RemoveFulfillmentPlacesResponse;
use Google\Rpc\Status;

/**
 * @param string $formattedProduct Full resource name of [Product][google.cloud.retail.v2.Product],
 *                                 such as
 *                                 `projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
 *
 *                                 If the caller does not have permission to access the
 *                                 [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                                 exists, a PERMISSION_DENIED error is returned. Please see
 *                                 {@see ProductServiceClient::productName()} for help formatting this field.
 * @param string $type             The fulfillment type, including commonly used types (such as
 *                                 pickup in store and same day delivery), and custom types.
 *
 *                                 Supported values:
 *
 *                                 * "pickup-in-store"
 *                                 * "ship-to-store"
 *                                 * "same-day-delivery"
 *                                 * "next-day-delivery"
 *                                 * "custom-type-1"
 *                                 * "custom-type-2"
 *                                 * "custom-type-3"
 *                                 * "custom-type-4"
 *                                 * "custom-type-5"
 *
 *                                 If this field is set to an invalid value other than these, an
 *                                 INVALID_ARGUMENT error is returned.
 *
 *                                 This field directly corresponds to
 *                                 [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type].
 * @param string $placeIdsElement  The IDs for this
 *                                 [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], such as
 *                                 the store IDs for "pickup-in-store" or the region IDs for
 *                                 "same-day-delivery", to be removed for this
 *                                 [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type].
 *
 *                                 At least 1 value is required, and a maximum of 2000 values are allowed.
 *                                 Each value must be a string with a length limit of 10 characters, matching
 *                                 the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an
 *                                 INVALID_ARGUMENT error is returned.
 */
function remove_fulfillment_places_sample(
    string $formattedProduct,
    string $type,
    string $placeIdsElement
): void {
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $placeIds = [$placeIdsElement,];
    $request = (new RemoveFulfillmentPlacesRequest())
        ->setProduct($formattedProduct)
        ->setType($type)
        ->setPlaceIds($placeIds);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $productServiceClient->removeFulfillmentPlaces($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var RemoveFulfillmentPlacesResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedProduct = ProductServiceClient::productName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]',
        '[PRODUCT]'
    );
    $type = '[TYPE]';
    $placeIdsElement = '[PLACE_IDS]';

    remove_fulfillment_places_sample($formattedProduct, $type, $placeIdsElement);
}

removeLocalInventories

Remove local inventory information for a Product at a list of places at a removal timestamp.

This process is asynchronous. If the request is valid, the removal will be enqueued and processed downstream. As a consequence, when a response is returned, removals are not immediately manifested in the Product queried by ProductService.GetProduct or ProductService.ListProducts.

Local inventory information can only be removed using this method. ProductService.CreateProduct and ProductService.UpdateProduct has no effect on local inventories.

The returned Operations will be obsolete after 1 day, and GetOperation API will return NOT_FOUND afterwards.

If conflicting updates are issued, the Operations associated with the stale updates will not be marked as done until being obsolete.

The async variant is Google\Cloud\Retail\V2\Client\ProductServiceClient::removeLocalInventoriesAsync() .

Parameters
Name Description
request Google\Cloud\Retail\V2\RemoveLocalInventoriesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\RemoveLocalInventoriesRequest;
use Google\Cloud\Retail\V2\RemoveLocalInventoriesResponse;
use Google\Rpc\Status;

/**
 * @param string $formattedProduct Full resource name of [Product][google.cloud.retail.v2.Product],
 *                                 such as
 *                                 `projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
 *
 *                                 If the caller does not have permission to access the
 *                                 [Product][google.cloud.retail.v2.Product], regardless of whether or not it
 *                                 exists, a PERMISSION_DENIED error is returned. Please see
 *                                 {@see ProductServiceClient::productName()} for help formatting this field.
 * @param string $placeIdsElement  A list of place IDs to have their inventory deleted.
 *                                 At most 3000 place IDs are allowed per request.
 */
function remove_local_inventories_sample(string $formattedProduct, string $placeIdsElement): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $placeIds = [$placeIdsElement,];
    $request = (new RemoveLocalInventoriesRequest())
        ->setProduct($formattedProduct)
        ->setPlaceIds($placeIds);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $productServiceClient->removeLocalInventories($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var RemoveLocalInventoriesResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedProduct = ProductServiceClient::productName(
        '[PROJECT]',
        '[LOCATION]',
        '[CATALOG]',
        '[BRANCH]',
        '[PRODUCT]'
    );
    $placeIdsElement = '[PLACE_IDS]';

    remove_local_inventories_sample($formattedProduct, $placeIdsElement);
}

setInventory

Updates inventory information for a Product while respecting the last update timestamps of each inventory field.

This process is asynchronous and does not require the Product to exist before updating fulfillment information. If the request is valid, the update is enqueued and processed downstream. As a consequence, when a response is returned, updates are not immediately manifested in the Product queried by ProductService.GetProduct or ProductService.ListProducts.

When inventory is updated with ProductService.CreateProduct and ProductService.UpdateProduct, the specified inventory field value(s) overwrite any existing value(s) while ignoring the last update time for this field. Furthermore, the last update times for the specified inventory fields are overwritten by the times of the ProductService.CreateProduct or ProductService.UpdateProduct request.

If no inventory fields are set in CreateProductRequest.product, then any pre-existing inventory information for this product is used.

If no inventory fields are set in SetInventoryRequest.set_mask, then any existing inventory information is preserved.

Pre-existing inventory information can only be updated with ProductService.SetInventory, ProductService.AddFulfillmentPlaces, and ProductService.RemoveFulfillmentPlaces.

The returned Operations is obsolete after one day, and the GetOperation API returns NOT_FOUND afterwards.

If conflicting updates are issued, the Operations associated with the stale updates are not marked as done until they are obsolete.

The async variant is Google\Cloud\Retail\V2\Client\ProductServiceClient::setInventoryAsync() .

Parameters
Name Description
request Google\Cloud\Retail\V2\SetInventoryRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\Product;
use Google\Cloud\Retail\V2\SetInventoryRequest;
use Google\Cloud\Retail\V2\SetInventoryResponse;
use Google\Rpc\Status;

/**
 * @param string $inventoryTitle Product title.
 *
 *                               This field must be a UTF-8 encoded string with a length limit of 1,000
 *                               characters. Otherwise, an INVALID_ARGUMENT error is returned.
 *
 *                               Corresponding properties: Google Merchant Center property
 *                               [title](https://support.google.com/merchants/answer/6324415). Schema.org
 *                               property [Product.name](https://schema.org/name).
 */
function set_inventory_sample(string $inventoryTitle): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $inventory = (new Product())
        ->setTitle($inventoryTitle);
    $request = (new SetInventoryRequest())
        ->setInventory($inventory);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $productServiceClient->setInventory($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var SetInventoryResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $inventoryTitle = '[TITLE]';

    set_inventory_sample($inventoryTitle);
}

updateProduct

Parameters
Name Description
request Google\Cloud\Retail\V2\UpdateProductRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
Type Description
Google\Cloud\Retail\V2\Product
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Client\ProductServiceClient;
use Google\Cloud\Retail\V2\Product;
use Google\Cloud\Retail\V2\UpdateProductRequest;

/**
 * @param string $productTitle Product title.
 *
 *                             This field must be a UTF-8 encoded string with a length limit of 1,000
 *                             characters. Otherwise, an INVALID_ARGUMENT error is returned.
 *
 *                             Corresponding properties: Google Merchant Center property
 *                             [title](https://support.google.com/merchants/answer/6324415). Schema.org
 *                             property [Product.name](https://schema.org/name).
 */
function update_product_sample(string $productTitle): void
{
    // Create a client.
    $productServiceClient = new ProductServiceClient();

    // Prepare the request message.
    $product = (new Product())
        ->setTitle($productTitle);
    $request = (new UpdateProductRequest())
        ->setProduct($product);

    // Call the API and handle any network failures.
    try {
        /** @var Product $response */
        $response = $productServiceClient->updateProduct($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $productTitle = '[TITLE]';

    update_product_sample($productTitle);
}

addFulfillmentPlacesAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\AddFulfillmentPlacesRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

addLocalInventoriesAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\AddLocalInventoriesRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

createProductAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\CreateProductRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

deleteProductAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\DeleteProductRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

getProductAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\GetProductRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

importProductsAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\ImportProductsRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

listProductsAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\ListProductsRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

removeFulfillmentPlacesAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\RemoveFulfillmentPlacesRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

removeLocalInventoriesAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\RemoveLocalInventoriesRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

setInventoryAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\SetInventoryRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

updateProductAsync

Parameters
Name Description
request Google\Cloud\Retail\V2\UpdateProductRequest
optionalArgs = [] array
Returns
Type Description
GuzzleHttp\Promise\PromiseInterface

getOperationsClient

Return an OperationsClient object with the same endpoint as $this.

Returns
Type Description
Google\ApiCore\LongRunning\OperationsClient

resumeOperation

Resume an existing long running operation that was previously started by a long running API method. If $methodName is not provided, or does not match a long running API method, then the operation can still be resumed, but the OperationResponse object will not deserialize the final response.

Parameters
Name Description
operationName string

The name of the long running operation

methodName string

The name of the method used to start the operation

Returns
Type Description
Google\ApiCore\OperationResponse

static::branchName

Formats a string containing the fully-qualified path to represent a branch resource.

Parameters
Name Description
project string
location string
catalog string
branch string
Returns
Type Description
string The formatted branch resource.

static::productName

Formats a string containing the fully-qualified path to represent a product resource.

Parameters
Name Description
project string
location string
catalog string
branch string
product string
Returns
Type Description
string The formatted product resource.

static::parseName

Parses a formatted name string and returns an associative array of the components in the name.

The following name formats are supported: Template: Pattern

  • branch: projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}
  • product: projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}

The optional $template argument can be supplied to specify a particular pattern, and must match one of the templates listed above. If no $template argument is provided, or if the $template argument does not match one of the templates listed, then parseName will check each of the supported templates, and return the first match.

Parameters
Name Description
formattedName string

The formatted name string

template string

Optional name of template to match

Returns
Type Description
array An associative array from name component IDs to component values.