使用Google Play开发者API进行服务器端授权? [英] Server side authorization with Google Play Developer API?

查看:2165
本文介绍了使用Google Play开发者API进行服务器端授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要授权才能从



<2>。)下载这个服务帐户私人密钥.json文件(不要误以为)在Google Play Developer Console中,转到设置 - >用户&权限 - >邀请新用户,并将新用户的 client_email 的用户电子邮件设置为下载文件的用户电子邮件。通过此视图中的复选框分配您想要赋予此用户的访问权限(例如'查看财务数据')。

4。)将适当的依赖关系添加到您的项目(版本...- 1.23.0不适用于我):

 <依赖项> 
< groupId> com.google.apis< / groupId>
< artifactId> google-api-services-androidpublisher< / artifactId>
< version> v2-rev50-1.22.0< / version>
< /依赖关系>

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

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

/ ** HTTP传输的全局实例。 * /
public static HttpTransport HTTP_TRANSPORT;

/ ** JSON工厂的全局实例。 * /
public static JsonFactory JSON_FACTORY;

私人GoogleCredential凭证;

@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));

$ b catch(IOException | GeneralSecurityException e)
{
throw new InitialExceptionException(e);


$ b $ 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 - 在Wildfly中将其配置为VM启动参数);



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

6)现在我是能够获取Google Play Developer API信息,例如评论:

  private void invokeGoogleApi()抛出IOException 
{
AndroidPublisher publisher = new AndroidPublisher.Builder WebServerConfiguration.HTTP_TRANSPORT,WebserverConfiguration.JSON_FACTORY,configuration.getCredential())。setApplicationName(Google Play上我的应用程序的名称)。
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(Google Play上我的应用程序的名称)。 ();
AndroidPublisher.Purchases purchases = publisher.purchases();

SubscriptionPurchase购买= purchases.subscriptions()。get(the.packagename.of.my.app,subscriptionId,由应用程序发送的计费令牌)。

//做某件事或返回
退货购买;
}


Authorization is required to fetch information from the Google Play Developer API.

I know how to do this with Postman, but implementing authorization is much more cumbersome (redirect url, handling redirects, and so on...) These would be the steps when you already have setup the auth data inside the 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.

Now I want to do all this programmatically. Obviously not so easy. I thought the Google API Client Libraries will help, but I don't see, how these lib can help me with my use case.
For example classes like GoogleAuthorizationCodeFlow expect a user id at the moment of the request, but I not necessarily have one at this moment, so I wonder how this API should be used in a clean way.

Is there a clean way to handle OAuth2.0 easier / programmatically with some API to access Google Play Developer API? Otherwise I must implement it manually.

解决方案

After lots of headache (like always with Google APIs and services) I figured out how one can access Google Play Developer API information (like billing) by using existing APIs.

1.) Create in Developer API Console a service account (JSON) key:

2.) Download this service-account-private-key.json file (don't mistake it with the OAuth2.0 client secret file!).

3.) In Google Play Developer Console go to Settings -> Users & Permissions -> Invite New User and set as user e-mail of the new user the client_email from the downloaded file. Assign the access rights you want to give to this users via the checkboxes inside this view (for example 'View financial data').

4.) Add the proper dependency to your project (version ...-1.23.0 does not work for me):

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

5.) Load the service-account-private-key.json file into your application. In my case it's a webserver:

@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.) Now I am able the fetch Google Play Developer API information, e.g. reviews:

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());
}

This worked.

I cannot test it yet, but I'm sure that fetching the billing information works as well:

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;
}

这篇关于使用Google Play开发者API进行服务器端授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