如何为Google Play Developers API生成有效Access Token与Refresh Token
Got it, let's work through this OAuth token request issue step by step—those 400 errors are usually easy to squash once you check the basics!
First, Fixing Postman's "Missing header: Content-Type" Error
Google's OAuth2 token endpoint requires the Content-Type header to be set to application/x-www-form-urlencoded for POST requests. Here's how to fix this in Postman:
- Go to the Headers tab, add a new key-value pair:
- Key:
Content-Type - Value:
application/x-www-form-urlencoded
- Key:
- Switch to the Body tab, select the
x-www-form-urlencodedoption (not form-data or raw JSON), then fill in all required parameters:code: Your authorization code from the consoleclient_id: Your OAuth 2.0 client IDclient_secret: Your client secretredirect_uri: The exact redirect URI you used to get the code (must match exactly, including slashes/case)grant_type: This is critical—don't forget this! Set it toauthorization_code
Send the request again, and this should resolve the missing header error.
Fixing Chrome's Generic "invalid_request" Error
Chrome's direct POST requests (like using the address bar or simple dev tools) are tricky because they don't let you easily set headers or format parameters correctly. Instead, use the Chrome DevTools Console to send a properly formatted request with fetch:
// Replace these values with your actual credentials const authParams = new URLSearchParams({ code: "YOUR_AUTHORIZATION_CODE", client_id: "YOUR_CLIENT_ID", client_secret: "YOUR_CLIENT_SECRET", redirect_uri: "YOUR_REDIRECT_URI", grant_type: "authorization_code" }); fetch("https://accounts.google.com/o/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: authParams }) .then(response => response.json()) .then(data => console.log("Token response:", data)) .catch(error => console.error("Error:", error));
Paste this into the Console, replace the placeholder values, and run it—you'll get a proper JSON response if everything is set correctly.
Key Pitfalls to Double-Check
- Grant Type is Mandatory: The
grant_type=authorization_codeparameter is non-negotiable—Google will reject your request without it. - Redirect URI Exact Match: Even a tiny difference (like a trailing slash vs none) will cause an error. Make sure it's identical to what you used when generating the authorization code.
- One-Time Code: Authorization codes (
code) can only be used once. If you've already tried using it once, you'll need to generate a new code from your console. - Credential Accuracy: Double-check that your
client_idandclient_secretmatch exactly what's listed in your Google Cloud Console OAuth client settings.
Once you've covered all these bases, your request should return a valid access token and refresh token as expected.
内容的提问来源于stack exchange,提问作者EdgeDev

