Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Error Api Strava

Estas en el tema de Error Api Strava en el foro de PHP en Foros del Web. Hola a todos: He creado una aplicacion de Strava y he seguido los pasos que se indican en la documentación: http://strava.github.io/api/v3/oauth/ Una vez "autorizado" desde ...
  #1 (permalink)  
Antiguo 07/01/2015, 15:43
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Error Api Strava

Hola a todos:

He creado una aplicacion de Strava y he seguido los pasos que se indican en la documentación: http://strava.github.io/api/v3/oauth/

Una vez "autorizado" desde una cuenta me redirecciona a mi web: ejemplo.com con el código, etc (como se ve en el pantallazo). Después se debe enviar ese código a "https://www.strava.com/oauth/token" para que devuelva el "access_token" pero me indica un "error" al realizarlo.

"You are being redirect".

¿Alguien tiene alguna idea de que puede ser si estoy siguiendo paso a paso la documentación?

Muchas gracias
  #2 (permalink)  
Antiguo 07/01/2015, 20:07
Avatar de enlinea777  
Fecha de Ingreso: mayo-2008
Ubicación: frente al pc
Mensajes: 1.830
Antigüedad: 15 años, 11 meses
Puntos: 127
Respuesta: Error Api Strava

Busca el error en google
  #3 (permalink)  
Antiguo 08/01/2015, 11:37
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: Error Api Strava

Preguntaba esto puesto que en google no hay nada al respecto, he seguido los pasos de la documentación, y abrí un mensaje en el soporte de strava hace como 12 días.
  #4 (permalink)  
Antiguo 08/01/2015, 13:05
Avatar de enlinea777  
Fecha de Ingreso: mayo-2008
Ubicación: frente al pc
Mensajes: 1.830
Antigüedad: 15 años, 11 meses
Puntos: 127
Respuesta: Error Api Strava

el codigo?
  #5 (permalink)  
Antiguo 08/01/2015, 15:04
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: Error Api Strava

Ok, Voy a intentar poner el código para entenderlo:


Código PHP:
Ver original
  1. <?php
  2.     /**
  3.      * Simple PHP Library for the Strava v3 API
  4.      *
  5.      * @author Stuart Wilson <[email protected]>
  6.      *
  7.      * @link https://github.com/iamstuartwilson/strava
  8.      */
  9.     class Strava
  10.     {
  11.         const BASE_URL = 'https://www.strava.com/';
  12.        
  13.         public $lastRequest;
  14.         public $lastRequestData;
  15.         public $lastRequestInfo;
  16.        
  17.         protected $apiUrl;
  18.         protected $authUrl;
  19.         protected $clientId;
  20.         protected $clientSecret;
  21.        
  22.         private $accessToken;
  23.         /**
  24.          * Sets up the class with the $clientId and $clientSecret
  25.          *
  26.          * @param int    $clientId
  27.          * @param string $clientSecret
  28.          */
  29.         public function __construct($clientId = 1234, $clientSecret = 'aaaaaaa')
  30.         {
  31.             $this->clientId = $clientId;
  32.             $this->clientSecret = $clientSecret;
  33.             $this->apiUrl = self::BASE_URL . 'api/v3/';
  34.             $this->authUrl = self::BASE_URL . 'oauth/';
  35.         }
  36.         /**
  37.          * Appends query array onto URL
  38.          *
  39.          * @param string $url
  40.          * @param array  $query
  41.          *
  42.          * @return string
  43.          */
  44.         protected function parseGet($url, $query)
  45.         {
  46.             $append = strpos($url, '?') === false ? '?' : '&';
  47.             return $url . $append . http_build_query($query);
  48.         }
  49.         /**
  50.          * Parses JSON as PHP object
  51.          *
  52.          * @param string $response
  53.          *
  54.          * @return object
  55.          */
  56.         protected function parseResponse($response)
  57.         {
  58.             return json_decode($response);
  59.         }
  60.         /**
  61.          * Makes HTTP Request to the API
  62.          *
  63.          * @param string $url
  64.          * @param array  $parameters
  65.          *
  66.          * @return mixed
  67.          */
  68.         protected function request($url, $parameters = array(), $request = false)
  69.         {
  70.             $this->lastRequest = $url;
  71.             $this->lastRequestData = $parameters;
  72.             $curl = curl_init($url);
  73.             $curlOptions = array(
  74.                 CURLOPT_SSL_VERIFYPEER => false,
  75.                 CURLOPT_FOLLOWLOCATION => true,
  76.                 CURLOPT_REFERER        => $url,
  77.                 CURLOPT_RETURNTRANSFER => true,
  78.             );
  79.            
  80.             if (! empty($parameters) || ! empty($request))
  81.             {
  82.                 if (! empty($request))
  83.                 {
  84.                     $curlOptions[ CURLOPT_CUSTOMREQUEST ] = $request;
  85.                     $parameters = http_build_query($parameters);
  86.                 }
  87.                 else
  88.                 {
  89.                     $curlOptions[ CURLOPT_POST ] = true;
  90.                 }
  91.                 $curlOptions[ CURLOPT_POSTFIELDS ] = $parameters;
  92.             }
  93.                        
  94.             /*                      
  95.             echo $url;
  96.             echo "<pre>";
  97.             var_dump($parameters);
  98.             echo "</pre>";
  99.             */
  100.            
  101.             curl_setopt_array($curl, $curlOptions);
  102.             $response = curl_exec($curl);
  103.             $error = curl_error($curl);
  104.             $this->lastRequestInfo = curl_getinfo($curl);
  105.             curl_close($curl);
  106.             if (! $response)
  107.             {
  108.                 return $error;
  109.             }
  110.             else
  111.             {
  112.                 return $this->parseResponse($response);
  113.             }
  114.         }
  115.         /**
  116.          * Creates authentication URL for your app
  117.          *
  118.          * @param string $redirect
  119.          * @param string $approvalPrompt
  120.          * @param string $scope
  121.          * @param string $state
  122.          *
  123.          * @link http://strava.github.io/api/v3/oauth/#get-authorize
  124.          *
  125.          * @return string
  126.          */
  127.         public function authenticationUrl($redirect, $approvalPrompt = 'auto', $scope = null, $state = null)
  128.         {
  129.             $parameters = array(
  130.                 'client_id'       => $this->clientId,
  131.                 'redirect_uri'    => $redirect,
  132.                 'response_type'   => 'code',
  133.                 'approval_prompt' => $approvalPrompt,
  134.                 'scope'           => $scope,
  135.                 'state'           => $state,
  136.             );
  137.             return $this->parseGet(
  138.                 $this->authUrl . 'authorize',
  139.                 $parameters
  140.             );
  141.         }
  142.         /**
  143.          * Authenticates token returned from API
  144.          *
  145.          * @param string $code
  146.          *
  147.          * @link http://strava.github.io/api/v3/oauth/#post-token
  148.          *
  149.          * @return string
  150.          */
  151.         public function tokenExchange($code)
  152.         {
  153.             $parameters = array(
  154.                 'client_id'     => $this->clientId,
  155.                 'client_secret' => $this->clientSecret,
  156.                 'code'          => $code,
  157.             );
  158.             return $this->request($this->authUrl.'token', $parameters);
  159.         }
  160.         /**
  161.          * Deauthorises application
  162.          *
  163.          * @link http://strava.github.io/api/v3/oauth/#deauthorize
  164.          *
  165.          * @return string
  166.          */
  167.         public function deauthorize()
  168.         {
  169.             return $this->request(
  170.                 $this->authUrl . 'deauthorize',
  171.                 $this->generateParameters(array())
  172.             );
  173.         }
  174.         /**
  175.          * Sets the access token used to authenticate API requests
  176.          *
  177.          * @param string $token
  178.          */
  179.         public function setAccessToken($token)
  180.         {
  181.             return $this->accessToken = $token;
  182.         }
  183.         /**
  184.          * Sends GET request to specified API endpoint
  185.          *
  186.          * @param string $request
  187.          * @param array  $parameters
  188.          *
  189.          * @example http://strava.github.io/api/v3/athlete/#koms
  190.          *
  191.          * @return string
  192.          */
  193.         public function get($request, $parameters = array())
  194.         {
  195.             $parameters = $this->generateParameters($parameters);
  196.             $requestUrl = $this->parseGet($this->apiUrl . $request, $parameters);
  197.             return $this->request($requestUrl);
  198.         }
  199.         /**
  200.          * Sends PUT request to specified API endpoint
  201.          *
  202.          * @param string $request
  203.          * @param array  $parameters
  204.          *
  205.          * @example http://strava.github.io/api/v3/athlete/#update
  206.          *
  207.          * @return string
  208.          */
  209.         public function put($request, $parameters = array())
  210.         {
  211.             return $this->request(
  212.                 $this->apiUrl . $request,
  213.                 $this->generateParameters($parameters),
  214.                 'PUT'
  215.             );
  216.         }
  217.         /**
  218.          * Sends POST request to specified API endpoint
  219.          *
  220.          * @param string $request
  221.          * @param array  $parameters
  222.          *
  223.          * @example http://strava.github.io/api/v3/activities/#create
  224.          *
  225.          * @return string
  226.          */
  227.         public function post($request, $parameters = array())
  228.         {
  229.             return $this->request(
  230.                 $this->apiUrl . $request,
  231.                 $this->generateParameters($parameters)
  232.             );
  233.         }
  234.         /**
  235.          * Sends DELETE request to specified API endpoint
  236.          *
  237.          * @param string $request
  238.          * @param array  $parameters
  239.          *
  240.          * @example http://strava.github.io/api/v3/activities/#delete
  241.          *
  242.          * @return string
  243.          */
  244.         public function delete($request, $parameters = array())
  245.         {
  246.             return $this->request(
  247.                 $this->apiUrl . $request,
  248.                 $this->generateParameters($parameters),
  249.                 'DELETE'
  250.             );
  251.         }
  252.         /**
  253.          * Adds access token to paramters sent to API
  254.          *
  255.          * @param  array $parameters
  256.          *
  257.          * @return array
  258.          */
  259.         protected function generateParameters($parameters)
  260.         {
  261.             return array_merge(
  262.                 $parameters,
  263.                 array( 'access_token' => $this->accessToken )
  264.             );
  265.         }
  266.        
  267.         public function get_activities()
  268.         {            
  269.             $parameters = array(
  270.                 'access_token' => $this->accessToken
  271.             );
  272.            
  273.             $result = $this->get("activities", $parameters);
  274.             return $result;
  275.         }
  276.     }

