性能提示

本文档介绍了可用来提高应用性能的方法和技巧。在某些情况下,我们会采用其他 API 或通用 API 中的示例来阐释所介绍的概念,不过,其中的概念对于 Google Wallet API 也同样适用。

使用 gzip 进行压缩

如需减少每个请求所需的带宽,您可以选择启用 gzip 压缩,这是一种既方便又简单的方法。虽然这种方法需要一些额外的 CPU 时间对结果进行解压缩,但考虑到它对节约网络费用的贡献,通常还是值得一用的。

为了接收 gzip 编码的响应,您必须执行以下两项操作:设置 Accept-Encoding 标头,以及修改您的用户代理,使其包含字符串 gzip。下面提供了一个用于启用 gzip 压缩的格式正确的 HTTP 标头示例:

Accept-Encoding: gzip
User-Agent: my program (gzip)

使用部分资源

提高 API 调用性能的另一方法是仅发送和接收您感兴趣的那部分数据。这样可以避免应用传输、解析和存储不需要的字段,使应用可以更高效地利用网络、CPU 和内存等资源。

部分请求有以下两种类型:

  • 部分响应:在此类请求中指定要包含在响应中的字段(使用 fields 请求参数)。
  • 修补:在此类更新请求中只发送您想更改的字段(使用 PATCH HTTP 动词)。

如需详细了解如何发出部分请求,请参阅以下各部分内容。

部分响应

默认情况下,处理完请求之后,服务器会发回资源的完整表示形式。为了提高性能,您可以要求服务器仅发送自己真正需要的字段,从而只接收部分响应。

如需请求部分响应,请使用 fields 请求参数来指定您希望返回的字段。对于返回响应数据的任何请求,您都可以使用此参数。

注意,fields 参数仅影响响应数据;并不会影响您需要发送的数据(如有)。如需减少您在修改资源时发送的数据量,请使用修补请求。

示例

以下示例显示的是将 fields 参数与通用(虚构)“Demo” API 结合使用的情况。

简单请求:下面的 HTTP GET 请求省略了 fields 参数,并且返回完整的资源。

https://www.googleapis.com/demo/v1

完整资源响应:完整资源数据包括以下字段以及其他许多字段(为简便起见,此处省略了那些字段)。

{
  "kind": "demo",
  ...
  "items": [
  {
    "title": "First title",
    "comment": "First comment.",
    "characteristics": {
      "length": "short",
      "accuracy": "high",
      "followers": ["Jo", "Will"],
    },
    "status": "active",
    ...
  },
  {
    "title": "Second title",
    "comment": "Second comment.",
    "characteristics": {
      "length": "long",
      "accuracy": "medium"
      "followers": [ ],
    },
    "status": "pending",
    ...
  },
  ...
  ]
}

对部分响应的请求:以下针对此同一资源的请求使用了 fields 参数,从而大幅减少了所返回的数据量。

https://www.googleapis.com/demo/v1?fields=kind,items(title,characteristics/length)

部分响应:服务器为响应上述请求而发回的响应只包含类型信息和一个简化的 items 数组,该数组中的每个项目只包含 HTML 标题和长度特征信息。

200 OK
{
  "kind": "demo",
  "items": [{
    "title": "First title",
    "characteristics": {
      "length": "short"
    }
  }, {
    "title": "Second title",
    "characteristics": {
      "length": "long"
    }
  },
  ...
  ]
}

请注意,该响应是一个只包括所选字段及其所属父对象的 JSON 对象。

接下来,我们将详细介绍如何设置 fields 参数格式,以及响应中会返回哪些确切内容。

“fields”参数语法摘要

fields 请求参数值的格式大致上基于 XPath 语法。支持的语法总结如下,另外下一节还将提供更多示例。

  • 使用以逗号分隔的列表来选择多个字段。
  • 使用 a/b 选择嵌套在字段 a 内的字段 b;使用 a/b/c 选择嵌套在 b 内的字段 c。

    例外:对于使用“data”封装容器的 API 响应(响应嵌套在 data 对象内,例如 data: { ... }),请勿在 fields 规范中包含“data”。在 fields 规范中加入 data 对象(如 data/a/b)会引发错误。请改用类似 a/b 的 fields 规范。

  • 用圆括号“( )”将表达式括起来,使用子选择器请求数组或对象的一组特定子字段。

    例如:fields=items(id,author/email) 只会返回 items 数组中每个元素的项 ID 和作者的电子邮件地址。您还可以指定单个子字段,其中 fields=items(id) 等同于 fields=items/id。

  • 如果需要,可在选择字段时使用通配符。

    例如:使用 fields=items/pagemap/* 即可选择 pagemap 中的所有对象。

使用 fields 参数的更多示例

下面的示例说明了 fields 参数值对响应有何影响。

注意:与所有查询参数值一样,fields 参数值也必须采用网址编码。为了便于阅读,本文中的示例省略了编码。

指定您想返回的字段,或者进行字段选择。
fields 请求参数值是一个以英文逗号分隔的字段列表,并且每个字段均是相对于响应的根来指定的。因此,如果您执行的是 list 操作,响应就是一个集合,其中通常包含一系列资源。如果您执行的是返回单一资源的操作,则字段是相对于该资源指定的。如果您选择的字段是(或属于)一个数组,则服务器会返回数组中所有元素的选定部分。

下面提供了几个集合层面的示例:
示例 效果
items 返回 items 数组中的所有元素,包括每个元素中的所有字段,但不包括其他字段。
etag,items 同时返回 etag 字段和 items 数组中的所有元素。
items/title 仅返回 items 数组中所有元素的 title 字段。

每当返回嵌套字段时,响应中均包括该字段的父对象。父级字段不会包含其他任何子字段(除非已明确选择)。
context/facets/label 仅返回 facets 数组中所有成员的 label 字段,而该数组本身嵌套在 context 对象中。
items/pagemap/*/title 对于 items 数组中的每个元素,仅返回 pagemap 的所有子对象的 title 字段(如果存在)。

