Создание классов проходов и объектов проходов

Почти все пропуски, которые вы можете выдать конечному пользователю для сохранения в своем Google Кошельке, определяются двумя компонентами: классом пропусков и объектом пропусков. Каждый раз, когда вы выдаете пропуск пользователю, вам понадобится экземпляр класса Passes и объекта Passes, который сообщает API Google Кошелька, какой тип пропуска нужно создать, а также детали, которые нужно отобразить на пропуске, например стоимость подарочной карты или имя владельца билета.

API Google Кошелька предоставляет предопределенный набор классов Passes и объектов Passes, экземпляры которых вы создаете, а затем используете для создания пропуска, выдаваемого пользователю, например GiftCardClass и GiftCardObject , GenericClass и GenericObject и другие.

Каждый экземпляр класса Passes и объекта Passes определяется как объект JSON, который имеет набор обязательных и дополнительных свойств, соответствующих конкретному варианту использования, предназначенному для этого типа прохода.

Создайте класс пропусков

Класс пропусков можно рассматривать как общий шаблон, на основе которого создаются пропуски. Класс проходов определяет определенные свойства, которые будут включены во все проходы, которые его используют. Эмитент пропуска может создать несколько классов, каждый из которых имеет свой собственный набор свойств, определяющих такие атрибуты, как стиль и внешний вид, а также дополнительные функции, такие как Smart Tap, а также регистрацию и вход в систему.

Классы Passes можно создавать с помощью REST API Google Кошелька, Google Wallet Android SDK или в бизнес-консоли Google Wallet.

Для новых пользователей бизнес-консоль — это самый простой способ начать работу с созданием класса Passes, поскольку она предоставляет простой пользовательский интерфейс, в котором вы можете определить различные поля вашего первого класса Passes, заполняя поля формы.

Для опытных пользователей лучшим подходом является программное создание классов Passes.

Используйте бизнес-консоль Google Кошелька

Чтобы создать класс Passes в консоли Google Wallet Business, выполните следующие действия:

  1. Перейдите в бизнес-консоль Google Pay и Wallet и войдите в свою учетную запись эмитента API Google Кошелька.
  2. На карточке «API Google Кошелька» нажмите кнопку «Управление пропусками».
  3. В разделе «Получить доступ к публикации» нажмите кнопку «Создать курс».
  4. Выберите тип пропуска в диалоговом окне. Google Кошелек предлагает различные типы пропусков (билет на мероприятие, предложение, карта лояльности и т. д.). Для гибкого варианта использования выберите «Общий» в качестве типа пропуска.
  5. Заполните соответствующие значения в обязательных полях.
  6. Нажмите кнопку «Создать класс», чтобы сохранить класс.

Используйте REST API Google Кошелька.

Чтобы создать класс Passes с помощью REST API Google Кошелька, отправьте запрос POST на адрес https://walletobjects.googleapis.com/walletobjects/v1/genericClass . Дополнительную информацию смотрите в справочной документации .

Джава

Чтобы начать интеграцию с Java, ознакомьтесь с нашими полными примерами кода на GitHub .

/**
 * Create a class.
 *
 * @param issuerId The issuer ID being used for this request.
 * @param classSuffix Developer-defined unique ID for this pass class.
 * @return The pass class ID: "{issuerId}.{classSuffix}"
 */
