【发布时间】:2018-10-19 08:19:38
【问题描述】:
我正在尝试按照Google-Play-Billing docs 的建议在我的后端实施购买验证。在此 documentation 进行订阅购买验证之后,它告诉我必须使用我的 android 应用程序的 包名称、subscription_id 向该 URL (Purchases.subscriptions: get) 发出获取请求,和购买令牌。但是,在我可以向该 URL 发出 get 请求之前,我必须授权我的后端服务器处理 API 请求。因此,按照该文档中指向here 的链接,我开始执行这些步骤。我创建了一个 OAuth 2.0 客户端 ID,然后通过转到浏览器中的下一个 url 生成初始刷新令牌。我的 client_id 设置为我刚刚生成的 OAuth 2.0 客户端 ID,我的 redirect_uri 设置为 urn:ietf:wg :oauth:2.0:oob,这是我从 Google API 控制台 下载的 JSON 文件中收到的。我成功检索了我的初始刷新令牌并将其放入我的后端代码中。
现在的目标是在我的 Android 应用中成功购买,然后向我的后端发送一个带有必要参数的发布请求。这部分工作得很好。但是,在执行authorization documentation 的后续步骤时,它会说“通过向...发送 POST 请求来交换此代码以获取访问和刷新令牌对...”以便获取我的 access_code,我将字段设置为文档所说的设置字段,但我的请求返回 400 错误并显示错误消息:“invalid_grant” .我不明白为什么会收到此错误。
这是我的发帖请求代码:
List <NameValuePair> parameters = new ArrayList <>();
parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
parameters.add(new BasicNameValuePair("code", initial_code));
parameters.add(new BasicNameValuePair("client_id", client_id));
parameters.add(new BasicNameValuePair("client_secret", client_secret));
parameters.add(new BasicNameValuePair("redirect_uri", redirect_uri));
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(requestConfig);
try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
HttpPost request = new HttpPost("https://accounts.google.com/o/oauth2/token");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(new UrlEncodedFormEntity(parameters));
try (CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
final StatusLine statusLine = response.getStatusLine();
if (entity != null) {
System.out.println("Response returned: " + statusLine.getStatusCode() + " - " + EntityUtils.toString(entity));
}
}
}
请帮忙!
【问题讨论】:
-
经过更多研究,我想知道是否需要将我的 client_id 的 access_type 设置为
offline?但是我无法弄清楚如何实际做到这一点。 -
好的,经过更多研究,我意识到我设置的 redirect_uri 是为了打开浏览器手动复制/粘贴授权码。我不需要它来将用户重定向到任何地方,因为这一切都发生在后端。那么当我不想重定向到请求来源以外的任何地方时,我应该将我的 redirect_uri 设置为什么?
-
说真的!没人能帮我吗?
标签: java android oauth-2.0 play-billing-library