以下是一些资源级别的示例:
示例 效果
title 返回所请求资源的 title 字段。
author/uri 返回所请求资源中 author 对象的 uri 子字段。
links/*/href
返回 links 的所有子对象的 href 字段。
使用“子选择”仅请求特定字段的相关部分。
默认情况下,如果您的请求指定具体字段,则服务器会完整地返回相应的对象或数组元素。您可以指定一个仅包含特定子字段的响应。如下例所示,您可以使用“( )”子选择语法来实现此目的。
示例 效果
items(title,author/uri) 仅返回 items 数组中每个元素的 title 值和作者的 uri。

处理部分响应

处理完含有 fields 查询参数的有效请求之后,服务器将发回一个 HTTP 200 OK 状态代码以及所请求的数据。如果 fields 查询参数出现错误或因其他原因而无效,服务器将返回一个 HTTP 400 Bad Request 状态代码以及一条错误消息,告知用户他们的字段选择出现了什么错误(例如 "Invalid field selection a/b")。

以下是上文简介部分所提到的部分响应的示例。该请求使用 fields 参数来指定要返回的字段。

https://www.googleapis.com/demo/v1?fields=kind,items(title,characteristics/length)

部分响应如下所示:

200 OK
{
  "kind": "demo",
  "items": [{
    "title": "First title",
    "characteristics": {
      "length": "short"
    }
  }, {
    "title": "Second title",
    "characteristics": {
      "length": "long"
    }
  },
  ...
  ]
}

注意:对于支持使用查询参数进行数据分页(例如 maxResults 和 nextPageToken)的 API,请使用这些参数将每个查询的结果缩减为易于管理的大小。否则,可能无法实现本可通过部分响应获得的性能提升。

修补(部分更新)

在修改资源时,您也可以避免发送不必要的数据。如果您只想为您要更改的特定字段发送更新数据,请使用 HTTP PATCH 动词。本文所述的修补语义不同于采用 GData 实现的旧版部分更新方案,并且更简单。

下面的简短示例显示了如何使用修补最大限度地减少进行小的更新时需要发送的数据。

示例

本示例显示的是一个简单的修补请求,目的只是为了更新一个通用(虚构)“Demo” API 资源的标题。该资源还包含一条注释、一组特征、状态以及许多其他字段,但由于 title 字段是唯一要修改的字段,所以此请求仅会发送该字段:

PATCH https://www.googleapis.com/demo/v1/324
Authorization: Bearer your_auth_token
Content-Type: application/json

{
  "title": "New title"
}

响应:

200 OK
{
  "title": "New title",
  "comment": "First comment.",
  "characteristics": {
    "length": "short",
    "accuracy": "high",
    "followers": ["Jo", "Will"],
  },
  "status": "active",
  ...
}

服务器将返回 200 OK 状态代码以及更新后的资源的完整表示形式。由于修补请求中仅包含 title 字段,因此只有该值会与之前的值有所不同。

注意:如果您将部分响应 fields 参数与修补请求结合使用,则可以进一步提高更新请求的效率。修补请求只会缩减请求的大小。而部分响应会缩减响应的大小。因此,为了使两个方向发送的数据量都缩减,请将修补请求与 fields 参数结合使用。

修补请求的语义

PATCH 请求的正文中仅包含您要修改的资源字段。在指定字段时,您必须将其所属的任何父级对象也包括在内,就如部分响应中也会返回所属父级对象。您发送的已修改数据将合并到父对象(如果有)的数据中。

  • 添加:要添加目前并不存在的字段,请指定这个新字段及其值。
  • 修改:如需更改现有字段的值,请指定该字段并将其设置为新值。
  • 删除:如需删除字段,请指定相应字段并将其设置为 null。例如:"comment": null。此外,您还可以删除整个对象(如果该对象是可变的),只需将其设置为 null 即可。如果您使用的是 Java API 客户端库,请改用 Data.NULL_STRING;如需了解详情,请参阅 JSON null。

关于数组的备注:包含数组的修补请求会将现有数组替换为您提供的数组。您不能逐个修改、添加或删除数组中的项目。

在读取-修改-写入周期中使用修补

一种比较实用的做法是,先检索包含您要修改的数据的部分响应。这对于使用 ETag 的资源尤其重要,因为您必须在 If-Match HTTP 标头中提供当前 ETag 值才能成功更新资源。获取数据之后,您就可以修改自己想要更改的值,并将已修改的部分表示形式与修补请求一起发回。以下示例假设 Demo 资源使用 ETag:

GET https://www.googleapis.com/demo/v1/324?fields=etag,title,comment,characteristics
Authorization: Bearer your_auth_token

以下是部分响应:

200 OK
{
  "etag": "ETagString"
  "title": "New title"
  "comment": "First comment.",
  "characteristics": {
    "length": "short",
    "level": "5",
    "followers": ["Jo", "Will"],
  }
}

以下修补请求基于该响应。如下所示,该请求还使用 fields 参数对修补响应中返回的数据进行限制:

PATCH https://www.googleapis.com/demo/v1/324?fields=etag,title,comment,characteristics
Authorization: Bearer your_auth_token
Content-Type: application/json
If-Match: "ETagString"
{
  "etag": "ETagString"
  "title": "",                  /* Clear the value of the title by setting it to the empty string. */
  "comment": null,              /* Delete the comment by replacing its value with null. */
  "characteristics": {
    "length": "short",
    "level": "10",              /* Modify the level value. */
    "followers": ["Jo", "Liz"], /* Replace the followers array to delete Will and add Liz. */
    "accuracy": "high"          /* Add a new characteristic. */
  },
}

服务器将返回 200 OK HTTP 状态代码,以及更新后的资源的部分表示形式:

200 OK
{
  "etag": "newETagString"
  "title": "",                 /* Title is cleared; deleted comment field is missing. */
  "characteristics": {
    "length": "short",
    "level": "10",             /* Value is updated.*/
    "followers": ["Jo" g>"Liz"], /* New follower Liz is present; deleted Will is missing. */
    "accuracy": "high"         /* New characteristic is present. */
  }
}

直接构建修补请求

某些修补请求必须以您之前检索到的数据作为构建依据。例如,如果您希望向数组中添加项目,并且不希望丢失任何现有的数组元素,则需要首先获取现有的数据。同样,如果 API 使用 ETag,您必须将之前的 ETag 值与您的请求一起发送,才能成功更新资源。

注意:您可以借助 "If-Match: *" HTTP 标头强制在使用 ETag 时完成修补。如果您采用这一方法,就无需在写入之前执行读取操作。

