Adicionar vários tipos de cartão

Para adicionar vários cartões à conta da Carteira do Google do usuário, clique no botão "Adicionar à Carteira do Google". Cada cartão pode ser de um tipo diferente, exceto cartões de vacinação e registros de teste. Por exemplo, é possível adicionar um ingresso de evento e uma oferta em um determinado JWT, como mostrado abaixo.

{
  "aud": "google",
  "iat": “YOUR_ISSUER_ID”,
  "iss": "YOUR_SERVICE_ACCOUNT",
  "typ": "savetogooglepay",
  "payload": {
    "offerObjects": [
      {
        "classId": "YOUR_ISSUER_ID.offClassId",
        "id": "YOUR_ISSUER_ID.offer"
      }
    ],
    "eventTicketObjects": [
      {
        "classId": "YOUR_ISSUER_ID.evClassId",
        "id": "YOUR_ISSUER_ID.event"
      }
    ]
  },
  "origins": []
}

Quando o usuário clicar no link, ele vai conferir o número de cartões salvos ao adicionar os cartões ao dispositivo. Depois de adicionados, os cartões aparecem na carteira.

O exemplo de código a seguir mostra como diferentes tipos de cartões podem ser adicionados ao mesmo JWT.

Java

/**
 * Generate a signed JWT that references an existing pass object.
 *
 * <p>When the user opens the "Add to Google Wallet" URL and saves the pass to their wallet, the
 * pass objects defined in the JWT are added to the user's Google Wallet app. This allows the user
 * to save multiple pass objects in one API call.
 *
 * <p>The objects to add must follow the below format:
 *
 * <p>{ 'id': 'ISSUER_ID.OBJECT_SUFFIX', 'classId': 'ISSUER_ID.CLASS_SUFFIX' }
 *
 * @param issuerId The issuer ID being used for this request.
 * @return An "Add to Google Wallet" link.
 */