public String createClass(String issuerId, String classSuffix) throws IOException {
  // Check if the class exists
  try {
    service.genericclass().get(String.format("%s.%s", issuerId, classSuffix)).execute();

    System.out.printf("Class %s.%s already exists!%n", issuerId, classSuffix);
    return String.format("%s.%s", issuerId, classSuffix);
  } catch (GoogleJsonResponseException ex) {
    if (ex.getStatusCode() != 404) {
      // Something else went wrong...
      ex.printStackTrace();
      return String.format("%s.%s", issuerId, classSuffix);
    }
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/generic/rest/v1/genericclass
  GenericClass newClass = new GenericClass().setId(String.format("%s.%s", issuerId, classSuffix));

  GenericClass response = service.genericclass().insert(newClass).execute();

  System.out.println("Class insert response");
  System.out.println(response.toPrettyString());

  return response.getId();
}

PHP

Чтобы начать интеграцию с PHP, ознакомьтесь с нашими полными примерами кода на GitHub .

/**
 * Create a class.
 *
 * @param string $issuerId The issuer ID being used for this request.
 * @param string $classSuffix Developer-defined unique ID for this pass class.
 *
 * @return string The pass class ID: "{$issuerId}.{$classSuffix}"
 */
public function createClass(string $issuerId, string $classSuffix)
{
  // Check if the class exists
  try {
    $this->service->genericclass->get("{$issuerId}.{$classSuffix}");

    print("Class {$issuerId}.{$classSuffix} already exists!");
    return "{$issuerId}.{$classSuffix}";
  } catch (Google\Service\Exception $ex) {
    if (empty($ex->getErrors()) || $ex->getErrors()[0]['reason'] != 'classNotFound') {
      // Something else went wrong...
      print_r($ex);
      return "{$issuerId}.{$classSuffix}";
    }
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/generic/rest/v1/genericclass
  $newClass = new GenericClass([
    'id' => "{$issuerId}.{$classSuffix}"
  ]);

  $response = $this->service->genericclass->insert($newClass);

  print "Class insert response\n";
  print_r($response);

  return $response->id;
}

Питон

Чтобы начать интеграцию с Python, ознакомьтесь с полными примерами кода на GitHub .

def create_class(self, issuer_id: str, class_suffix: str) -> str:
    """Create a class.

    Args:
        issuer_id (str): The issuer ID being used for this request.
        class_suffix (str): Developer-defined unique ID for this pass class.

    Returns:
        The pass class ID: f"{issuer_id}.{class_suffix}"
    """

    # Check if the class exists
    try:
        self.client.genericclass().get(resourceId=f'{issuer_id}.{class_suffix}').execute()
    except HttpError as e:
        if e.status_code != 404:
            # Something else went wrong...
            print(e.error_details)
            return f'{issuer_id}.{class_suffix}'
    else:
        print(f'Class {issuer_id}.{class_suffix} already exists!')
        return f'{issuer_id}.{class_suffix}'

    # See link below for more information on required properties
    # https://developers.google.com/wallet/generic/rest/v1/genericclass
    new_class = {'id': f'{issuer_id}.{class_suffix}'}

    response = self.client.genericclass().insert(body=new_class).execute()

    print('Class insert response')
    print(response)

    return f'{issuer_id}.{class_suffix}'

С#

Чтобы начать интеграцию с C#, ознакомьтесь с полными примерами кода на GitHub .

/// <summary>
/// Create a 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>
/// <returns>The pass class ID: "{issuerId}.{classSuffix}"</returns>
public string CreateClass(string issuerId, string classSuffix)
{
  // Check if the class exists
  Stream responseStream = service.Genericclass
      .Get($"{issuerId}.{classSuffix}")
      .ExecuteAsStream();

  StreamReader responseReader = new StreamReader(responseStream);
  JObject jsonResponse = JObject.Parse(responseReader.ReadToEnd());

  if (!jsonResponse.ContainsKey("error"))
  {
    Console.WriteLine($"Class {issuerId}.{classSuffix} already exists!");
    return $"{issuerId}.{classSuffix}";
  }
  else if (jsonResponse["error"].Value<int>("code") != 404)
  {
    // Something else went wrong...
    Console.WriteLine(jsonResponse.ToString());
    return $"{issuerId}.{classSuffix}";
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/generic/rest/v1/genericclass
  GenericClass newClass = new GenericClass
  {
    Id = $"{issuerId}.{classSuffix}"
  };

  responseStream = service.Genericclass
      .Insert(newClass)
      .ExecuteAsStream();

  responseReader = new StreamReader(responseStream);
  jsonResponse = JObject.Parse(responseReader.ReadToEnd());

  Console.WriteLine("Class insert response");
  Console.WriteLine(jsonResponse.ToString());

  return $"{issuerId}.{classSuffix}";
}

Node.js

Чтобы начать интеграцию в Node, ознакомьтесь с полными примерами кода на GitHub .

/**
 * Create a class.
 *
 * @param {string} issuerId The issuer ID being used for this request.
 * @param {string} classSuffix Developer-defined unique ID for this pass class.
 *
 * @returns {string} The pass class ID: `${issuerId}.${classSuffix}`
 */
async createClass(issuerId, classSuffix) {
  let response;

  // Check if the class exists
  try {
    response = await this.client.genericclass.get({
      resourceId: `${issuerId}.${classSuffix}`
    });

    console.log(`Class ${issuerId}.${classSuffix} already exists!`);

    return `${issuerId}.${classSuffix}`;
  } catch (err) {
    if (err.response && err.response.status !== 404) {
      // Something else went wrong...
      console.log(err);
      return `${issuerId}.${classSuffix}`;
    }
  }

  // See link below for more information on required properties
  // https://developers.google.com/wallet/generic/rest/v1/genericclass
  let newClass = {
    'id': `${issuerId}.${classSuffix}`
  };

  response = await this.client.genericclass.insert({
    requestBody: newClass
  });

  console.log('Class insert response');
  console.log(response);

  return `${issuerId}.${classSuffix}`;
}

Идти

Чтобы начать интеграцию в Go, ознакомьтесь с нашими полными примерами кода на GitHub. Примеры кода на Github .

// Create a class.
func (d *demoGeneric) createClass(issuerId, classSuffix string) {
	genericClass := new(walletobjects.GenericClass)
	genericClass.Id = fmt.Sprintf("%s.%s", issuerId, classSuffix)
	res, err := d.service.Genericclass.Insert(genericClass).Do()
	if err != nil {
		log.Fatalf("Unable to insert class: %v", err)
	} else {
		fmt.Printf("Class insert id:\n%v\n", res.Id)
	}
}

Создайте объект пропусков

Объект Passes является экземпляром класса Passes. Чтобы создать объект Passes, необходимо предоставить следующие атрибуты:

  • classId : id класса Passes.
  • id : уникальный идентификатор вашего клиента.

    Пример кода для создания объекта Passes:

    Джава

    Чтобы начать интеграцию с Java, ознакомьтесь с нашими полными примерами кода на GitHub .

    /**
     * Create an object.
     *
     * @param issuerId The issuer ID being used for this request.
     * @param classSuffix Developer-defined unique ID for this pass class.
     * @param objectSuffix Developer-defined unique ID for this pass object.
     * @return The pass object ID: "{issuerId}.{objectSuffix}"
     */
    public String createObject(String issuerId, String classSuffix, String objectSuffix)
        throws IOException {
      // Check if the object exists
      try {
        service.genericobject().get(String.format("%s.%s", issuerId, objectSuffix)).execute();
    
        System.out.printf("Object %s.%s already exists!%n", issuerId, objectSuffix);
        return String.format("%s.%s", issuerId, objectSuffix);
      } catch (GoogleJsonResponseException ex) {
        if (ex.getStatusCode() != 404) {
          // Something else went wrong...
          ex.printStackTrace();
          return String.format("%s.%s", issuerId, objectSuffix);
        }
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/generic/rest/v1/genericobject
      GenericObject newObject =
          new GenericObject()
              .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"))
              .setCardTitle(
                  new LocalizedString()
                      .setDefaultValue(
                          new TranslatedString().setLanguage("en-US").setValue("Generic card title")))
              .setHeader(
                  new LocalizedString()
                      .setDefaultValue(
                          new TranslatedString().setLanguage("en-US").setValue("Generic header")))
              .setHexBackgroundColor("#4285f4")
              .setLogo(
                  new Image()
                      .setSourceUri(
                          new ImageUri()
                              .setUri(
                                  "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"))
                      .setContentDescription(
                          new LocalizedString()
                              .setDefaultValue(
                                  new TranslatedString()
                                      .setLanguage("en-US")
                                      .setValue("Generic card logo"))));
    
      GenericObject response = service.genericobject().insert(newObject).execute();
    
      System.out.println("Object insert response");
      System.out.println(response.toPrettyString());
    
      return response.getId();
    }
    

    PHP

    Чтобы начать интеграцию с PHP, ознакомьтесь с нашими полными примерами кода на GitHub .

    /**
     * Create an object.
     *
     * @param string $issuerId The issuer ID being used for this request.
     * @param string $classSuffix Developer-defined unique ID for this pass class.
     * @param string $objectSuffix Developer-defined unique ID for this pass object.
     *
     * @return string The pass object ID: "{$issuerId}.{$objectSuffix}"
     */
    public function createObject(string $issuerId, string $classSuffix, string $objectSuffix)
    {
      // Check if the object exists
      try {
        $this->service->genericobject->get("{$issuerId}.{$objectSuffix}");
    
        print("Object {$issuerId}.{$objectSuffix} already exists!");
        return "{$issuerId}.{$objectSuffix}";
      } catch (Google\Service\Exception $ex) {
        if (empty($ex->getErrors()) || $ex->getErrors()[0]['reason'] != 'resourceNotFound') {
          // Something else went wrong...
          print_r($ex);
          return "{$issuerId}.{$objectSuffix}";
        }
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/generic/rest/v1/genericobject
      $newObject = new GenericObject([
        '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'
        ]),
        'cardTitle' => new LocalizedString([
          'defaultValue' => new TranslatedString([
            'language' => 'en-US',
            'value' => 'Generic card title'
          ])
        ]),
        'header' => new LocalizedString([
          'defaultValue' => new TranslatedString([
            'language' => 'en-US',
            'value' => 'Generic header'
          ])
        ]),
        'hexBackgroundColor' => '#4285f4',
        'logo' => new Image([
          'sourceUri' => new ImageUri([
            'uri' => 'https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg'
          ]),
          'contentDescription' => new LocalizedString([
            'defaultValue' => new TranslatedString([
              'language' => 'en-US',
              'value' => 'Generic card logo'
            ])
          ])
        ])
      ]);
    
      $response = $this->service->genericobject->insert($newObject);
    
      print "Object insert response\n";
      print_r($response);
    
      return $response->id;
    }
    

    Питон

    Чтобы начать интеграцию с Python, ознакомьтесь с полными примерами кода на GitHub .

    def create_object(self, issuer_id: str, class_suffix: str,
                      object_suffix: str) -> str:
        """Create an object.
    
        Args:
            issuer_id (str): The issuer ID being used for this request.
            class_suffix (str): Developer-defined unique ID for the pass class.
            object_suffix (str): Developer-defined unique ID for the pass object.
    
        Returns:
            The pass object ID: f"{issuer_id}.{object_suffix}"
        """
    
        # Check if the object exists
        try:
            self.client.genericobject().get(resourceId=f'{issuer_id}.{object_suffix}').execute()
        except HttpError as e:
            if e.status_code != 404:
                # Something else went wrong...
                print(e.error_details)
                return f'{issuer_id}.{object_suffix}'
        else:
            print(f'Object {issuer_id}.{object_suffix} already exists!')
            return f'{issuer_id}.{object_suffix}'
    
        # See link below for more information on required properties
        # https://developers.google.com/wallet/generic/rest/v1/genericobject
        new_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'
            },
            'cardTitle': {
                'defaultValue': {
                    'language': 'en-US',
                    'value': 'Generic card title'
                }
            },
            'header': {
                'defaultValue': {
                    'language': 'en-US',
                    'value': 'Generic header'
                }
            },
            'hexBackgroundColor': '#4285f4',
            'logo': {
                'sourceUri': {
                    'uri':
                        'https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg'
                },
                'contentDescription': {
                    'defaultValue': {
                        'language': 'en-US',
                        'value': 'Generic card logo'
                    }
                }
            }
        }
    
        # Create the object
        response = self.client.genericobject().insert(body=new_object).execute()
    
        print('Object insert response')
        print(response)
    
        return f'{issuer_id}.{object_suffix}'
    
    

    С#

    Чтобы начать интеграцию с C#, ознакомьтесь с полными примерами кода на GitHub .

    /// <summary>
    /// Create an object.
    /// </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>
    /// <param name="objectSuffix">Developer-defined unique ID for this pass object.</param>
    /// <returns>The pass object ID: "{issuerId}.{objectSuffix}"</returns>
    public string CreateObject(string issuerId, string classSuffix, string objectSuffix)
    {
      // Check if the object exists
      Stream responseStream = service.Genericobject
          .Get($"{issuerId}.{objectSuffix}")
          .ExecuteAsStream();
    
      StreamReader responseReader = new StreamReader(responseStream);
      JObject jsonResponse = JObject.Parse(responseReader.ReadToEnd());
    
      if (!jsonResponse.ContainsKey("error"))
      {
        Console.WriteLine($"Object {issuerId}.{objectSuffix} already exists!");
        return $"{issuerId}.{objectSuffix}";
      }
      else if (jsonResponse["error"].Value<int>("code") != 404)
      {
        // Something else went wrong...
        Console.WriteLine(jsonResponse.ToString());
        return $"{issuerId}.{objectSuffix}";
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/generic/rest/v1/genericobject
      GenericObject newObject = new GenericObject
      {
        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"
        },
        CardTitle = new LocalizedString
        {
          DefaultValue = new TranslatedString
          {
            Language = "en-US",
            Value = "Generic card title"
          }
        },
        Header = new LocalizedString
        {
          DefaultValue = new TranslatedString
          {
            Language = "en-US",
            Value = "Generic header"
          }
        },
        HexBackgroundColor = "#4285f4",
        Logo = new Image
        {
          SourceUri = new ImageUri
          {
            Uri = "https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg"
          },
          ContentDescription = new LocalizedString
          {
            DefaultValue = new TranslatedString
            {
              Language = "en-US",
              Value = "Generic card logo"
            }
          },
        }
      };
    
      responseStream = service.Genericobject
          .Insert(newObject)
          .ExecuteAsStream();
      responseReader = new StreamReader(responseStream);
      jsonResponse = JObject.Parse(responseReader.ReadToEnd());
    
      Console.WriteLine("Object insert response");
      Console.WriteLine(jsonResponse.ToString());
    
      return $"{issuerId}.{objectSuffix}";
    }
    

    Node.js

    Чтобы начать интеграцию в Node, ознакомьтесь с полными примерами кода на GitHub .

    /**
     * Create an object.
     *
     * @param {string} issuerId The issuer ID being used for this request.
     * @param {string} classSuffix Developer-defined unique ID for the pass class.
     * @param {string} objectSuffix Developer-defined unique ID for the pass object.
     *
     * @returns {string} The pass object ID: `${issuerId}.${objectSuffix}`
     */
    async createObject(issuerId, classSuffix, objectSuffix) {
      let response;
    
      // Check if the object exists
      try {
        response = await this.client.genericobject.get({
          resourceId: `${issuerId}.${objectSuffix}`
        });
    
        console.log(`Object ${issuerId}.${objectSuffix} already exists!`);
    
        return `${issuerId}.${objectSuffix}`;
      } catch (err) {
        if (err.response && err.response.status !== 404) {
          // Something else went wrong...
          console.log(err);
          return `${issuerId}.${objectSuffix}`;
        }
      }
    
      // See link below for more information on required properties
      // https://developers.google.com/wallet/generic/rest/v1/genericobject
      let newObject = {
        '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'
        },
        'cardTitle': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'Generic card title'
          }
        },
        'header': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'Generic header'
          }
        },
        'hexBackgroundColor': '#4285f4',
        'logo': {
          'sourceUri': {
            'uri': 'https://storage.googleapis.com/wallet-lab-tools-codelab-artifacts-public/pass_google_logo.jpg'
          },
          'contentDescription': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'Generic card logo'
            }
          }
        }
      };
    
      response = await this.client.genericobject.insert({
        requestBody: newObject
      });
    
      console.log('Object insert response');
      console.log(response);
    
      return `${issuerId}.${objectSuffix}`;
    }
    

    Идти

    Чтобы начать интеграцию в Go, ознакомьтесь с нашими полными примерами кода на GitHub. Примеры кода на Github .

    // Create an object.
    func (d *demoGeneric) createObject(issuerId, classSuffix, objectSuffix string) {
    	genericObject := new(walletobjects.GenericObject)
    	genericObject.Id = fmt.Sprintf("%s.%s", issuerId, objectSuffix)
    	genericObject.ClassId = fmt.Sprintf("%s.%s", issuerId, classSuffix)
    	genericObject.State = "ACTIVE"
    	genericObject.Barcode = &walletobjects.Barcode{
    		Type:  "QR_CODE",
    		Value: "QR code",
    	}
    	genericObject.CardTitle = &walletobjects.LocalizedString{
    		DefaultValue: &walletobjects.TranslatedString{
    			Language: "en-us",
    			Value:    "Card title",
    		},
    	}
    	genericObject.Header = &walletobjects.LocalizedString{
    		DefaultValue: &walletobjects.TranslatedString{
    			Language: "en-us",
    			Value:    "Header",
    		},
    	}
    	genericObject.HeroImage = &walletobjects.Image{
    		SourceUri: &walletobjects.ImageUri{
    			Uri: "https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg",
    		},
    	}
    	genericObject.LinksModuleData = &walletobjects.LinksModuleData{
    		Uris: []*walletobjects.Uri{
    			&walletobjects.Uri{
    				Id:          "LINK_MODULE_URI_ID",
    				Uri:         "http://maps.google.com/",
    				Description: "Link module URI description",
    			},
    			&walletobjects.Uri{
    				Id:          "LINK_MODULE_TEL_ID",
    				Uri:         "tel:6505555555",
    				Description: "Link module tel description",
    			},
    		},
    	}
    	genericObject.ImageModulesData = []*walletobjects.ImageModuleData{
    		&walletobjects.ImageModuleData{
    			Id: "IMAGE_MODULE_ID",
    			MainImage: &walletobjects.Image{
    				SourceUri: &walletobjects.ImageUri{
    					Uri: "http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg",
    				},
    			},
    		},
    	}
    	genericObject.TextModulesData = []*walletobjects.TextModuleData{
    		&walletobjects.TextModuleData{
    			Body:   "Text module body",
    			Header: "Text module header",
    			Id:     "TEXT_MODULE_ID",
    		},
    	}
    
    	res, err := d.service.Genericobject.Insert(genericObject).Do()
    	if err != nil {
    		log.Fatalf("Unable to insert object: %v", err)
    	} else {
    		fmt.Printf("Object insert id:\n%s\n", res.Id)
    	}
    }
    
    

    После завершения объект Passes вашего клиента будет создан на сервере. Однако на данном этапе объект Passes не связан с пользователем Google или его устройством. Чтобы пропуск был связан с пользователем Google Кошелька, необходимо выдать его.