不过,在其他一些情况下,您可以直接构建修补请求,无需首先检索现有数据。例如,您可以轻松创建一个修补请求,用以将某个字段更新为新值或添加一个新字段。示例如下:

PATCH https://www.googleapis.com/demo/v1/324?fields=comment,characteristics
Authorization: Bearer your_auth_token
Content-Type: application/json

{
  "comment": "A new comment",
  "characteristics": {
    "volume": "loud",
    "accuracy": null
  }
}

对于该请求,如果 comment 字段已有值,则新值会覆盖该值;否则,系统会将该字段设置为新值。同样,如果 volume 特征已有值,则该值会被覆盖;否则,系统会创建一个值。accuracy 字段(如果已设置)会被移除。

处理修补请求的响应

处理有效修补请求之后,API 会返回 200 OK HTTP 响应代码以及修改后的资源的完整表示形式。如果 API 使用了 ETag,则服务器会在成功处理修补请求后更新 ETag 值,正如使用 PUT 时那样。

修补请求的响应会返回资源的完整表示形式,除非您使用 fields 参数减少其返回的数据量。

如果修补请求导致的新资源状态在语法或语义上是无效的,则服务器会返回 400 Bad Request 或 422 Unprocessable Entity HTTP 状态代码,并且资源状态会保持不变。例如,如果您尝试删除必填字段的值,服务器就会返回错误。

不支持 PATCH HTTP 动词时的备用表示法

如果您的防火墙不允许 HTTP PATCH 请求,则可使用 HTTP POST 请求,并将替换标头设为 PATCH,如下所示:

POST https://www.googleapis.com/...
X-HTTP-Method-Override: PATCH
...

修补与更新之间的区别

在实际操作中,当为使用了 HTTP PUT 动词的更新请求发送数据时,您只需发送那些必需或可选字段;如果您发送服务器所设置的字段值,这些值将会被忽略。尽管这看起来好像是另一种执行部分更新的方法,但该方法有一些局限性。对于使用 HTTP PUT 动词的更新,如果您没有提供必需参数,则请求会失败;如果您没有提供可选参数,则请求会清除之前设置的数据。

出于以上原因,使用补丁程序是一个安全得多的选择。您只需为自己想要修改的字段提供数据;系统不会清除您省略的字段。此规则的唯一例外情况是存在重复的元素或数组之时:如果您省略所有重复的元素或数组,它们将会保持原样;如果您提供其中任何元素或数组,系统会将所有元素或数组替换为您提供的元素或数组。

向 Google 钱包发送批处理请求

Google Wallet API 支持批处理 API 调用,以减少客户端必须建立的连接数。如需详细了解批量请求和响应结构,请参阅批量详细信息。

以下示例代码演示了如何批量处理请求。Java 和 PHP 示例使用 Google 钱包库来简化类和对象的创建。

Java

如需开始在 Java 中进行集成,请参阅 GitHub 上提供的完整代码示例。

/**
 * Batch create Google Wallet objects from an existing class.
 *
 * @param issuerId The issuer ID being used for this request.
 * @param classSuffix Developer-defined unique ID for this pass class.
 */
