הגדרת הכרטיס

דרישות מוקדמות

לפני שתמשיכו, הקפידו לבצע את השלבים הבאים:

UPDATE לעומת PATCH בקשות

השיטה UPDATE מחליפה לחלוטין הגדרת אובייקט או סיווג העברה. אם משתמשים באפשרות הזו, צריך תמיד לקרוא קודם ל-method GET כדי לאחזר את המחלקה המלאה או את הגדרת האובייקט לשימוש בבקשה UPDATE. אחרת, יכול להיות שתמחקו חלקים מסיווג הכרטיס או מהאובייקט. לחלופין, משתמשים בשיטה PATCH כדי לעדכן מאפיינים ספציפיים של מחלקה או אובייקט.

העברה של הגדרות הכיתה

יש להגדיר את המאפיינים הבאים במחלקת המעבר:

  • הכתובת True הוגדרה כמיקום הenableSmartTap
  • redemptionIssuers מוגדרת לרשימת המנפיקים של מימושים שישתמשו בתכונה 'הקשה חכמה' כדי לממש אובייקטים של כרטיסים שמשויכים לכיתה הזו

מוכרים שונים (מנפיקי מימוש) יכולים לממש קבוצה מסוימת. לדוגמה, יכול להיות שאותו מועדון לקוחות, שמיוצג על ידי LoyaltyClass, יהיה זמין למימוש אצל מוכרים שונים. במקרה כזה, צריך להגדיר את המחלקה כך שתכלול את המזהים של כל מנפיקי המימוש שעומדים בדרישות.

אפשר לעדכן את סוג הכרטיס במסוף Google Pay ו-Wallet, או דרך Google Wallet API. דוגמת הקוד הבאה מדגימה עדכון של מחלקה כדי לאפשר את השימוש בתכונה 'הקשה חכמה' ולהוסיף כמה מנפיקי מימושים:

Java

/**
 * Enable Smart Tap for a pass 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}"
 * @throws IOException
 */
public String EnableSmartTap(String issuerId, String classSuffix) throws IOException {
  // Check if the class exists
  try {
    service.genericclass().get(String.format("%s.%s", issuerId, classSuffix)).execute();
  } catch (GoogleJsonResponseException ex) {
    if (ex.getStatusCode() == 404) {
      // Class does not exist
      System.out.println(String.format("Class %s.%s not found!", issuerId, classSuffix));
      return String.format("%s.%s", issuerId, classSuffix);
    } else {
      // Something else went wrong...
      ex.printStackTrace();
      return String.format("%s.%s", issuerId, classSuffix);
    }
  }

  // Patch the class by enabling Smart Tap and adding Redemption Issuers
  GenericClass patchBody =
      new GenericClass()
          .setEnableSmartTap(true)
          .setRedemptionIssuers(
              new ArrayList<Long>(
                  Arrays.asList(
                      // Add any Redemption Issuer IDs
                      1234000000087654321L, 1234000000012345678L)));

  GenericClass response =
      service
          .genericclass()
          .patch(String.format("%s.%s", issuerId, classSuffix), patchBody)
          .execute();

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

  return response.getId();
}

PHP

