Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Delphi para la web
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 23-11-2014
Avatar de oesqueda
oesqueda oesqueda is offline
Miembro
 
Registrado: dic 2007
Ubicación: Guadalajara, Mexico
Posts: 66
Poder: 17
oesqueda Va por buen camino
Exclamation PayPal usando REST

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;
Archivos Adjuntos
Tipo de Archivo: rar PayPalREST.rar (59,3 KB, 40 visitas)
__________________
OEsqueda
Responder Con Cita
  #2  
Antiguo 24-11-2014
Avatar de duilioisola
[duilioisola] duilioisola is offline
Miembro Premium
 
Registrado: ago 2007
Ubicación: Barcelona, España
Posts: 1.732
Poder: 20
duilioisola Es un diamante en brutoduilioisola Es un diamante en brutoduilioisola Es un diamante en bruto
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
Responder Con Cita
  #3  
Antiguo 25-11-2014
Avatar de oesqueda
oesqueda oesqueda is offline
Miembro
 
Registrado: dic 2007
Ubicación: Guadalajara, Mexico
Posts: 66
Poder: 17
oesqueda Va por buen camino
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
Responder Con Cita
  #4  
Antiguo 26-11-2014
Avatar de oesqueda
oesqueda oesqueda is offline
Miembro
 
Registrado: dic 2007
Ubicación: Guadalajara, Mexico
Posts: 66
Poder: 17
oesqueda Va por buen camino
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
__________________
OEsqueda
Responder Con Cita
  #5  
Antiguo 26-11-2014
Avatar de duilioisola
[duilioisola] duilioisola is offline
Miembro Premium
 
Registrado: ago 2007
Ubicación: Barcelona, España
Posts: 1.732
Poder: 20
duilioisola Es un diamante en brutoduilioisola Es un diamante en brutoduilioisola Es un diamante en bruto
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...
Responder Con Cita
  #6  
Antiguo 02-12-2014
Avatar de oesqueda
oesqueda oesqueda is offline
Miembro
 
Registrado: dic 2007
Ubicación: Guadalajara, Mexico
Posts: 66
Poder: 17
oesqueda Va por buen camino
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
__________________
OEsqueda
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Rest roman La Taberna 11 30-07-2014 17:52:00
Datasnap Rest Server dison Desarrollo en Delphi para Android 3 16-05-2014 10:48:44
REST, Marshaling y \ iuqrul Providers 1 08-11-2013 11:51:33
Donaciones Paypal, sugerencia. REHome La Taberna 12 07-11-2010 17:54:05
¿quien usa paypal en México.? JXJ La Taberna 4 18-02-2010 23:59:33


La franja horaria es GMT +2. Ahora son las 16:07:30.


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
Copyright 1996-2007 Club Delphi