public void BatchCreateObjects(String issuerId, String classSuffix) throws IOException {
  // Create the batch request client
  BatchRequest batch = service.batch(new HttpCredentialsAdapter(credentials));

  // The callback will be invoked for each request in the batch
  JsonBatchCallback<LoyaltyObject> callback =
      new JsonBatchCallback<LoyaltyObject>() {
        // Invoked if the request was successful
        public void onSuccess(LoyaltyObject response, HttpHeaders responseHeaders) {
          System.out.println("Batch insert response");
          System.out.println(response.toString());
        }

        // Invoked if the request failed
        public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
          System.out.println("Error Message: " + e.getMessage());
        }
      };

  // Example: Generate three new pass objects
  for (int i = 0; i < 3; i++) {
    // Generate a random object suffix
    String objectSuffix = UUID.randomUUID().toString().replaceAll("[^\\w.-]", "_");

    // See link below for more information on required properties
    // https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
    LoyaltyObject batchObject =
        new LoyaltyObject()
            .setId(String.format("%s.%s", issuerId, objectSuffix))
            .setClassId(String.format("%s.%s", issuerId, classSuffix))
            .setState("ACTIVE")
            .setHeroImage(
                new Image()
                    .setSourceUri(
                        new ImageUri()
                            .setUri(
                                "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"))
                    .setContentDescription(
                        new LocalizedString()
                            .setDefaultValue(
                                new TranslatedString()
                                    .setLanguage("en-US")
                                    .setValue("Hero image description"))))
            .setTextModulesData(
                    List.of(
                            new TextModuleData()
                                    .setHeader("Text module header")
                                    .setBody("Text module body")
                                    .setId("TEXT_MODULE_ID")))
            .setLinksModuleData(
                new LinksModuleData()
                    .setUris(
                        Arrays.asList(
                            new Uri()
                                .setUri("http://maps.google.com/")
                                .setDescription("Link module URI description")
                                .setId("LINK_MODULE_URI_ID"),
                            new Uri()
                                .setUri("tel:6505555555")
                                .setDescription("Link module tel description")
                                .setId("LINK_MODULE_TEL_ID"))))
            .setImageModulesData(
                    List.of(
                            new ImageModuleData()
                                    .setMainImage(
                                            new Image()
                                                    .setSourceUri(
                                                            new ImageUri()
                                                                    .setUri(
                                                                            "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"))
                                                    .setContentDescription(
                                                            new LocalizedString()
                                                                    .setDefaultValue(
                                                                            new TranslatedString()
                                                                                    .setLanguage("en-US")
                                                                                    .setValue("Image module description"))))
                                    .setId("IMAGE_MODULE_ID")))
            .setBarcode(new Barcode().setType("QR_CODE").setValue("QR code value"))
            .setLocations(
                    List.of(
                            new LatLongPoint()
                                    .setLatitude(37.424015499999996)
                                    .setLongitude(-122.09259560000001)))
            .setAccountId("Account ID")
            .setAccountName("Account name")
            .setLoyaltyPoints(
                new LoyaltyPoints()
                    .setLabel("Points")
                    .setBalance(new LoyaltyPointsBalance().setInt(800)));

    service.loyaltyobject().insert(batchObject).queue(batch, callback);
  }

  // Invoke the batch API calls
  batch.execute();
}

PHP

如需开始在 PHP 中进行集成,请参阅 GitHub 上的完整代码示例。

/**
 * Batch create Google Wallet objects from an existing class.
 *
 * @param string $issuerId The issuer ID being used for this request.
 * @param string $classSuffix Developer-defined unique ID for the pass class.
 */
public function batchCreateObjects(string $issuerId, string $classSuffix)
{
  // Update the client to enable batch requests
  $this->client->setUseBatch(true);
  $batch = $this->service->createBatch();

  // Example: Generate three new pass objects
  for ($i = 0; $i < 3; $i++) {
    // Generate a random object suffix
    $objectSuffix = preg_replace('/[^\w.-]/i', '_', uniqid());

    // See link below for more information on required properties
    // https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
    $batchObject = new LoyaltyObject([
      'id' => "{$issuerId}.{$objectSuffix}",
      'classId' => "{$issuerId}.{$classSuffix}",
      'state' => 'ACTIVE',
      'heroImage' => new Image([
        'sourceUri' => new ImageUri([
          'uri' => 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg'
        ]),
        'contentDescription' => new LocalizedString([
          'defaultValue' => new TranslatedString([
            'language' => 'en-US',
            'value' => 'Hero image description'
          ])
        ])
      ]),
      'textModulesData' => [
        new TextModuleData([
          'header' => 'Text module header',
          'body' => 'Text module body',
          'id' => 'TEXT_MODULE_ID'
        ])
      ],
      'linksModuleData' => new LinksModuleData([
        'uris' => [
          new Uri([
            'uri' => 'http://maps.google.com/',
            'description' => 'Link module URI description',
            'id' => 'LINK_MODULE_URI_ID'
          ]),
          new Uri([
            'uri' => 'tel:6505555555',
            'description' => 'Link module tel description',
            'id' => 'LINK_MODULE_TEL_ID'
          ])
        ]
      ]),
      'imageModulesData' => [
        new ImageModuleData([
          'mainImage' => new Image([
            'sourceUri' => new ImageUri([
              'uri' => 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg'
            ]),
            'contentDescription' => new LocalizedString([
              'defaultValue' => new TranslatedString([
                'language' => 'en-US',
                'value' => 'Image module description'
              ])
            ])
          ]),
          'id' => 'IMAGE_MODULE_ID'
        ])
      ],
      'barcode' => new Barcode([
        'type' => 'QR_CODE',
        'value' => 'QR code value'
      ]),
      'locations' => [
        new LatLongPoint([
          'latitude' => 37.424015499999996,
          'longitude' =>  -122.09259560000001
        ])
      ],
      'accountId' => 'Account ID',
      'accountName' => 'Account name',
      'loyaltyPoints' => new LoyaltyPoints([
        'balance' => new LoyaltyPointsBalance([
          'int' => 800
        ])
      ])
    ]);

    $batch->add($this->service->loyaltyobject->insert($batchObject));
  }

  // Make the batch request
  $batchResponse = $batch->execute();

  print "Batch insert response\n";
  foreach ($batchResponse as $key => $value) {
    if ($value instanceof Google_Service_Exception) {
      print_r($value->getErrors());
      continue;
    }
    print "{$value->getId()}\n";
  }
}

Python

如需开始在 Python 中进行集成,请参阅 GitHub 上的完整代码示例。

def batch_create_objects(self, issuer_id: str, class_suffix: str):
    """Batch create Google Wallet objects from an existing class.

    The request body will be a multiline string. See below for information.

    https://cloud.google.com/compute/docs/api/how-tos/batch#example

    Args:
        issuer_id (str): The issuer ID being used for this request.
        class_suffix (str): Developer-defined unique ID for this pass class.
    """
    batch = self.client.new_batch_http_request()

    # Example: Generate three new pass objects
    for _ in range(3):
        # Generate a random object suffix
        object_suffix = str(uuid.uuid4()).replace('[^\\w.-]', '_')

        # See link below for more information on required properties
        # https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
        batch_object = {
            'id': f'{issuer_id}.{object_suffix}',
            'classId': f'{issuer_id}.{class_suffix}',
            'state': 'ACTIVE',
            'heroImage': {
                'sourceUri': {
                    'uri':
                        'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg'
                },
                'contentDescription': {
                    'defaultValue': {
                        'language': 'en-US',
                        'value': 'Hero image description'
                    }
                }
            },
            'textModulesData': [{
                'header': 'Text module header',
                'body': 'Text module body',
                'id': 'TEXT_MODULE_ID'
            }],
            'linksModuleData': {
                'uris': [{
                    'uri': 'http://maps.google.com/',
                    'description': 'Link module URI description',
                    'id': 'LINK_MODULE_URI_ID'
                }, {
                    'uri': 'tel:6505555555',
                    'description': 'Link module tel description',
                    'id': 'LINK_MODULE_TEL_ID'
                }]
            },
            'imageModulesData': [{
                'mainImage': {
                    'sourceUri': {
                        'uri':
                            'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg'
                    },
                    'contentDescription': {
                        'defaultValue': {
                            'language': 'en-US',
                            'value': 'Image module description'
                        }
                    }
                },
                'id': 'IMAGE_MODULE_ID'
            }],
            'barcode': {
                'type': 'QR_CODE',
                'value': 'QR code'
            },
            'locations': [{
                'latitude': 37.424015499999996,
                'longitude': -122.09259560000001
            }],
            'accountId': 'Account id',
            'accountName': 'Account name',
            'loyaltyPoints': {
                'label': 'Points',
                'balance': {
                    'int': 800
                }
            }
        }

        batch.add(self.client.loyaltyobject().insert(body=batch_object))

    # Invoke the batch API calls
    response = batch.execute()

    print('Batch complete')

C#

如需开始在 C# 中进行集成,请参阅 GitHub 上提供的完整 代码示例。