Este es el código que auto-genera el link a strava para solicitar permiso a la aplicación creada en Strava:

Código PHP:
Ver original
  1. $new_strava = New Strava();
  2. $url_redirect = $context->link->getPageLink("admin-sincronizacion");
  3. $link = $new_strava->authenticationUrl($url_redirect, 'force', "write", "strava");

Por otr lado, este es el código que recibe el 'code' de strava que debes enviarle para recibir el "access_token" que es lo que realmente servirá en un futuro para realizar la conexión del usuario correspondiente (es en este paso donde da el error).

Código PHP:
Ver original
  1. $new_strava = New Strava();
  2. $return = $new_strava->tokenExchange($code);

Muchas gracias.
  #6 (permalink)  
Antiguo 12/01/2015, 11:26
Avatar de enlinea777  
Fecha de Ingreso: mayo-2008
Ubicación: frente al pc
Mensajes: 1.830
Antigüedad: 15 años, 11 meses
Puntos: 127
Respuesta: Error Api Strava

debuguea
$url_redirect
o la clase con var_dump(), al parecer no estas colocando ninguna url o estas haciendo algo antes de redireccionar que bloquea la redireccion.
  #7 (permalink)  
Antiguo 13/01/2015, 08:13
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: Error Api Strava

He revisado lo que comentas y lo veo correctamente, quizás sea alguna tontería similar pero la verdad no veo el error.

En esta parte:

Código PHP:
Ver original
  1. $link = $new_strava->authenticationUrl($url_redirect, 'force', "write", "strava");

auto-genera la siguiente url: https://www.strava.com/oauth/authori...e&state=strava

a la que el sistema redirecciona correctamente para pedir permiso a la aplicación.