/**
 * Enable Smart Tap for a pass 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 enableSmartTap(string $issuerId, string $classSuffix)
{
  // Check if the class exists
  try {
    $this->service->genericclass->get("{$issuerId}.{$classSuffix}");
  } catch (Google\Service\Exception $ex) {
    if (!empty($ex->getErrors()) && $ex->getErrors()[0]['reason'] == 'classNotFound') {
      // Class does not exist
      print("Class {$issuerId}.{$classSuffix} not found!");
      return "{$issuerId}.{$classSuffix}";
    } else {
      // Something else went wrong...
      print_r($ex);
      return "{$issuerId}.{$classSuffix}";
    }
  }

  // Patch the class by enabling Smart Tap and adding Redemption Issuers
  $patchBody = new Google_Service_Walletobjects_GenericClass([
    'enableSmartTap' => true,
    'redemptionIssuers' => [
      // Add any Redemption Issuer IDs
      '1234000000087654321',
      '1234000000012345678'
    ]
  ]);

  $response = $this->service->genericclass->patch("{$issuerId}.{$classSuffix}", $patchBody);

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

  return $response->id;
}

Python

def enable_smart_tap(self, issuer_id: str, class_suffix: str) -> str:
    """Enable Smart Tap for a pass 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
    response = self.http_client.get(
        url=f'{self.class_url}/{issuer_id}.{class_suffix}')

    if response.status_code == 404:
        print(f'Class {issuer_id}.{class_suffix} not found!')
        return f'{issuer_id}.{class_suffix}'
    elif response.status_code != 200:
        # Something else went wrong...
        print(response.text)
        return f'{issuer_id}.{class_suffix}'

    # Patch the class by enabling Smart Tap and adding Redemption Issuers
    patch_body = {
        'enableSmartTap':
            True,
        'redemptionIssuers': [
            # Add any Redemption Issuer IDs
            '1234000000087654321',
            '1234000000012345678'
        ]
    }

    response = self.http_client.patch(
        url=f'{self.class_url}/{issuer_id}.{class_suffix}', json=patch_body)

    print('Class patch response')
    print(response.text)

    return f'{issuer_id}.{class_suffix}'

C#

/// <summary>
/// Enable Smart Tap for a pass 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 EnableSmartTap(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"))
  {
    if (jsonResponse["error"].Value<int>("code") == 404)
    {
      // Class does not exist
      Console.WriteLine($"Class {issuerId}.{classSuffix} not found!");
      return $"{issuerId}.{classSuffix}";
    }
    else
    {
      // Something else went wrong...
      Console.WriteLine(jsonResponse.ToString());
      return $"{issuerId}.{classSuffix}";
    }
  }

  // Patch the class by enabling Smart Tap and adding Redemption Issuers
  GenericClass patchClass = new GenericClass
  {
    EnableSmartTap = true,
    RedemptionIssuers = new List<Int64?>
    {
      // Add any Redemption Issuer IDs
      1234000000087654321,
      1234000000012345678
    }
  };

  responseStream = service.Genericclass
      .Patch(patchClass, $"{issuerId}.{classSuffix}")
      .ExecuteAsStream();

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

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

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

Node.js

/**
 * Enable Smart Tap for a pass 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 enableSmartTap(issuerId, classSuffix) {
  // Check if the class exists
  try {
    await this.httpClient.request({
      url: `${this.classUrl}/${issuerId}.${classSuffix}`,
      method: 'GET'
    });
  } catch (err) {
    if (err.response && err.response.status === 404) {
      console.log(`Class ${issuerId}.${classSuffix} not found!`);
      return `${issuerId}.${classSuffix}`;
    } else {
      // Something else went wrong...
      console.log(err);
      return `${issuerId}.${classSuffix}`;
    }
  }

  // Patch the class by enabling Smart Tap and adding Redemption Issuers
  let patchBody = {
    'enableSmartTap': true,
    'redemptionIssuers': [
      // Add any Redemption Issuer IDs
      '1234000000087654321',
      '1234000000012345678'
    ]
  };

  response = await this.httpClient.request({
    url: `${this.classUrl}/${issuerId}.${classSuffix}`,
    method: 'PATCH',
    data: patchBody
  });

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

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

העברה של הגדרת האובייקט

באובייקט ההעברה, יש להגדיר את הערך smartTapRedemptionValue. דוגמת הקוד הבאה מדגימה עדכון של אובייקט Pass כך שיכלול את הנתונים שיישלחו למסוף של המוכר במהלך הקשה ב-NFC:

Java

/**
 * Enable Smart Tap for a pass object.
 *
 * @param issuerId The issuer ID being used for this request.
 * @param objectSuffix Developer-defined unique ID for this pass object.
 * @return The pass object ID: "{issuerId}.{objectSuffix}"
 * @throws IOException
 */
public String EnableSmartTap(String issuerId, String objectSuffix) throws IOException {
  // Check if the object exists
  try {
    service.genericobject().get(String.format("%s.%s", issuerId, objectSuffix)).execute();
  } catch (GoogleJsonResponseException ex) {
    if (ex.getStatusCode() == 404) {
      // Object does not exist
      System.out.println(String.format("Object %s.%s not found!", issuerId, objectSuffix));
      return String.format("%s.%s", issuerId, objectSuffix);
    } else {
      // Something else went wrong...
      ex.printStackTrace();
      return String.format("%s.%s", issuerId, objectSuffix);
    }
  }

  // Patch the object by setting the Smart Tap redemption value
  GenericObject patchBody =
      new GenericObject().setSmartTapRedemptionValue("Value to be sent to merchant terminals");

  GenericObject response =
      service
          .genericobject()
          .patch(String.format("%s.%s", issuerId, objectSuffix), patchBody)
          .execute();

  System.out.println("Object patch response");
  System.out.println(response.toPrettyString());

  return String.format("%s.%s", issuerId, objectSuffix);
}

PHP

/**
 * Enable Smart Tap for a pass object.
 *
 * @param string $issuerId The issuer ID being used for this request.
 * @param string $objectSuffix Developer-defined unique ID for this pass object.
 *
 * @return string The pass object ID: "{$issuerId}.{$objectSuffix}"
 */