/// <summary>
/// Batch create Google Wallet objects from an existing class.
/// </summary>
/// <param name="issuerId">The issuer ID being used for this request.</param>
/// <param name="classSuffix">Developer-defined unique ID for this pass class.</param>
public async void BatchCreateObjects(string issuerId, string classSuffix)
{
  // The request body will be a multiline string
  // See below for more information
  // https://cloud.google.com/compute/docs/api/how-tos/batch//example
  string data = "";

  HttpClient httpClient = new HttpClient();
  httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer",
    credentials.GetAccessTokenForRequestAsync().Result
  );

  // Example: Generate three new pass objects
  for (int i = 0; i < 3; i++)
  {
    // Generate a random object suffix
    string objectSuffix = Regex.Replace(Guid.NewGuid().ToString(), "[^\\w.-]", "_");

    // See link below for more information on required properties
    // https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
    LoyaltyObject batchObject = new LoyaltyObject
    {
      Id = $"{issuerId}.{objectSuffix}",
      ClassId = $"{issuerId}.{classSuffix}",
      State = "ACTIVE",
      HeroImage = new Image
      {
        SourceUri = new ImageUri
        {
          Uri = "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg"
        },
        ContentDescription = new LocalizedString
        {
          DefaultValue = new TranslatedString
          {
            Language = "en-US",
            Value = "Hero image description"
          }
        }
      },
      TextModulesData = new List<TextModuleData>
      {
        new TextModuleData
        {
          Header = "Text module header",
          Body = "Text module body",
          Id = "TEXT_MODULE_ID"
        }
      },
      LinksModuleData = new LinksModuleData
      {
        Uris = new List<Google.Apis.Walletobjects.v1.Data.Uri>
        {
          new Google.Apis.Walletobjects.v1.Data.Uri
          {
            UriValue = "http://maps.google.com/",
            Description = "Link module URI description",
            Id = "LINK_MODULE_URI_ID"
          },
          new Google.Apis.Walletobjects.v1.Data.Uri
          {
            UriValue = "tel:6505555555",
            Description = "Link module tel description",
            Id = "LINK_MODULE_TEL_ID"
          }
        }
      },
      ImageModulesData = new List<ImageModuleData>
      {
        new ImageModuleData
        {
          MainImage = new Image
          {
            SourceUri = new ImageUri
            {
              Uri = "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg"
            },
            ContentDescription = new LocalizedString
            {
              DefaultValue = new TranslatedString
              {
                Language = "en-US",
                Value = "Image module description"
              }
            }
          },
          Id = "IMAGE_MODULE_ID"
        }
      },
      Barcode = new Barcode
      {
        Type = "QR_CODE",
        Value = "QR code"
      },
      Locations = new List<LatLongPoint>
      {
        new LatLongPoint
        {
          Latitude = 37.424015499999996,
          Longitude = -122.09259560000001
        }
      },
      AccountId = "Account id",
      AccountName = "Account name",
      LoyaltyPoints = new LoyaltyPoints
      {
        Label = "Points",
        Balance = new LoyaltyPointsBalance
        {
          Int__ = 800
        }
      }
    };

    data += "--batch_createobjectbatch\n";
    data += "Content-Type: application/json\n\n";
    data += "POST /walletobjects/v1/loyaltyObject/\n\n";

    data += JsonConvert.SerializeObject(batchObject) + "\n\n";
  }
  data += "--batch_createobjectbatch--";

  // Invoke the batch API calls
  HttpRequestMessage batchObjectRequest = new HttpRequestMessage(
      HttpMethod.Post,
      "https://walletobjects.googleapis.com/batch");

  batchObjectRequest.Content = new StringContent(data);
  batchObjectRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(
      "multipart/mixed");
  // `boundary` is the delimiter between API calls in the batch request
  batchObjectRequest.Content.Headers.ContentType.Parameters.Add(
      new NameValueHeaderValue("boundary", "batch_createobjectbatch"));

  HttpResponseMessage batchObjectResponse = httpClient.Send(
      batchObjectRequest);

  string batchObjectContent = await batchObjectResponse
      .Content
      .ReadAsStringAsync();

  Console.WriteLine("Batch insert response");
  Console.WriteLine(batchObjectContent);
}

Node.js

如需开始在 Node 中进行集成,请参阅 GitHub 上提供的完整 代码示例。

/**
 * Batch create Google Wallet objects from an existing class.
 *
 * @param {string} issuerId The issuer ID being used for this request.
 * @param {string} classSuffix Developer-defined unique ID for this pass class.
 */
