在Delphi XE2中使用PayPal REST客户端

在Delphi XE2中使用PayPal REST客户端,delphi,rest,paypal,indy,Delphi,Rest,Paypal,Indy,我正在尝试与PayPal REST客户端进行交互,请遵循以下说明: 我可以使用具有以下代码的TIdHttp组件成功获取访问令牌: http.Request.ContentType := 'application/x-www-form-urlencoded'; http.Request.Accept := 'application/json'; http.Request.AcceptLanguage := 'en_US'; http.Request.BasicAuthentication :=

我正在尝试与PayPal REST客户端进行交互,请遵循以下说明:

我可以使用具有以下代码的TIdHttp组件成功获取访问令牌:

http.Request.ContentType := 'application/x-www-form-urlencoded';
http.Request.Accept := 'application/json';
http.Request.AcceptLanguage := 'en_US';
http.Request.BasicAuthentication := True;
http.Request.Username := 'my paypal clientid';
http.Request.Password := 'my paypal secret';

slParameters := TStringList.Create;
Response := TStringStream.Create;
try
  //get an access token
  slParameters.Add('grant_type=client_credentials');
  http.Post('https://api.sandbox.paypal.com/v1/oauth2/token', slParameters, Response);
  json := Response.DataString;
  PayPalObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(json), 0) as TJSONObject;
  try
    jTokenValue := PayPalObj.Get('access_token').JsonValue;
    AccessToken := jTokenValue.Value;
    jTokenValue := PayPalObj.Get('token_type').JsonValue;
    TokenType := jTokenValue.Value;
  finally
    PayPalObj.Free;
  end;

  if TokenType <> 'Bearer' then
    Exit;

  if AccessToken = '' then
    Exit;

  ....

finally
  Response.Free;
  slParameters.Free;
end;

我没有得到任何回应。我确信我已经正确地构造了JSON字符串,因为我已经仔细地将它与示例字符串进行了比较。我还使用cURL测试了示例1,它确实有效。我不确定像我所做的那样将JSON字符串添加到字符串列表中是否正确。我也不确定是否需要在某个地方包含“-d”cURL参数。如果您有任何建议,我们将不胜感激。

在第二步中,您不能使用
TStringList
发布JSON数据。这只适用于
应用程序/x-www-form-urlencoded
帖子。要发布JSON,您需要使用
TStream

此外,您不需要使用
TStringStream
以字符串形式获取响应
Post()
可以直接返回字符串

试试这个:

json := http.Post('https://api.sandbox.paypal.com/v1/oauth2/token', slParameters);
...
ssJson := TStringStream.Create(PayPalObj.ToString, TEncoding.ASCII);
try
  json := http.Post('https://api.sandbox.paypal.com/v1/payments/payment', ssJson);
finally
  ssJson.Free;
end;

非常感谢Remy,我将尝试一下。使用与您在步骤1中使用的相同代码,我只收到一个HTTP/1.0 400错误请求。。。有什么提示吗?
json := http.Post('https://api.sandbox.paypal.com/v1/oauth2/token', slParameters);
...
ssJson := TStringStream.Create(PayPalObj.ToString, TEncoding.ASCII);
try
  json := http.Post('https://api.sandbox.paypal.com/v1/payments/payment', ssJson);
finally
  ssJson.Free;
end;