无法从 Google Play Android Developer API 获取订阅信息 [英] Unable to get the subscription information from Google Play Android Developer API

查看:38
本文介绍了无法从 Google Play Android Developer API 获取订阅信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java 版 Google API 客户端库来获取有关用户在我的 android 应用中购买的订阅的信息.这是我现在的做法:

I'trying to use Google APIs Client Library for Java to get information about user's subscriptions purchased in my android app. Here is how I'm doing for now:

HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();

GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                    .setJsonFactory(JSON_FACTORY)
                    .setServiceAccountId(GOOGLE_CLIENT_MAIL)
                    .setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher")
                    .setServiceAccountPrivateKeyFromP12File(new File(GOOGLE_KEY_FILE_PATH))
                    .build();

Androidpublisher publisher = new Androidpublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).
                    setApplicationName(GOOGLE_PRODUCT_NAME).
                    build();

Androidpublisher.Purchases purchases = publisher.purchases();
Get get = purchases.get("XXXXX", subscriptionId, token);
SubscriptionPurchase subscripcion = get.execute(); //Exception returned here

GOOGLE_CLIENT_MAIL 是来自 Google 控制台 API 访问的电子邮件地址.GOOGLE_KEY_FILE_PATH是从API Access下载的p12文件.
GOOGLE_PRODUCT_NAME 是品牌信息中的产品名称.
在 Google APIS 控制台中启用了Google Play Android Developer API"服务.

GOOGLE_CLIENT_MAIL is the email address from API Access from the Google Console. GOOGLE_KEY_FILE_PATH is the p12 file downloaded from the API Access.
GOOGLE_PRODUCT_NAME is the product name from the branding information.
In Google APIS Console the Service "Google Play Android Developer API" is enabled.

我得到的是:

{
  "code" : 401,
  "errors" : [ {
    "domain" : "androidpublisher",
    "message" : "This developer account does not own the application.",
    "reason" : "developerDoesNotOwnApplication"
  } ],
  "message" : "This developer account does not own the application."
}

非常感谢您对这个问题的帮助...

I really appreciate your help for this issue...

推荐答案

我成功了!我遵循的步骤:

I got it working! The steps I followed:

在开始之前,我们需要生成一个刷新令牌.为此,我们必须先创建一个 API 控制台项目:

Before start, we need to generate a refresh token. To do this first we have to create an APIs console project:

  1. 转至 API 控制台并使用您的 Android 开发者登录帐户(在 Android 开发者控制台中用于上传 APK 的帐户).
  2. 选择创建项目.
  3. 转到左侧导航面板中的服务.
  4. 开启 Google Play Android Developer API.
  5. 接受服务条款.
  6. 转到左侧导航面板中的 API Access.
  7. 选择创建 OAuth 2.0 客户端 ID:
    • 在第一页,您需要填写产品名称,但徽标不是必需的.
    • 在第二页上,选择网络应用程序并设置重定向 URI和 Javascript 起源.我们稍后将使用它作为重定向 URI.
  1. Go to the APIs Console and log in with your Android developer account (the same account used in Android Developer Console to upload the APK).
  2. Select Create project.
  3. Go to Services in the left-hand navigation panel.
  4. Turn the Google Play Android Developer API on.
  5. Accept the Terms of Service.
  6. Go to API Access in the left-hand navigation panel.
  7. Select Create an OAuth 2.0 client ID:
    • On the first page, you will need to fill in the product name, but a logo is not required.
    • On the second page, select web application and set the redirect URI and Javascript origins. We will use it later the redirect URI.

所以,现在我们可以生成刷新令牌:

So, now we can generate the refresh token:

  1. 转到以下 URI(请注意,重定向 URI 必须与在客户端 ID 中输入的值完全匹配,包括任何尾随反斜杠):

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID

  1. 在出现提示时选择允许访问.
  2. 浏览器将使用 code 参数重定向到您的重定向 URI,该参数类似于 4/eWdxD7b-YSQ5CNNb-c2iI83KQx19.wp6198ti5Zc7dJ3UXOl0T3aRLxQmbwI.复制这个值.
  1. Select Allow access when prompted.
  2. The browser will be redirected to your redirect URI with a code parameter, which will look similar to 4/eWdxD7b-YSQ5CNNb-c2iI83KQx19.wp6198ti5Zc7dJ3UXOl0T3aRLxQmbwI. Copy this value.

创建一个主类:

public static String getRefreshToken(String code)
{

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
    try 
    {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
        nameValuePairs.add(new BasicNameValuePair("grant_type",    "authorization_code"));
        nameValuePairs.add(new BasicNameValuePair("client_id",     GOOGLE_CLIENT_ID));
        nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET));
        nameValuePairs.add(new BasicNameValuePair("code", code));
        nameValuePairs.add(new BasicNameValuePair("redirect_uri", GOOGLE_REDIRECT_URI));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        org.apache.http.HttpResponse response = client.execute(post);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer buffer = new StringBuffer();
        for (String line = reader.readLine(); line != null; line = reader.readLine())
        {
            buffer.append(line);
        }

        JSONObject json = new JSONObject(buffer.toString());
        String refreshToken = json.getString("refresh_token");                      
        return refreshToken;
    }
    catch (Exception e) { e.printStackTrace(); }

    return null;
}

GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRETGOOGLE_REDIRECT_URI 是之前的值.

GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET and GOOGLE_REDIRECT_URI are the previously values.

终于,我们有了刷新令牌!该值不会过期,因此我们可以存储在某个站点中,例如属性文件.

Finally, we have our refresh token! This value does not expire, so we can store in some site, like a property file.

  1. 获取访问令牌.我们将需要我们之前的刷新令牌:

  1. Getting the access token. We will need our previosly refresh token:

private static String getAccessToken(String refreshToken){

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
try 
{
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("grant_type",    "refresh_token"));
    nameValuePairs.add(new BasicNameValuePair("client_id",     GOOGLE_CLIENT_ID));
    nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    org.apache.http.HttpResponse response = client.execute(post);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer buffer = new StringBuffer();
    for (String line = reader.readLine(); line != null; line = reader.readLine())
    {
        buffer.append(line);
    }

    JSONObject json = new JSONObject(buffer.toString());
    String accessToken = json.getString("access_token");

    return accessToken;

}
catch (IOException e) { e.printStackTrace(); }

return null;

}

现在,我们可以访问 Android API.我对订阅的到期时间很感兴趣,所以:

Now, we can access to the Android API. I'm interesting in the expiration time of a subscription, so:

private static HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static JsonFactory JSON_FACTORY = new com.google.api.client.json.jackson2.JacksonFactory();

private static Long getSubscriptionExpire(String accessToken, String refreshToken, String subscriptionId, String purchaseToken){

try{

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setAccessToken(accessToken);
    tokenResponse.setRefreshToken(refreshToken);
    tokenResponse.setExpiresInSeconds(3600L);
    tokenResponse.setScope("https://www.googleapis.com/auth/androidpublisher");
    tokenResponse.setTokenType("Bearer");

    HttpRequestInitializer credential =  new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
            .setJsonFactory(JSON_FACTORY)
            .setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
            .build()
            .setFromTokenResponse(tokenResponse);

    Androidpublisher publisher = new Androidpublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).
            setApplicationName(GOOGLE_PRODUCT_NAME).
            build();

    Androidpublisher.Purchases purchases = publisher.purchases();
    Get get = purchases.get(GOOGLE_PACKAGE_NAME, subscriptionId, purchaseToken);
    SubscriptionPurchase subscripcion = get.execute();

    return subscripcion.getValidUntilTimestampMsec();

}
catch (IOException e) { e.printStackTrace(); }
return null;

}

仅此而已!

一些步骤来自https://developers.google.com/android-publisher/authorization.

这篇关于无法从 Google Play Android Developer API 获取订阅信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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