En el 2º paso, el sistema nos redirecciona a nuestra url de vuelta con el "code" que corresponda, y es en ese 2º paso

Código PHP:
Ver original
  1. $new_strava = New Strava();
  2. $return = $new_strava->tokenExchange($code);

es donde también redirecciona correctamente pero nos auto envía a una url de 404; es decir, la clase Strava ejecuta por Curl la siguiente URL y parámetros:

Código PHP:
Ver original
  1. https://www.strava.com/oauth/token
  2. array(3) {
  3.   ["client_id"]=>
  4.   int(1234)
  5.   ["client_secret"]=>
  6.   string(40) "aaaaaaaa"
  7.   ["code"]=>
  8.   string(40) "bbbbb"
  9. }

y en esta respuesta es donde da el error de 404 strava (pese a que en su documentación de la Api indica que debe ser así: http://strava.github.io/api/v3/oauth/).

¿Que puede ser?

Muchas gracias por la ayuda.
  #8 (permalink)  
Antiguo 13/01/2015, 08:30
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: Error Api Strava

Tengo que aclatar también que la forma de usar la Api de Strava es según el ejemplo de https://github.com/iamstuartwilson/strava
  #9 (permalink)  
Antiguo 13/01/2015, 09:03
Avatar de Eleazan  
Fecha de Ingreso: abril-2008
Ubicación: Ibiza
Mensajes: 1.879
Antigüedad: 16 años
Puntos: 326
Respuesta: Error Api Strava

Imagino que el code lo capturas, no?
__________________
>> Eleazan's Source
>> @Eleazan
  #10 (permalink)  
Antiguo 13/01/2015, 09:19
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: Error Api Strava

Si claro, lo capturo y lo auto-genera correctamente puesto que cada vez que "autorizas" a la aplicación te devuelve uno diferente.
  #11 (permalink)  
Antiguo 13/01/2015, 10:07
Avatar de Eleazan  
Fecha de Ingreso: abril-2008
Ubicación: Ibiza
Mensajes: 1.879
Antigüedad: 16 años
Puntos: 326
Respuesta: Error Api Strava

Si pruebas aqui:

https://www.hurl.it/

Y pones la url del token, y client_id, client_secret, y code... te devuelve respuesta correctamente (en mi caso, diciendo que el code es erroneo).

Así pues, parece más un problema en la API que utilizas... ¿puedes añadir que te pase los headers de curl?

Edit:

En la clase del Api:
Código PHP:
Ver original
  1. protected function request($url, $parameters = array(), $request = false)
  2.         {
  3.             $this->lastRequest = $url;
  4.             $this->lastRequestData = $parameters;
  5.             $curl = curl_init($url);
  6.             $curlOptions = array(
  7.                 CURLOPT_SSL_VERIFYPEER => false,
  8.                 CURLOPT_FOLLOWLOCATION => true,
  9.                 CURLOPT_REFERER        => $url,
  10.                 CURLOPT_RETURNTRANSFER => true,
  11.                 CURLOPT_HEADER => true,
  12.             );

Añadele ese header, y en parseResponse haz un echo '<pre>'.$response.'</pre>'; exit();
__________________
>> Eleazan's Source
>> @Eleazan
  #12 (permalink)  
Antiguo 13/01/2015, 10:48
Avatar de victor5atodogas  
Fecha de Ingreso: junio-2010
Mensajes: 447
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: Error Api Strava

Hola de nuevo:

Al final no se exactamente donde puede estar el error pero al crear otra función de prueba me ha funcionado correctamente:

Código PHP:
Ver original
  1. protected function request2($url, $parameters = array(), $request = false)
  2.         {
  3.             $ch = curl_init();
  4.             curl_setopt($ch, CURLOPT_URL,$url);
  5.             curl_setopt($ch, CURLOPT_POST, 1);
  6.             curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
  7.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);            
  8.             $response = curl_exec ($ch);            
  9.             curl_close ($ch);
  10.            
  11.             return $this->parseResponse($response);        
  12.         }

por lo que ya queda solucionado el tema.

Muchas gracias por la ayuda.

Etiquetas: api
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 11:12.