public function enableSmartTap(string $issuerId, string $objectSuffix)
{
  // Check if the object exists
  try {
    $this->service->genericobject->get("{$issuerId}.{$objectSuffix}");
  } catch (Google\Service\Exception $ex) {
    if (!empty($ex->getErrors()) && $ex->getErrors()[0]['reason'] == 'resourceNotFound') {
      print("Object {$issuerId}.{$objectSuffix} not found!");
      return "{$issuerId}.{$objectSuffix}";
    } else {
      // Something else went wrong...
      print_r($ex);
      return "{$issuerId}.{$objectSuffix}";
    }
  }

  // Patch the object by setting the Smart Tap redemption value
  $patchBody = new Google_Service_Walletobjects_GenericObject([
    'smartTapRedemptionValue' => 'Value to be sent to merchant terminals'
  ]);

  $response = $this->service->genericobject->patch("{$issuerId}.{$objectSuffix}", $patchBody);

  print "Object patch response\n";
  print_r($response);

  return $response->id;
}

Python

def enable_smart_tap(self, issuer_id: str, object_suffix: str) -> str:
    """Enable Smart Tap for a pass object.

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

    Returns:
        The pass object ID: f"{issuer_id}.{object_suffix}"
    """

    # Check if the object exists
    response = self.http_client.get(
        url=f'{self.object_url}/{issuer_id}.{object_suffix}')

    if response.status_code == 404:
        print(f'Object {issuer_id}.{object_suffix} not found!')
        return f'{issuer_id}.{object_suffix}'
    elif response.status_code != 200:
        # Something else went wrong...
        print(response.text)
        return f'{issuer_id}.{object_suffix}'

    # Patch the object by setting the Smart Tap redemption value
    patch_body = {
        'smartTapRedemptionValue': 'Value to be sent to merchant terminals'
    }

    response = self.http_client.patch(
        url=f'{self.object_url}/{issuer_id}.{object_suffix}',
        json=patch_body)

    print('Object patch response')
    print(response.text)

    return f'{issuer_id}.{object_suffix}'

C#

/// <summary>
/// Enable Smart Tap for a pass object.
/// </summary>
/// <param name="issuerId">The issuer ID being used for this request.</param>
/// <param name="objectSuffix">Developer-defined unique ID for this pass object.</param>
/// <returns>The pass object ID: "{issuerId}.{objectSuffix}"</returns>
public string EnableSmartTap(string issuerId, 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"))
  {
    if (jsonResponse["error"].Value<int>("code") == 404)
    {
      // Object does not exist
      Console.WriteLine($"Object {issuerId}.{objectSuffix} not found!");
      return $"{issuerId}.{objectSuffix}";
    }
    else
    {
      // Something else went wrong...
      Console.WriteLine(jsonResponse.ToString());
      return $"{issuerId}.{objectSuffix}";
    }
  }

  // Patch the object by setting the Smart Tap redemption value
  GenericObject patchObject = new GenericObject
  {
    SmartTapRedemptionValue = "Value to be sent to merchant terminals"
  };

  responseStream = service.Genericobject
      .Patch(patchObject, $"{issuerId}.{objectSuffix}")
      .ExecuteAsStream();

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

  Console.WriteLine("Object patch response");
  Console.WriteLine(jsonResponse.ToString());

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

Node.js

/**
 * Enable Smart Tap for a pass object.
 *
 * @param {string} issuerId The issuer ID being used for this request.
 * @param {string} objectSuffix Developer-defined unique ID for this pass object.
 *
 * @returns {string} The pass object ID: `${issuerId}.${objectSuffix}`
 */
async enableSmartTap(issuerId, objectSuffix) {
  // Check if the object exists
  try {
    await this.httpClient.request({
      url: `${this.objectUrl}/${issuerId}.${objectSuffix}`,
      method: 'GET'
    });
  } catch (err) {
    if (err.response && err.response.status === 404) {
      console.log(`Object ${issuerId}.${objectSuffix} not found!`);
      return `${issuerId}.${objectSuffix}`;
    } else {
      // Something else went wrong...
      console.log(err);
      return `${issuerId}.${objectSuffix}`;
    }
  }

  // Patch the object by setting the Smart Tap redemption value
  let patchBody = {
    'smartTapRedemptionValue': 'Value to be sent to merchant terminals'
  };

  response = await this.httpClient.request({
    url: `${this.objectUrl}/${issuerId}.${objectSuffix}`,
    method: 'PATCH',
    data: patchBody
  });

  console.log('Object patch response');
  console.log(response);

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