You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#调用Ebay API获取AccessToken时遇invalid_grant错误

使用Authorization Code Grant Type获取Ebay Access Token时返回400错误

问题描述

我用C#通过Authorization Code Grant Type获取用户access token时,请求返回400(Bad Request)错误,但切换到client_credentials模式时,相同的请求方法能正常运行。

错误信息

运行代码后抛出的异常:

System.Net.HttpRequestException has been thrown
"Response status does not indicate success: 400(Bad Request)

完整错误输出:

Status Code: BadRequest
Reason Phrase: Bad Request
Error Content: {"error":"invalid_grant","error_description":"the provided authorization grant code is invalid or was issued to another client"}

我的代码

class Program
{
    static async Task Main(string[] args)
    {
        string clientId = "...CLIENTID…";
        string clientSecret = "...CLIENTSECRET…";
        string authorizationCode = "v%...";
        string redirectUri = "...REDİRECTURI…";
        string credentials = $"{clientId}:{clientSecret}";
        string base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));

        using (var client = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "https://api.sandbox.ebay.com/identity/v1/oauth2/token");

            request.Headers.Add("Authorization", $"Basic {base64Credentials}");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "authorization_code"),
                new KeyValuePair<string, string>("redirect_uri", redirectUri),
                new KeyValuePair<string, string>("code", authorizationCode)
            });
            request.Content = content;

            var response = await client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}

期望响应

按照Ebay的Authorization Code Grant类型文档,期望得到包含access和refresh tokens的响应:

{
    "access_token": "v^1.1#i^1#p^3#r^1...XzMjRV4xMjg0",
    "expires_in": 7200,
    "refresh_token": "v^1.1#i^1#p^3#r^1...zYjRV4xMjg0",
    "refresh_token_expires_in": 47304000,
    "token_type": "User Access Token"
}

排查与解决建议

  • 确认授权码未被使用:Authorization Code是一次性有效凭证,用过之后立即失效,检查你的authorizationCode是否是刚获取的未使用过的。
  • 匹配客户端与跳转地址:确保请求中的clientId、redirectUri和获取授权码时使用的完全一致,包括大小写、特殊字符(比如redirectUri里的İ是否和授权流程中的一致)。
  • 处理授权码编码:如果授权码是URL编码格式(比如你的authorizationCode包含%),需要先用Uri.UnescapeDataString(authorizationCode)解码后再传入请求。
  • 统一环境:确认获取授权码和请求token的操作都在Ebay沙箱环境下完成,不要混用生产环境的配置信息。

内容的提问来源于stack exchange,提问作者ny0la

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 17:48:16