public String createJWTExistingObjects(String issuerId) {
  // Multiple pass types can be added at the same time
  // At least one type must be specified in the JWT claims
  // Note: Make sure to replace the placeholder class and object suffixes
  HashMap<String, Object> objectsToAdd = new HashMap<String, Object>();

  // Event tickets
  objectsToAdd.put(
      "eventTicketObjects",
          List.of(
                  new EventTicketObject()
                          .setId(String.format("%s.%s", issuerId, "EVENT_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "EVENT_CLASS_SUFFIX"))));

  // Boarding passes
  objectsToAdd.put(
      "flightObjects",
          List.of(
                  new FlightObject()
                          .setId(String.format("%s.%s", issuerId, "FLIGHT_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "FLIGHT_CLASS_SUFFIX"))));

  // Generic passes
  objectsToAdd.put(
      "genericObjects",
          List.of(
                  new GenericObject()
                          .setId(String.format("%s.%s", issuerId, "GENERIC_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "GENERIC_CLASS_SUFFIX"))));

  // Gift cards
  objectsToAdd.put(
      "giftCardObjects",
          List.of(
                  new GiftCardObject()
                          .setId(String.format("%s.%s", issuerId, "GIFT_CARD_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "GIFT_CARD_CLASS_SUFFIX"))));

  // Loyalty cards
  objectsToAdd.put(
      "loyaltyObjects",
          List.of(
                  new LoyaltyObject()
                          .setId(String.format("%s.%s", issuerId, "LOYALTY_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "LOYALTY_CLASS_SUFFIX"))));

  // Offers
  objectsToAdd.put(
      "offerObjects",
          List.of(
                  new OfferObject()
                          .setId(String.format("%s.%s", issuerId, "OFFER_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "OFFER_CLASS_SUFFIX"))));

  // Transit passes
  objectsToAdd.put(
      "transitObjects",
          List.of(
                  new TransitObject()
                          .setId(String.format("%s.%s", issuerId, "TRANSIT_OBJECT_SUFFIX"))
                          .setClassId(String.format("%s.%s", issuerId, "TRANSIT_CLASS_SUFFIX"))));

  // Create the JWT as a HashMap object
  HashMap<String, Object> claims = new HashMap<String, Object>();
  claims.put("iss", ((ServiceAccountCredentials) credentials).getClientEmail());
  claims.put("aud", "google");
  claims.put("origins", List.of("www.example.com"));
  claims.put("typ", "savetowallet");
  claims.put("payload", objectsToAdd);

  // The service account credentials are used to sign the JWT
  Algorithm algorithm =
      Algorithm.RSA256(
          null, (RSAPrivateKey) ((ServiceAccountCredentials) credentials).getPrivateKey());
  String token = JWT.create().withPayload(claims).sign(algorithm);

  System.out.println("Add to Google Wallet link");
  System.out.printf("https://pay.google.com/gp/v/save/%s%n", token);

  return String.format("https://pay.google.com/gp/v/save/%s", token);
}

PHP

/**
 * Generate a signed JWT that references an existing pass object.
 *
 * When the user opens the "Add to Google Wallet" URL and saves the pass to
 * their wallet, the pass objects defined in the JWT are added to the
 * user's Google Wallet app. This allows the user to save multiple pass
 * objects in one API call.
 *
 * The objects to add must follow the below format:
 *
 *  {
 *    'id': 'ISSUER_ID.OBJECT_SUFFIX',
 *    'classId': 'ISSUER_ID.CLASS_SUFFIX'
 *  }
 *
 * @param string $issuerId The issuer ID being used for this request.
 *
 * @return string An "Add to Google Wallet" link.
 */
public function createJwtExistingObjects(string $issuerId)
{
  // Multiple pass types can be added at the same time
  // At least one type must be specified in the JWT claims
  // Note: Make sure to replace the placeholder class and object suffixes
  $objectsToAdd = [
    // Event tickets
    'eventTicketObjects' => [
      [
        'id' => "{$issuerId}.EVENT_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.EVENT_CLASS_SUFFIX"
      ]
    ],

    // Boarding passes
    'flightObjects' => [
      [
        'id' => "{$issuerId}.FLIGHT_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.FLIGHT_CLASS_SUFFIX"
      ]
    ],

    // Generic passes
    'genericObjects' => [
      [
        'id' => "{$issuerId}.GENERIC_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.GENERIC_CLASS_SUFFIX"
      ]
    ],

    // Gift cards
    'giftCardObjects' => [
      [
        'id' => "{$issuerId}.GIFT_CARD_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.GIFT_CARD_CLASS_SUFFIX"
      ]
    ],

    // Loyalty cards
    'loyaltyObjects' => [
      [
        'id' => "{$issuerId}.LOYALTY_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.LOYALTY_CLASS_SUFFIX"
      ]
    ],

    // Offers
    'offerObjects' => [
      [
        'id' => "{$issuerId}.OFFER_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.OFFER_CLASS_SUFFIX"
      ]
    ],

    // Tranist passes
    'transitObjects' => [
      [
        'id' => "{$issuerId}.TRANSIT_OBJECT_SUFFIX",
        'classId' => "{$issuerId}.TRANSIT_CLASS_SUFFIX"
      ]
    ]
  ];

  // The service account credentials are used to sign the JWT
  $serviceAccount = json_decode(file_get_contents($this->keyFilePath), true);

  // Create the JWT as an array of key/value pairs
  $claims = [
    'iss' => $serviceAccount['client_email'],
    'aud' => 'google',
    'origins' => ['www.example.com'],
    'typ' => 'savetowallet',
    'payload' => $objectsToAdd
  ];

  $token = JWT::encode(
    $claims,
    $serviceAccount['private_key'],
    'RS256'
  );

  print "Add to Google Wallet link\n";
  print "https://pay.google.com/gp/v/save/{$token}";

  return "https://pay.google.com/gp/v/save/{$token}";
}

Python

def create_jwt_existing_objects(self, issuer_id: str) -> str:
    """Generate a signed JWT that references an existing pass object.

    When the user opens the "Add to Google Wallet" URL and saves the pass to
    their wallet, the pass objects defined in the JWT are added to the
    user's Google Wallet app. This allows the user to save multiple pass
    objects in one API call.

    The objects to add must follow the below format:

    {
        'id': 'ISSUER_ID.OBJECT_SUFFIX',
        'classId': 'ISSUER_ID.CLASS_SUFFIX'
    }

    Args:
        issuer_id (str): The issuer ID being used for this request.

    Returns:
        An "Add to Google Wallet" link
    """

    # Multiple pass types can be added at the same time
    # At least one type must be specified in the JWT claims
    # Note: Make sure to replace the placeholder class and object suffixes
    objects_to_add = {
        # Event tickets
        'eventTicketObjects': [{
            'id': f'{issuer_id}.EVENT_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.EVENT_CLASS_SUFFIX'
        }],

        # Boarding passes
        'flightObjects': [{
            'id': f'{issuer_id}.FLIGHT_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.FLIGHT_CLASS_SUFFIX'
        }],

        # Generic passes
        'genericObjects': [{
            'id': f'{issuer_id}.GENERIC_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.GENERIC_CLASS_SUFFIX'
        }],

        # Gift cards
        'giftCardObjects': [{
            'id': f'{issuer_id}.GIFT_CARD_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.GIFT_CARD_CLASS_SUFFIX'
        }],

        # Loyalty cards
        'loyaltyObjects': [{
            'id': f'{issuer_id}.LOYALTY_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.LOYALTY_CLASS_SUFFIX'
        }],

        # Offers
        'offerObjects': [{
            'id': f'{issuer_id}.OFFER_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.OFFER_CLASS_SUFFIX'
        }],

        # Transit passes
        'transitObjects': [{
            'id': f'{issuer_id}.TRANSIT_OBJECT_SUFFIX',
            'classId': f'{issuer_id}.TRANSIT_CLASS_SUFFIX'
        }]
    }

    # Create the JWT claims
    claims = {
        'iss': self.credentials.service_account_email,
        'aud': 'google',
        'origins': ['www.example.com'],
        'typ': 'savetowallet',
        'payload': objects_to_add
    }

    # The service account credentials are used to sign the JWT
    signer = crypt.RSASigner.from_service_account_file(self.key_file_path)
    token = jwt.encode(signer, claims).decode('utf-8')

    print('Add to Google Wallet link')
    print(f'https://pay.google.com/gp/v/save/{token}')

    return f'https://pay.google.com/gp/v/save/{token}'

C#

/// <summary>
/// Generate a signed JWT that references an existing pass object.
/// <para />
/// When the user opens the "Add to Google Wallet" URL and saves the pass to
/// their wallet, the pass objects defined in the JWT are added to the user's
/// Google Wallet app. This allows the user to save multiple pass objects in
/// one API call.
/// <para />
/// The objects to add must follow the below format:
/// <para />
/// { 'id': 'ISSUER_ID.OBJECT_SUFFIX', 'classId': 'ISSUER_ID.CLASS_SUFFIX' }
/// <para />
/// The Google Wallet C# library uses Newtonsoft.Json.JsonPropertyAttribute
/// to specify the property names when converting objects to JSON. The
/// Newtonsoft.Json.JsonConvert.SerializeObject method will automatically
/// serialize the object with the right property names.
/// </summary>
/// <param name="issuerId">The issuer ID being used for this request.</param>
/// <returns>An "Add to Google Wallet" link.</returns>
public string CreateJWTExistingObjects(string issuerId)
{
  // Ignore null values when serializing to/from JSON
  JsonSerializerSettings excludeNulls = new JsonSerializerSettings()
  {
    NullValueHandling = NullValueHandling.Ignore
  };

  // Multiple pass types can be added at the same time
  // At least one type must be specified in the JWT claims
  // Note: Make sure to replace the placeholder class and object suffixes
  Dictionary<string, Object> objectsToAdd = new Dictionary<string, Object>();

  // Event tickets
  objectsToAdd.Add("eventTicketObjects", new List<EventTicketObject>
  {
    new EventTicketObject
    {
      Id = $"{issuerId}.EVENT_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.EVENT_CLASS_SUFFIX"
    }
  });

  // Boarding passes
  objectsToAdd.Add("flightObjects", new List<FlightObject>
  {
    new FlightObject
    {
      Id = $"{issuerId}.FLIGHT_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.FLIGHT_CLASS_SUFFIX"
    }
  });

  // Generic passes
  objectsToAdd.Add("genericObjects", new List<GenericObject>
  {
    new GenericObject
    {
      Id = $"{issuerId}.GENERIC_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.GENERIC_CLASS_SUFFIX"
    }
  });

  // Gift cards
  objectsToAdd.Add("giftCardObjects", new List<GiftCardObject>
  {
    new GiftCardObject
    {
      Id = $"{issuerId}.GIFT_CARD_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.GIFT_CARD_CLASS_SUFFIX"
    }
  });

  // Loyalty cards
  objectsToAdd.Add("loyaltyObjects", new List<LoyaltyObject>
  {
    new LoyaltyObject
    {
      Id = $"{issuerId}.LOYALTY_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.LOYALTY_CLASS_SUFFIX"
    }
  });

  // Offers
  objectsToAdd.Add("offerObjects", new List<OfferObject>
  {
    new OfferObject
    {
      Id = $"{issuerId}.OFFER_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.OFFER_CLASS_SUFFIX"
    }
  });

  // Transit passes
  objectsToAdd.Add("transitObjects", new List<TransitObject>
  {
    new TransitObject
    {
      Id = $"{issuerId}.TRANSIT_OBJECT_SUFFIX",
      ClassId = $"{issuerId}.TRANSIT_CLASS_SUFFIX"
    }
  });

  // Create a JSON representation of the payload
  JObject serializedPayload = JObject.Parse(
      JsonConvert.SerializeObject(objectsToAdd, excludeNulls));

  // Create the JWT as a JSON object
  JObject jwtPayload = JObject.Parse(JsonConvert.SerializeObject(new
  {
    iss = credentials.Id,
    aud = "google",
    origins = new string[]
    {
      "www.example.com"
    },
    typ = "savetowallet",
    payload = serializedPayload
  }));

  // Deserialize into a JwtPayload
  JwtPayload claims = JwtPayload.Deserialize(jwtPayload.ToString());

  // The service account credentials are used to sign the JWT
  RsaSecurityKey key = new RsaSecurityKey(credentials.Key);
  SigningCredentials signingCredentials = new SigningCredentials(
      key, SecurityAlgorithms.RsaSha256);
  JwtSecurityToken jwt = new JwtSecurityToken(
      new JwtHeader(signingCredentials), claims);
  string token = new JwtSecurityTokenHandler().WriteToken(jwt);

  Console.WriteLine("Add to Google Wallet link");
  Console.WriteLine($"https://pay.google.com/gp/v/save/{token}");

  return $"https://pay.google.com/gp/v/save/{token}";
}

Node.js

/**
 * Generate a signed JWT that references an existing pass object.
 *
 * When the user opens the "Add to Google Wallet" URL and saves the pass to
 * their wallet, the pass objects defined in the JWT are added to the
 * user's Google Wallet app. This allows the user to save multiple pass
 * objects in one API call.
 *
 * The objects to add must follow the below format:
 *
 *  {
 *    'id': 'ISSUER_ID.OBJECT_SUFFIX',
 *    'classId': 'ISSUER_ID.CLASS_SUFFIX'
 *  }
 *
 * @param {string} issuerId The issuer ID being used for this request.
 *
 * @returns {string} An "Add to Google Wallet" link.
 */
createJwtExistingObjects(issuerId) {
  // Multiple pass types can be added at the same time
  // At least one type must be specified in the JWT claims
  // Note: Make sure to replace the placeholder class and object suffixes
  let objectsToAdd = {
    // Event tickets
    'eventTicketObjects': [{
      'id': `${issuerId}.EVENT_OBJECT_SUFFIX`,
      'classId': `${issuerId}.EVENT_CLASS_SUFFIX`
    }],

    // Boarding passes
    'flightObjects': [{
      'id': `${issuerId}.FLIGHT_OBJECT_SUFFIX`,
      'classId': `${issuerId}.FLIGHT_CLASS_SUFFIX`
    }],

    // Generic passes
    'genericObjects': [{
      'id': `${issuerId}.GENERIC_OBJECT_SUFFIX`,
      'classId': `${issuerId}.GENERIC_CLASS_SUFFIX`
    }],

    // Gift cards
    'giftCardObjects': [{
      'id': `${issuerId}.GIFT_CARD_OBJECT_SUFFIX`,
      'classId': `${issuerId}.GIFT_CARD_CLASS_SUFFIX`
    }],

    // Loyalty cards
    'loyaltyObjects': [{
      'id': `${issuerId}.LOYALTY_OBJECT_SUFFIX`,
      'classId': `${issuerId}.LOYALTY_CLASS_SUFFIX`
    }],

    // Offers
    'offerObjects': [{
      'id': `${issuerId}.OFFER_OBJECT_SUFFIX`,
      'classId': `${issuerId}.OFFER_CLASS_SUFFIX`
    }],

    // Transit passes
    'transitObjects': [{
      'id': `${issuerId}.TRANSIT_OBJECT_SUFFIX`,
      'classId': `${issuerId}.TRANSIT_CLASS_SUFFIX`
    }]
  }

  // Create the JWT claims
  let claims = {
    iss: this.credentials.client_email,
    aud: 'google',
    origins: ['www.example.com'],
    typ: 'savetowallet',
    payload: objectsToAdd
  };

  // The service account credentials are used to sign the JWT
  let token = jwt.sign(claims, this.credentials.private_key, { algorithm: 'RS256' });

  console.log('Add to Google Wallet link');
  console.log(`https://pay.google.com/gp/v/save/${token}`);

  return `https://pay.google.com/gp/v/save/${token}`;
}