我正在尝试实现Google Play开发者API,以便从服务器端获取我的用户的所有IAP和订阅详细信息(到期,用户退款等)。
我遵循了https://developers.google.com/android-publisher/authorization的指南和Am I getting the steps right for verifying a user's Android in-app subscription?的步骤,直到我必须向https://accounts.google.com/o/oauth2/token url发送POST请求为止。
我尝试根据https://webdevdesigner.com/q/invalid-grant-trying-to-get-oauth-token-from-google-6945/上的用户,用我的服务帐户电子邮件(app-name@api-1234-56789.iam.gserviceaccount.com)替换客户端ID,以重新启动整个步骤。他说Google文档对客户ID产生误导。这给了我“错误400:redirect_uri_mismatch”,并且没有选择将重定向uri添加到Google Cloud控制台上的服务帐户的选项。 然后,我尝试在https://reqbin.com/上发送请求,但得到的响应与下面的Java源代码相同。
I/System.out: Resp Code: 400
Resp Message:Bad Request
I/System.out: {
"error": "invalid_grant",
"error_description": "Bad Request"
private void testOAuth()
{
try
{
String query = "client_id="+URLEncoder.encode("***-***.apps.googleusercontent.com","UTF-8");
query += "&";
query += "client_secret="+ URLEncoder.encode("***-***","UTF-8") ;
query += "&";
query += "code="+ URLEncoder.encode("4/***","UTF-8") ;
query += "&";
query += "grant_type="+ URLEncoder.encode("authorization_code","UTF-8") ;
query += "&";
query += "redirect_uri="+ URLEncoder.encode("https://www.google.com","UTF-8") ;
/*query += "&";
query += "scope="+ URLEncoder.encode("https://www.googleapis.com/auth/androidpublisher","UTF-8") ;*/
URL url=new URL("https://accounts.google.com/o/oauth2/token");
HttpsURLConnection httpsURLConnection=(HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("POST");
httpsURLConnection.setRequestProperty("Content-length", String.valueOf(query.length()));
httpsURLConnection.setRequestProperty("Content-Type","application/json");
//httpsURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
//httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setInstanceFollowRedirects(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream());
dataOutputStream.writeBytes(query);
dataOutputStream.close();
/*DataInputStream dataInputStream=new DataInputStream(httpsURLConnection.getInputStream());
for( int c = dataInputStream.read(); c != -1; c = dataInputStream.read() ){System.out.print( (char)c );}
dataInputStream.close();*/
int responseCode=httpsURLConnection.getResponseCode();
System.out.println("Resp Code: "+responseCode);
System.out.println("Resp Message:"+ httpsURLConnection.getResponseMessage());
if(responseCode>=400)
{
DataInputStream errorStream=new DataInputStream(httpsURLConnection.getErrorStream());
for( int c = errorStream.read(); c != -1; c = errorStream.read() ){System.out.print( (char)c );}
errorStream.close();
}
}
catch(MalformedURLException e){e.printStackTrace();}
catch (IOException e){e.printStackTrace();}
}
catch(MalformedURLException e){e.printStackTrace();}
catch (IOException e){e.printStackTrace();}
}