如何验证应用内购买 Android 服务器端 Java?

How to validate in-app-purchase Android server side Java?

我遵循了这个教程:https://medium.com/@infinitesimal_/doing-android-purchase-validation-api-v3-in-java-5c46fc837368

但是我做不到!我所能得到的是:

{
  "code" : 401,
  "errors" : [ {
    "domain" : "androidpublisher",
    "message" : "The current user has insufficient permissions to perform the requested operation.",
    "reason" : "permissionDenied"
  } ],
  "message" : "The current user has insufficient permissions to perform the requested operation."
}

这是我的 java 代码:

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();    

    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();        
    String applicationName = "My App";       
    String packageName = "com.my.package";
    final Set<String> scopes = Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER);
    GoogleCredential credential = new GoogleCredential.Builder()                    
        .setTransport(httpTransport)                        
        .setJsonFactory(jsonFactory)                    
        .setServiceAccountId("myAccoutId")                     
        .setServiceAccountScopes(scopes)                    
        .setServiceAccountPrivateKeyFromP12File(
          new File("/my/path"))                    
        .build();

    AndroidPublisher pub = new AndroidPublisher.Builder
            (httpTransport, jsonFactory, credential)                     
            .setApplicationName(applicationName)                    
            .build();            
        final AndroidPublisher.Purchases.Products.Get get = 
            pub.purchases()
            .products()                    
            .get(packageName, "name", "transactionId"); 
        final ProductPurchase purchase = get.execute();            
        System.out.println("Found google purchase item " + purchase.toPrettyString());

我创建了一个服务帐户并赋予了所有者角色。我去了 Google 游戏控制台,在用户和权限中我也让这个服务帐户成为管理员。

我们使用了相同的示例,并进行了一系列更改以使其工作:

  1. 使用程序包名称代替应用程序名称:将 .setApplicationName(applicationName) 替换为 .setApplicationName(packageName)

  2. 我们使用 JSON 键代替 P12: GoogleCredential credential = GoogleCredential.fromStream(IOUtils.toInputStream(jsonCert));

其中 jsonCert 是一个 JSON 密钥(服务帐户 -> Select 一个帐户 -> 创建密钥)看起来像

{
"type": "service_account",
"project_id": "api-xxx",
"private_key_id": "xxx",
"private_key": "your_private_key",
"client_email": "api-server-service-account@api-xxx.iam.gserviceaccount.com",
"client_id": "xxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/api-server-service-account%40api-xxx.iam.gserviceaccount.com"
};

更新:根据@Q Locker,Google可能需要一些时间才能在创建后提供服务帐户(在@Q Locker 的情况下最多需要 2 天).

Dmitry Bogdanovich 的回答没有帮助。

创建服务帐户不会立即生效,就我而言,我等了不到 2 天就成功了。