使用PayPal .NET SDK获取/授权订单始终返回404错误求助
问题排查与解决方法
1. Authorization 头缺少 Bearer 前缀
你的REST API代码中,Authorization头仅直接使用了token,但PayPal API要求必须以Bearer 作为前缀。这会导致API无法正确验证身份,进而返回错误。
修正后的代码:
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
2. 授权请求的请求体格式错误
PayPal的/v2/checkout/orders/{order_id}/authorize端点要求请求体为空(或不发送任何内容)。你当前发送的是序列化后的空字符串(结果为""),这属于无效的JSON格式,会触发Bad Request错误。
修正方式:
// 推荐:不发送请求体 var response = await client.PostAsync("https://api.sandbox.paypal.com/v2/checkout/orders/1234567/authorize", null, CancellationToken.None); // 或者发送空内容 var content = new StringContent(string.Empty, Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://api.sandbox.paypal.com/v2/checkout/orders/1234567/authorize", content, CancellationToken.None);
3. 订单ID与API版本不匹配
如果你是通过v2 API创建的订单,使用PayPal-NET-SDK的Order.Get方法会调用v1的订单查询端点,而v2订单无法在v1端点中找到,从而返回404。该SDK主要针对v1 API设计,对于v2订单建议直接使用REST API调用v2端点,或者使用SDK中专门的v2订单操作方法。
4. 订单ID有效性检查
确保你使用的订单ID在沙箱环境中确实存在,且没有拼写错误。无效的订单ID会直接返回404 Not Found。
修正后的完整REST API代码示例
var config = new Dictionary<string, string> {{ "mode", "sandbox" }, { "clientId", "123" },{ "clientSecret", "ABC" }}; var token = new OAuthTokenCredential(config).GetAccessToken(); using var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); // 发送授权请求(无请求体) var response = await client.PostAsync("https://api.sandbox.paypal.com/v2/checkout/orders/1234567/authorize", null, CancellationToken.None); // 检查响应并获取详情 if (response.IsSuccessStatusCode) { var authorizeResult = await response.Content.ReadAsStringAsync(); // 处理授权成功逻辑 } else { var errorDetails = await response.Content.ReadAsStringAsync(); // 打印错误信息用于排查 Console.WriteLine(errorDetails); }
内容的提问来源于stack exchange,提问作者kryptobi
相关产品推荐
相关产品推荐

