使用Google Play Developer API进行服务器端授权?

时间:2018-01-09 20:28:26

标签: google-api google-oauth google-oauth2 google-oauth-java-client

需要授权才能从Google Play Developer API获取信息。

我知道如何使用Postman执行此操作,但实现授权更加繁琐(重定向网址,处理重定向等等...) 这些是您已在Google Developer API Console内设置身份验证数据的步骤。

1.) GET https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=http://www.myurl.com/oauth2callback&client_id=1234567890.apps.googleusercontent.com
2.) get code which was sent to redirect url. 
3.) POST https://accounts.google.com/o/oauth2/token
with
    grant_type:authorization_code
    code:[the code I got before]
    client_id:1234567890.apps.googleusercontent.com
    client_secret:[my client secret]
4.) Invoke GET https://www.googleapis.com/androidpublisher/v2/applications/packageName/purchases/subscriptions/subscriptionId/tokens/token
with:
  Scope: https://www.googleapis.com/auth/androidpublisher
and:
  access_token as query parameter I got before.

现在我想以编程方式完成所有这些操作。显然不那么容易。我认为Google API Client Libraries会有所帮助,但我不知道,这些lib如何帮助我处理我的用例。
例如GoogleAuthorizationCodeFlow之类的类在请求时期望用户ID,但此时我不一定有一个,所以我想知道如何以干净的方式使用这个API。

使用某些API访问Google Play Developer API,是否有更简洁/可编程处理OAuth2.0的方法?否则我必须手动实现它。

2 个答案:

答案 0 :(得分:4)

经过多次头疼(就像使用Google API和服务一样),我想出了如何使用现有的API访问Google Play Developer API信息(如结算)。

1。)在Developer API Console中创建服务帐户(JSON)密钥: enter image description here

2。)下载此service-account-private-key.json文件(不要将其与OAuth2.0客户端密钥文件混淆!)。

3。)在Google Play开发者控制台中,转到Settings -> Users & Permissions -> Invite New User,并从下载的文件中将新用户的电子邮件设置为 client_email 。通过此视图中的复选框分配您要为此用户提供的访问权限(例如,查看财务数据')。

4.。)为项目添加适当的依赖项(版本...... - 1.23.0对我不起作用):

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-androidpublisher</artifactId>
    <version>v2-rev50-1.22.0</version>
</dependency>

5.)将service-account-private-key.json文件加载到您的应用程序中。就我而言,它是一个网络服务器:

@Singleton
@Startup
public class WebserverConfiguration
{
    private String serviceAccountPrivateKeyFilePath;

    /** Global instance of the HTTP transport. */
    public static HttpTransport HTTP_TRANSPORT;

    /** Global instance of the JSON factory. */
    public static JsonFactory JSON_FACTORY;

    private GoogleCredential credential;

    @PostConstruct
    public void init()
    {
        assignServiceAccountFileProperty();
        initGoogleCredentials();
    }

    public String getServiceAccountPrivateKeyFilePath()
    {
        return serviceAccountPrivateKeyFilePath;
    }

    public GoogleCredential getCredential()
    {
        return credential;
    }

    private void initGoogleCredentials()
    {
        try
        {
            newTrustedTransport();
            newJsonFactory();

            String serviceAccountContent = new String(Files.readAllBytes(Paths.get(getServiceAccountPrivateKeyFilePath())));
            InputStream inputStream = new ByteArrayInputStream(serviceAccountContent.getBytes());

            credential = GoogleCredential.fromStream(inputStream).createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER));

        }
        catch (IOException | GeneralSecurityException e)
        {
            throw new InitializationException(e);
        }
    }

    private void newJsonFactory()
    {
        JSON_FACTORY = JacksonFactory.getDefaultInstance();
    }

    private void assignServiceAccountFileProperty()
    {
        serviceAccountPrivateKeyFilePath = System.getProperty("service.account.file.path");
        if (serviceAccountPrivateKeyFilePath == null)
        {
            throw new IllegalArgumentException("service.account.file.path UNKNOWN - configure it as VM startup parameter in Wildfly");
        }
    }

    private static void newTrustedTransport() throws GeneralSecurityException, IOException
    {
        if (HTTP_TRANSPORT == null)
        {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        }
    }
}

6。)现在,我可以获取Google Play Developer API信息,例如评论:

private void invokeGoogleApi() throws IOException
{       
    AndroidPublisher publisher = new AndroidPublisher.Builder(WebserverConfiguration.HTTP_TRANSPORT, WebserverConfiguration.JSON_FACTORY, configuration.getCredential()).setApplicationName("The name of my app on Google Play").build();
    AndroidPublisher.Reviews reviews = publisher.reviews();
    ReviewsListResponse reviewsListResponse = reviews.list("the.packagename.of.my.app").execute();
    logger.info("review list response = " + reviewsListResponse.toPrettyString());
}

这很有用。

我还无法测试,但我确信提取结算信息的方式也有效:

private SubscriptionPurchase getPurchase() throws IOException
{
    AndroidPublisher publisher = new AndroidPublisher.Builder(WebserverConfiguration.HTTP_TRANSPORT, WebserverConfiguration.JSON_FACTORY, configuration.getCredential()).setApplicationName("The name of my app on Google Play").build();
    AndroidPublisher.Purchases purchases = publisher.purchases();

    SubscriptionPurchase purchase = purchases.subscriptions().get("the.packagename.of.my.app", "subscriptionId", "billing token sent by the app").execute();

    //do something or return
    return purchase;
}

答案 1 :(得分:1)

在Java here

中有完整的代码示例和文档

Java source code中,这样授权

private static Credential authorizeWithServiceAccount(String serviceAccountEmail)
            throws GeneralSecurityException, IOException {
        log.info(String.format("Authorizing using Service Account: %s", serviceAccountEmail));

        // Build service account credential.
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(serviceAccountEmail)
                .setServiceAccountScopes(
                        Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER))
                .setServiceAccountPrivateKeyFromP12File(new File(SRC_RESOURCES_KEY_P12))
                .build();
        return credential;
    }