Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Delphi para la web (https://www.clubdelphi.com/foros/forumdisplay.php?f=51)
-   -   PayPal usando REST (https://www.clubdelphi.com/foros/showthread.php?t=87170)

oesqueda 23-11-2014 23:14:43

PayPal usando REST
 
1 Archivos Adjunto(s)
Hola,

estoy tratando de hacer una aplicacion para pago con PayPal (en realidad es para android e iOS pero lo que pruebo funciona en ambos mundos).

Uso la REST API de paypal https://developer.paypal.com/webapps...oper/docs/api/

La cuestion es que si puedo obtener el TOKEN, es decir ya me valide el acceso.
Pero al hacer el pago (Payment) me devuelve la respuesta JSON en blanco, alguien puede ayudarme.

Adjunto codigo fuente.
En el codigo fuente no pongo client id y secreto, por cuestion de seguridad.
En esta lista esta el codigo fuete y el ejecutable:
www.itcmx.com/PayPalREST.rar

Por su valiosa ayuda mil gracias

Este es el codigo para el token
Código Delphi [-]
var
  slParameters:TStringList;
  Response:TStringStream;
  json, sTokenType:string;
  PayPalObj:TJSONObject;
  jTokenValue:TJSONValue;
begin
memLog.Lines.Clear;
memLog.Lines.Add('TOKEN');

btnPayment.Enabled := False;
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 := 'CLIENT ID';
http.Request.Password := 'SECRETA';

slParameters := TStringList.Create;
Response := TStringStream.Create;
try
  //get an access token
  slParameters.Add('grant_type=client_credentials');
  json := http.Post('https://api.sandbox.paypal.com/v1/oauth2/token', slParameters);
  //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;
    sTokenType := jTokenValue.Value;

    Memo1.Lines.Clear;
    Memo1.Lines.Text := PayPalObj.ToString;
    Memo1.Lines.Add('Size: ' + IntToStr(PayPalObj.EstimatedByteSize));
  finally
    PayPalObj.Free;
  end;

  if sTokenType <> 'Bearer' then
    Exit;

  if AccessToken = '' then
    Exit;

  lblToken.Caption := Format('Token: %s - Type: %s', [AccessToken, sTokenType]);
  btnPayment.Enabled := True;
finally
  Response.Free;
  slParameters.Free;
end;

Y aqui el del payment

Código Delphi [-]
var
  PayPalObj :TJSONObject;
  PayPalObj2 :TJSONObject;
  RedirectObj :TJSONObject;
  PayerObj :TJSONObject;

  TransactionsArray : TJSONArray;
  AmountObj : TJSONObject;
  TransactionObj : TJSONObject;
  FundingArray : TJSONArray;
  CreditCardObj : TJSONObject;

  ssJson : TStringStream;
  json, Authorization:string;
begin
//create a payment
memLog.Lines.Add('PAYMENT');
PayPalObj := TJSONObject.Create;
try
  RedirectObj := TJSONObject.Create;
  try
    RedirectObj.AddPair(TJSONPair.Create('return_url', TJSONString.Create('http://blahblah.com/return')));
    RedirectObj.AddPair(TJSONPair.Create('cancel_url', TJSONString.Create('http://blahblah.com/cancel')));
  except
    RedirectObj.Free;
    Exit;
  end;

  PayerObj := TJSONObject.Create;
  try
    PayerObj.AddPair(TJSONPair.Create('payment_method', TJSONString.Create('credit_card')));

    CreditCardObj := TJSONObject.Create;
    CreditCardObj.AddPair('number', '5500005555555559');
    CreditCardObj.AddPair('type', 'mastercard');
    CreditCardObj.AddPair('expire_month', '12');
    CreditCardObj.AddPair('expire_year', '2018');
    CreditCardObj.AddPair('cvv2', '111');
    CreditCardObj.AddPair('first_name', 'yo');
    CreditCardObj.AddPair('last_name', 'tu');

    FundingArray := TJSONArray.Create;
    FundingArray.Add(CreditCardObj);

    PayerObj.AddPair(TJSONPair.Create('funding_instruments', FundingArray));
  except
    PayerObj.Free;
    Exit;
  end;

  TransactionsArray := TJSONArray.Create;
  AmountObj := TJSONObject.Create;
  TransactionObj := TJSONObject.Create;
  try
    AmountObj.AddPair('currency', TJSONString.Create('USD'));
    AmountObj.AddPair('total', TJSONString.Create('1'));
    TransactionObj.AddPair('amount', AmountObj);
    TransactionObj.AddPair('description', TJSONString.Create('payment description'));
    TransactionsArray.Add(TransactionObj);
  except
    TransactionsArray.Free;
    AmountObj.Free;
    TransactionObj.Free;
    Exit;
  end;

  PayPalObj.AddPair(TJSONPair.Create('intent', TJSONString.Create('sale')));
  PayPalObj.AddPair(TJSONPair.Create('payer', PayerObj));
  PayPalObj.AddPair(TJSONPair.Create('transactions', TransactionsArray));
  //PayPalObj.AddPair(TJSONPair.Create('redirect_urls', RedirectObj));

  Memo1.Lines.Add(' ');
  Memo1.Lines.Add(PayPalObj.ToString);
  Memo1.Lines.Add('Size: ' + IntToStr(PayPalObj.EstimatedByteSize));

  http.Request.Clear;
  http.Request.ContentType := 'application/json';
  http.Request.CustomHeaders.Clear;
  //http.Request.CustomHeaders.FoldLines := False;  //have tried this with no success
  Authorization := Format('Bearer %s', [AccessToken]);
  http.Request.CustomHeaders.AddValue('Authorization', Authorization);  //token obtained from first request

  Memo1.Lines.Add(' ');
  Memo1.Lines.Add(http.Request.CustomHeaders.Text);
  ssJson := TStringStream.Create(PayPalObj.ToString, TEncoding.ASCII);
  try
    { AQUI SE OBTIENE EL VALOR EN BLANCO }
    json := http.Post('https://api.sandbox.paypal.com/v1/payments/payment', ssJson);
    lblPayment.Caption := json;

    PayPalObj2 := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(json), 0) as TJSONObject;
    if Assigned(PayPalObj2) then
      try
        Memo1.Lines.Add(' ');
        Memo1.Lines.Add(PayPalObj2.ToString);
      finally
        PayPalObj2.Free;
      end;
  finally
    ssJson.Free;
  end;
finally
  PayPalObj.Free;
end;

duilioisola 24-11-2014 16:38:52

Según estuve viendo, las comunicaciones REST pueden devolver un dato o no. Además de ver el dato devuelto, deberás ver la cabecera HTTP.
Si por ejemplo devuelve 200 es que todo está OK.
Si devuelve 404 es que no encontró la página.
Mira esto: http://es.wikipedia.org/wiki/Anexo:C...de_estado_HTTP

Básicamente
2xx Ok
3xx Redirecciones
4xx Error en cliente
5xx Error en servidor

oesqueda 25-11-2014 04:32:54

Hola,

si ya vi, cuando solicito el token si obtengo un 200 en el response.
Pero en el otro obtengo un 401.

Creo que el poblema es cuando envio en la cabecera en el request mi Token que obtuve en el primer paso.

He aqui el codigo

Código Delphi [-]
  http.Request.ContentType := 'application/json';
  http.Request.CustomHeaders.Clear;
  Authorization := Format('Bearer %s', [AccessToken]);
  http.Request.CustomHeaders.AddValue('Authorization', Authorization);  //token obtained from first request

Intente usar un tidhttp para el token y otro para el payment, para que estuviera limpio, pero en ambos me marco el mismo error: 401 (http/1.1 401 Unauthorized.)

¿Estoy haciendo algo mal?

oesqueda 26-11-2014 04:33:07

Una pregunta como puedo obtener Request Data y Response Data, me lo piden en paypal pero no veo como obtenerlo.

Cita:

Can you please provide me your request data and the response from the server?

Regards
Hilman
Mil gracias por todo

duilioisola 26-11-2014 10:48:04

Prueba con cURL
http://curl.haxx.se/download.html
Es un programita que se ejecuta desde línea de comandos. Muy útil para hacer pruebas.

Aquí hay algunos ejemplos:
http://blogs.plexibus.com/2009/01/15...ing-with-curl/

Al principio del primer ejemplo ponen el parámetro -i para obtener el Response Header, que supongo que es lo que te piden, junto con el "dato" que responda PayPal.
Con respecto a Request Data, me imagino que es lo que tu envías.

Espero te sirva...

oesqueda 02-12-2014 01:36:41

Fijate que si, estoy usando el CURL que viene en la pagina de paypal y si uso de ambos sentidos los valores que se generan en la prueba (sandbox) y funciona, algo pasa que no pasa de ese paso que es al hacer el pago y envio los datos.

Mil gracias por tu respuesta

PD: en paypal ya me estan solicitando los datos del request y response a ver que me dicen ellos


La franja horaria es GMT +2. Ahora son las 19:13:43.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi