本指南介绍了如何使用 Google 钱包 API 进行回调。当卡券创建或删除时,Google 可以对您选择的 HTTPS 端点执行回调。 此回调是特定于类的,包含有关事件的数据,例如类、对象和事件类型。 这可用于跟踪发生的用户添加和删除次数。例如,您可以配置回调,以将事件发送到分析应用,从而跟踪促销活动期间的客户互动情况。
前提条件
在开始之前,请查看以下前提条件:
- 设置一个处理 POST 请求的 HTTPS 端点。此端点需要公开。
-
以编程方式更新每个类的回调端点。请在 REST API 中按类查看
callbackOptions属性。 - 建议:使用 Tink 库来验证签名。
实现回调
对于用户对对象执行的每个添加或删除操作,Google 都会使用每个类网址的添加或删除操作详情,对商家进行回调。商家需要先使用公钥验证消息的真实性。回调验证消息后,即可用于下游操作。
验证签名
我们建议您在实现 HTTPS 端点时使用 Tink 库验证消息签名。Tink 库提供 PaymentMethodTokenRecipient,这是一个可自动验证签名并在成功验证后返回实际消息的实用程序。
以下示例展示了如何使用 Tink 库实现 PaymentMethodTokenRecipient:
import java.io.IOException; import javax.servlet.http.*; import com.google.common.io.CharStreams; import com.google.crypto.tink.apps.paymentmethodtoken.*; // Replace ISSUER_ID with your issuer id private static final String RECIPIENT_ID = "ISSUER_ID"; private static final String PUBLIC_KEY_URL = "https://pay.google.com/gp/m/issuer/keys"; private static final String SENDER_ID = "GooglePayPasses"; private static final String PROTOCOL = "ECv2SigningOnly"; private static final GooglePaymentsPublicKeysManager keysManager = new GooglePaymentsPublicKeysManager.Builder() .setKeysUrl(PUBLIC_KEY_URL) .build(); public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { // Extract signed message with signature from POST request body. String signedMessage = CharStreams.toString(request.getReader()); PaymentMethodTokenRecipient recipient = new PaymentMethodTokenRecipient.Builder() .protocolVersion(PROTOCOL) .fetchSenderVerifyingKeysWith(keysManager) .senderId(SENDER_ID) .recipientId(RECIPIENT_ID) .build(); String serializedJsonMessage = recipient.unseal(signedMessage); // Use serializedJsonMessage to extract the details } catch (Exception e) { // Handle the error } }
预期的消息格式
消息格式是序列化为字符串的 JSON,包含以下属性:
| 标识符 | 说明 |
|---|---|
classId |
完全限定的类 ID。请使用以下格式: <issuer_id.class_id> |
objectId |
完全限定的对象 ID。请使用以下格式: <issuer_id.object_id> |
expTimeMillis |
自纪元开始的有效期(以毫秒为单位)。在有效期之后,该消息应被视为无效。 |
eventType |
对于 DELETE 和 SAVE,可以是 del 或 save。
|
nonce |
用于跟踪任何重复递送的 Nonce。 |
处理来自 Google 服务器的请求
下面列出了一些发送到回调端点的请求标头中的关键字段:
- User-Agent:
Googlebot - Content-Type:
application/json
配置服务器,使其不拒绝请求。为此,您可以在 robots.txt 中设置以下内容:
User-agent: Googlebot Disallow:
重试
系统会尽最大努力进行回调。Google 将使用常见的重试策略,以便在回调端点不响应或出现间歇性中断的情况下保持弹性,并会优雅地退避重试。
递送重复
在某些情况下可能会有重复的递送。我们建议您使用 nonce 来消除重复递送。