Google My Business API v1:正确使用readMask获取商家位置信息

DDD
发布: 2025-07-03 19:24:12
原创
414人浏览过

Google My Business API v1:正确使用readMask获取商家位置信息

本教程旨在解决在使用Google My Business Business Information API v1获取商家位置列表时,因readMask参数格式不正确导致的INVALID_ARGUMENT错误。核心在于,readMask必须指定Location资源自身的有效字段,而非其他关联资源或无效字段,以确保API请求的成功执行和数据的精准获取。

随着google my business api的迭代更新,尤其是从v4版本向更细粒度的服务(如businessinformation)迁移,开发者需要适应新的api结构和参数要求。在获取商家位置列表时,readmask参数是控制返回数据字段的关键,它允许客户端只请求所需的数据,从而提高性能并减少带宽消耗。

问题解析:readMask参数的误用

在使用Google_Service_MyBusinessBusinessInformation服务的accounts.locations.list方法时,开发者可能会遇到HTTP 400 INVALID_ARGUMENT错误,具体错误信息为Invalid field mask provided。这通常是由于readMask参数中包含了API不识别或不属于Location资源直接属性的字段。

例如,以下代码片段展示了一个常见的错误用法:

<?php

require __DIR__ . '/vendor/autoload.php'; // 假设您使用Composer管理依赖

use Google\Client;
use Google\Service\MyBusinessAccountManagement;
use Google\Service\MyBusinessBusinessInformation;
use Google\Service\Exception;

// 假设 $client 已经正确初始化并完成了认证
// 通常需要设置应用凭据或用户凭据
$client = new Client();
$client->setAuthConfig('path/to/your/credentials.json'); // 替换为您的凭据文件路径
$client->addScope('https://www.googleapis.com/auth/business.manage'); // 必要的API范围

try {
    $my_business_account = new MyBusinessAccountManagement($client);
    $list_accounts_response = $my_business_account->accounts->listAccounts();

    if (empty($list_accounts_response->getAccounts())) {
        echo "未找到任何账户。\n";
        exit;
    }

    $account = $list_accounts_response->getAccounts()[0]; // 获取第一个账户

    $mybusinessService = new MyBusinessBusinessInformation($client);
    $locations = $mybusinessService->accounts_locations;

    $queryParams = [
        "pageSize" => 10,
        // 错误示例:readMask 包含了非 Location 资源自身的字段
        'readMask' => "user.display_name,photo" 
    ];

    $locationsList = $locations->listAccountsLocations($account->name, $queryParams);

    // 处理返回的位置数据
    if ($locationsList->getLocations()) {
        foreach ($locationsList->getLocations() as $location) {
            echo "Location Name: " . $location->getName() . "\n";
            // 尝试访问 readMask 中指定的字段,但这里会因为 readMask 错误而无法获取正确数据
        }
    } else {
        echo "未找到任何位置。\n";
    }

} catch (Exception $e) {
    echo "发生错误: " . $e->getMessage() . "\n";
    if ($e->getCode() === 400) {
        // 尝试解析更详细的错误信息
        $errors = json_decode($e->getMessage(), true);
        if (isset($errors['error']['details'][0]['fieldViolations'][0]['description'])) {
            echo "错误详情: " . $errors['error']['details'][0]['fieldViolations'][0]['description'] . "\n";
        }
    }
}
登录后复制

上述代码中,readMask被设置为"user.display_name,photo"。然而,user.display_name和photo并非Location资源(https://developers.google.com/my-business/reference/businessinformation/rest/v1/locations)的直接顶级字段。readMask参数仅支持指定Location对象本身的属性,例如name、title、storeCode、websiteUri等。试图访问非直接属性会导致API服务器拒绝请求,并返回INVALID_ARGUMENT错误。

解决方案:正确构建readMask

解决此问题的关键在于,严格按照Google My Business Business Information API的Location资源定义来构建readMask。这意味着readMask中列出的字段必须是Location对象中直接可用的属性。

以下是一些Location资源常用的有效字段示例:

  • name:资源的完整名称,包括账户和位置ID。
  • title:商家在Google Maps上显示的名称。
  • storeCode:商家内部用于识别位置的唯一代码。
  • websiteUri:商家的官方网站URL。
  • phoneNumbers:商家的联系电话信息。
  • address:商家的物理地址。
  • latlng:商家的经纬度。
  • openInfo:商家的营业状态信息。
  • regularHours:商家的常规营业时间。
  • categories:商家的业务类别。

修正后的代码示例:

<?php

require __DIR__ . '/vendor/autoload.php'; // 假设您使用Composer管理依赖

use Google\Client;
use Google\Service\MyBusinessAccountManagement;
use Google\Service\MyBusinessBusinessInformation;
use Google\Service\Exception;

// 假设 $client 已经正确初始化并完成了认证
$client = new Client();
$client->setAuthConfig('path/to/your/credentials.json'); // 替换为您的凭据文件路径
$client->addScope('https://www.googleapis.com/auth/business.manage'); // 必要的API范围

try {
    $my_business_account = new MyBusinessAccountManagement($client);
    $list_accounts_response = $my_business_account->accounts->listAccounts();

    if (empty($list_accounts_response->getAccounts())) {
        echo "未找到任何账户。\n";
        exit;
    }

    $account = $list_accounts_response->getAccounts()[0]; // 获取第一个账户

    $mybusinessService = new MyBusinessBusinessInformation($client);
    $locations = $mybusinessService->accounts_locations;

    $queryParams = [
        "pageSize" => 10,
        // 正确示例:readMask 包含了 Location 资源自身的有效字段
        'readMask' => "name,title,storeCode,websiteUri,address"
    ];

    $locationsList = $locations->listAccountsLocations($account->name, $queryParams);

    if ($locationsList->getLocations()) {
        echo "成功获取商家位置列表:\n";
        foreach ($locationsList->getLocations() as $location) {
            echo "----------------------------------------\n";
            echo "位置名称 (API Name): " . $location->getName() . "\n";
            echo "商家标题 (Title): " . $location->getTitle() . "\n";
            echo "门店代码 (Store Code): " . $location->getStoreCode() . "\n";
            echo "网站URI (Website URI): " . $location->getWebsiteUri() . "\n";
            // 获取地址信息,地址是一个对象,需要进一步解析
            $address = $location->getAddress();
            if ($address) {
                echo "地址: " . $address->getPostalCode() . " " . $address->getLocality() . ", " . $address->getAdministrativeArea() . ", " . $address->getRegionCode() . "\n";
            }
        }
    } else {
        echo "未找到任何位置。\n";
    }

} catch (Exception $e) {
    echo "发生错误: " . $e->getMessage() . "\n";
    if ($e->getCode() === 400) {
        $errors = json_decode($e->getMessage(), true);
        if (isset($errors['error']['details'][0]['fieldViolations'][0]['description'])) {
            echo "错误详情: " . $errors['error']['details'][0]['fieldViolations'][0]['description'] . "\n";
        }
    }
}
登录后复制

注意事项与最佳实践

  1. 查阅官方文档: 始终以Google My Business Business Information API的官方Location资源文档(https://developers.google.com/my-business/reference/businessinformation/rest/v1/locations)为准,了解所有可用的字段及其数据类型。这是避免readMask错误的根本方法。
  2. 精确指定: readMask参数的目的是为了请求精确的数据。只请求你确实需要的字段,这不仅能避免INVALID_ARGUMENT错误,还能优化API调用的性能和响应时间,减少不必要的数据传输。
  3. 嵌套字段: 对于嵌套字段(例如address对象下的locality),readMask通常只需要指定顶级字段(例如address)。API客户端库会自动解析并返回该对象下的所有子字段,或者文档会明确指出如何指定嵌套路径。在Location资源中,像address、openInfo等都是复杂对象,指定它们会返回整个对象结构。
  4. 错误处理: 在生产环境中,务必实现健壮的错误处理机制。捕获并解析API返回的错误信息(特别是HTTP 400响应体中的fieldViolations),以便快速定位和解决问题。

总结

readMask参数在Google API中扮演着至关重要的角色,它控制着API响应中包含的数据字段。对于Google My Business Business Information API的accounts.locations.list方法,解决INVALID_ARGUMENT错误的关键在于确保readMask中指定的字段是Location资源本身定义的有效顶级属性。通过仔细查阅API文档并遵循正确的字段命名规范,开发者可以避免此类常见错误,并高效、准确地获取所需的商家位置数据。

以上就是Google My Business API v1:正确使用readMask获取商家位置信息的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号