async batchCreateObjects(issuerId, classSuffix) {
  // See below for more information
  // https://cloud.google.com/compute/docs/api/how-tos/batch#example
  let data = '';
  let batchObject;
  let objectSuffix;

  // Example: Generate three new pass objects
  for (let i = 0; i < 3; i++) {
    // Generate a random object suffix
    objectSuffix = uuidv4().replace('[^\w.-]', '_');

    // See link below for more information on required properties
    // https://developers.google.com/wallet/retail/loyalty-cards/rest/v1/loyaltyobject
    batchObject = {
      'id': `${issuerId}.${objectSuffix}`,
      'classId': `${issuerId}.${classSuffix}`,
      'state': 'ACTIVE',
      'heroImage': {
        'sourceUri': {
          'uri': 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg'
        },
        'contentDescription': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'Hero image description'
          }
        }
      },
      'textModulesData': [
        {
          'header': 'Text module header',
          'body': 'Text module body',
          'id': 'TEXT_MODULE_ID'
        }
      ],
      'linksModuleData': {
        'uris': [
          {
            'uri': 'http://maps.google.com/',
            'description': 'Link module URI description',
            'id': 'LINK_MODULE_URI_ID'
          },
          {
            'uri': 'tel:6505555555',
            'description': 'Link module tel description',
            'id': 'LINK_MODULE_TEL_ID'
          }
        ]
      },
      'imageModulesData': [
        {
          'mainImage': {
            'sourceUri': {
              'uri': 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg'
            },
            'contentDescription': {
              'defaultValue': {
                'language': 'en-US',
                'value': 'Image module description'
              }
            }
          },
          'id': 'IMAGE_MODULE_ID'
        }
      ],
      'barcode': {
        'type': 'QR_CODE',
        'value': 'QR code'
      },
      'locations': [
        {
          'latitude': 37.424015499999996,
          'longitude': -122.09259560000001
        }
      ],
      'accountId': 'Account id',
      'accountName': 'Account name',
      'loyaltyPoints': {
        'label': 'Points',
        'balance': {
          'int': 800
        }
      }
    };

    data += '--batch_createobjectbatch\n';
    data += 'Content-Type: application/json\n\n';
    data += 'POST /walletobjects/v1/loyaltyObject\n\n';

    data += JSON.stringify(batchObject) + '\n\n';
  }
  data += '--batch_createobjectbatch--';

  // Invoke the batch API calls
  let response = await this.client.context._options.auth.request({
    url: 'https://walletobjects.googleapis.com/batch',
    method: 'POST',
    data: data,
    headers: {
      // `boundary` is the delimiter between API calls in the batch request
      'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
    }
  });

  console.log('Batch insert response');
  console.log(response);
}

Go

如需开始在 Go 中进行集成,请参阅 GitHub 上的完整代码示例 GitHub 上的代码示例。

// Batch create Google Wallet objects from an existing class.
func (d *demoLoyalty) batchCreateObjects(issuerId, classSuffix string) {
	data := ""
	for i := 0; i < 3; i++ {
		objectSuffix := strings.ReplaceAll(uuid.New().String(), "-", "_")

		loyaltyObject := new(walletobjects.LoyaltyObject)
		loyaltyObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix)
		loyaltyObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix)
		loyaltyObject.AccountName = "Account name"
		loyaltyObject.AccountId = "Account id"
		loyaltyObject.State = "ACTIVE"

		loyaltyJson, _ := json.Marshal(loyaltyObject)
		batchObject := fmt.Sprintf("%s", loyaltyJson)

		data += "--batch_createobjectbatch\n"
		data += "Content-Type: application/json\n\n"
		data += "POST /walletobjects/v1/loyaltyObject\n\n"
		data += batchObject + "\n\n"
	}
	data += "--batch_createobjectbatch--"

	res, err := d.credentials.Client(oauth2.NoContext).Post("https://walletobjects.googleapis.com/batch", "multipart/mixed; boundary=batch_createobjectbatch", bytes.NewBuffer([]byte(data)))

	if err != nil {
		fmt.Println(err)
	} else {
		b, _ := io.ReadAll(res.Body)
		fmt.Printf("Batch insert response:\n%s\n", b)
	}
}