Git Product home page Git Product logo

stravaphp's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stravaphp's Issues

Uploading gpx file

actual_file = realpath('Giro_mattutino.gpx');
$file ='@'.$actual_file;
$client->uploadActivity($file, 'ride', 'Morning Ride', 'A test', 0, 1, 'gpx');

I'm using this code to upload the file but it doesn't seem to work.. Any help?

Can you do a point release?

Hi @vredeling, thanks for all the work on the library recently.

I just want to ask about your plans to do a version bump sometime soon, I have some code that depends on #64 and having a dependency on "dev-master" in my composer.json for so long is starting to give me unhappy feelings.

Thanks!

Having trouble getting OAuth2 to work and missing refresh token

I have used OAuth2 before, but having trouble getting this library to work as documented. And I don't see how you get a refresh token. It can probably can all be solved with more complete examples.

Right now I am getting the following error:
Required option not passed: "access_token" /League/OAuth2/Client/Token/AccessToken.php 96
called from /League/OAuth2/Client/Provider/AbstractProvider.php 746
called from /League/OAuth2/Client/Provider/AbstractProvider.php 544

I don't see "access_token" in the documentation.

I appreciate any insights.

Refresh Tokens Update

Hey

Am I right in thinking that the current code base doesn't support the Refresh Tokens Update, Strava announced a while back?

https://developers.strava.com/docs/oauth-updates/?utm_source=strava&utm_medium=mktgemail&utm_campaign=2018_10_15_API_update

From Oct 15th, the current "forever tokens" will be rejected, and they are moving to short lived refresh tokens.

Unless I'm not looking in the right place, the Auth process is only forever token based, with no provision for obtaining a refresh token and short lived access token.

Are there any plans to integrate this Strava change into this library?

Thanks

Handling Strava's conversion to oauth2

There was another issue related to email that also was related to this same issue. I'm breaking it out into a separate issue. Forever tokens are gone as of yesterday (october 15th 2019). You must store a refreshtoken alongside a limited time (usually just a few hours) access token. The refreshtoken has no expiration, as it is the one that needs to be used to obtain the next access token.

Here is my code for obtaining the new accesstoken and refreshtoken using the existing refreshtoken. This is using the oauth2-client object this is a requirement/dependence of the basvandorst/stravaphp package.

The first param to the getAccessToken method is called the "grant type". Strava says you have to use "refresh_token" as the grant type when getting new token.

I am raising this as an issue here on this library because it seems like the best place to help people using this library even though I agree that I don't think this library needs to have support for refresh tokens. That has to exist at a higher level than this library because the person using the library has to store the refresh token somewhere. Still, I spent many hours trying to figure out how to do this and this is probably best place to put the info for people who need to use this library. Maybe add it to the documentation on the main page?

$options = array( 'clientId' => INSERT_YOUR_CLIENT_ID AS INTEGER, 'clientSecret' => INSERT YOUR CLIENT SECRET AS STRING, 'scopes' => ['activity:read_all'] NOT SURE WHETHER THIS HAS ANY IMPACT ); $oauth = new OAuth($options); $token = $oauth->getAccessToken('refresh_token',['refresh_token'=>$user->refreshtoken]); print_r($token);

Wrong scopes in README.md code examples

Hi guys.

Maybe I'm missing something, but example code in README.md doesn't work because of the wrong scope names:

        print '<a href="'.$oauth->getAuthorizationUrl([
            // Uncomment required scopes.
            'scope' => [
                'public',
                // 'write',
                // 'view_private',
            ]
        ]).'">Connect</a>';

The right ones are read, read_all, profile:read_all, profile:write, activity:read, activity:read_all, activity:write as in https://developers.strava.com/docs/authentication/#detailsaboutrequestingaccess and replacing them in the example code fixed the bad request error I was getting.

Cheers!

base_uri

$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3']);
should be with trailing /:
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3/']);

Scrutinizer

The Scrutinizer badges are either not working or not updated. I'm not familiar with this tool - if it is something you're still using I will peek at it. Otherwise I am happy to replace them with GitHub Action badges for the new workflows.

Throws deprecated warning on php 7.1

mcrypt has been deprecated since php 7.1 and this package throws a warning when trying to call OAuth::getAuthorizationUrl method. As I can see this method is defined in one of the dependencies, so it probably will not be a quick fix?.. :/

Setup Packagist for automatic updates

Packagist is not set up for autoupdates so version 2 has not actually posted. Please turn on autoupdating (preferred) or at least force an update manually.

upload , delete , update activity problem

Upload Activity
Getting error during upload activity like show in below screenshot

image

Here is the which i tried

 $actual_file = realpath('text.gpx');
 $file ='@'.$actual_file;
 $activity_type='ride';
 $data_type='gpx';
 $client->uploadActivity($file, $activity_type, $name = null, $description = null, $private = null, $trainer = null, $data_type, $external_id = null);

When i try to upload it manually with curl.. it's working fine.But Here API call uploadActivity is not working

Update Activity
Also your update activity call is wrong
change in readmi
$client->updateActivity($name = null, $type = null, $private = false, $commute = false, $trainer = false, $gear_id = null, $description = null);

to

 $client->updateActivity($id,$name = null, $type = null, $private = false, $commute = false, $trainer = false, $gear_id = null, $description = null);

delete Activity
In rest.php

Need to change

  public function deleteActivity($id) {
    $path = '/activities/'.$id;
    $result = $this->adapter->delete($path, array());
    return $this->format($result);
  }

to

    public function deleteActivity($id) {
    $path = '/activities/'.$id;
    $result = $this->adapter->delete($path, $this->getHeaders());
    return $this->format($result);
    }

How to setup new access token when working on one client object?

I like the library and the separation approach.
My use case seems typical but is not easy to implement with the flow needed by this lib.
I have several strava events registered by webhook and I process them asynchronously in a batch.
Each event might be on behalf of different athlete.
So I need to initialize one Client and then setup access token per API call. But the Client depends on REST which has that token.
Any ideas how to achieve that? Something like Client::setToken()?

In my other project I use iamstuartwilson/strava which supports full flow (integrated) but lacks other stuff (like streams).

Is there any way to deauthorize user?

Is there any way to deauthorize user to revoke access to an athlete’s data? I need to remove the application from the athlete’s apps settings page. Is it implemented?

Upload gpx file failed

$client->uploadActivity( '/var/www/466928184.gpx, 'ride', null, null, null, null, null, 'gpx', 466928184 );

failed with the following error:

[SERVICE] [SERVICE] Client error: POST https://www.strava.com/api/v3/uploads?activity_type=ride&data_type=gpx&external_id=466928184&file%5Bname%5D=%2Fvar%2Fwww%2F466928184.gpx&file%5Bmime%5D=&file%5Bpostname%5D=&file_hack=%40%2Fvar%2Fwww%2F466928184.gpx&access_token=*** resulted in a 400 Bad Request response: {"message":"Bad Request","errors":[{"resource":"Upload","field":"file","code":"not a file"}]}

Whats wrong?

Updated package dependencies

Hello,

Is is possible to get the version requirement for "league/oauth2-client" updated to something more recent? Currently they are on version 1.4.1 and this package requires 0.8.1.

Thanks,
Jay

Issue with refresh page: Required option not passed: "access_token"

Hi - firstly, thank you for making this repository.

I have a simple page below - api-001.php:

<?php
require '../../vendor/autoload.php';

use Strava\API\OAuth;
use Strava\API\Exception;
use Strava\API\Client;
use Strava\API\Service\REST;

try {
    $options = [
        'clientId'     => 123456,
        'clientSecret' => '9876543210',
        'redirectUri'  => 'http://localhost/strava/api-001.php'
    ];
    $oauth = new OAuth($options);

    if (!isset($_GET['code'])) {
        print '<a href="'.$oauth->getAuthorizationUrl([
            // Uncomment required scopes.
            'scope' => [
                'read',
                'read_all',
                'profile:read_all',
                'profile:write',
                'activity:read',
                'activity:read_all',
                'activity:write',
            ]
        ]).'">Connect</a>';
		
    } else {
		
        $token = $oauth->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);
		
        print $token->getToken();
		
		try {
			$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3/']);
			$service = new REST($token->getToken(), $adapter);  // Define your user token here.
			$client = new Client($service);
			$athlete = $client->getAthlete();
			print_r($athlete);
			$activities = $client->getAthleteActivities();
		} catch(Exception $e) {
			print $e->getMessage();
		}

    }
} catch(Exception $e) {
    print $e->getMessage();
}
?>

When I first access it, I click Connect and click Authorize.

I'm redirected to http://localhost/strava/api-001.php and can see my athlete info.

However, if I click F5 on the browser, I end up with this error:

PHP Fatal error:  Uncaught InvalidArgumentException: Required option not passed: "access_token" in C:\Data\Websites\vendor\league\oauth2-client\src\Token\AccessToken.php:96
Stack trace:
#0 C:\Data\Websites\vendor\league\oauth2-client\src\Provider\AbstractProvider.php(844): League\OAuth2\Client\Token\AccessToken->__construct(Array)
#1 C:\Data\Websites\vendor\league\oauth2-client\src\Provider\AbstractProvider.php(642): League\OAuth2\Client\Provider\AbstractProvider->createAccessToken(Array, Object(League\OAuth2\Client\Grant\AuthorizationCode))
#2 C:\Data\Websites\strava\api-001.php(33): League\OAuth2\Client\Provider\AbstractProvider->getAccessToken(Object(League\OAuth2\Client\Grant\AuthorizationCode), Array)
#3 {main}
  thrown in C:\Data\Websites\vendor\league\oauth2-client\src\Token\AccessToken.php on line 96

I realise the documentation on the main page for this repository has 2 sections:

First, authorisation and authentication

Then, call your API method!

I tried putting the code for the second part in a separate page, but then it errors on this line:

$service = new REST($token->getToken(), $adapter);  // Define your user token here.

Because I haven't defined $token which is why in my quoted code above I redirect to the same starting page api-001.php as that already has $token defined.

I thought maybe I can store $token in localStorage but I am not sure how I'd store $token in localStorage as it is an array I think, not just a variable with a single value.

Sorry for probably overlooking something very basic - but I cannot see how to set things up so that I can refresh the page, otherwise I have to go back to click Connect each time.

I checked these issues:

#92
#57

But can't work it out.

Sorry if it is something simple, I have basic PHP skills but am trying to work out what to do.

Thanks

PHPUnit tests fail when running locally

Hi,

Not sure if this is the correct place to raise this, but I am running PHPUnit on master and getting failures on the following tests:

public function testGetRouteAsGPX()
{
$restMock = $this->getRestMock();
$restMock->expects($this->once())->method('get')
->with($this->equalTo('routes/1234/export_gpx'))
->will($this->returnValue('<?xml version="1.0" encoding="UTF-8"?><gpx creator="StravaGPX"/>'));
$service = new \Strava\API\Service\REST('TOKEN', $restMock);
$output = $service->getRouteAsGPX(1234);
$this->assertInternalType('string', $output);
}

public function testGetRouteAsTCX()
{
$restMock = $this->getRestMock();
$restMock->expects($this->once())->method('get')
->with($this->equalTo('routes/1234/export_tcx'))
->will($this->returnValue('<?xml version="1.0" encoding="UTF-8"?><TrainingCenterDatabase/>'));
$service = new \Strava\API\Service\REST('TOKEN', $restMock);
$output = $service->getRouteAsTCX(1234);
$this->assertInternalType('string', $output);
}

I'm getting the error Trying to configure method "get" which cannot be configured because it does not exist, has not been specified, is final, or is static

Would anyone be able to point me to the reason why it's failing locally but not on scrutinizer?

Library Compatibility

Hi maintainers! I'm working with a client who needs Strava integrations - excited to see that someone has already wrapped this up into an SDK. There are a few incompatibilities (Guzzle being a big one, I see there has been some work on that). I will send a few PRs over to get this up-to-speed, then maybe some recommendations for a next major release that would have a lot of QOL improvements for PHP >= 7.4.

Please let me know if there are any guiding principles I should be aware of, as you have no contributing docs. Happy to hop on Discord/Slack/Discussions whatever.

Full Leaderboards

Hi,

  • is it possible to show more than 10 people on a leaderboard of a segment?
  • Is it possible to show a leaderboard without the athlete en the -2 and +2 atheletes who is connected?

Keep up the good work!

getStreamsRoute returns null.

I'm not sure if this is an issue with the library or Strava but the getStreamsRoute is returning null. Doing some dumping, it appears as thought the URL being called is returning a 301 even though it is correct according to the Strava documentation. (I confirmed the ID being called was valid via the Strava website)

Streams resolution parameter default value

Hey,
The default value of the resolution parameter in the streams function is set to all:

$client->getStreamsActivity($id, $types, $resolution = 'all', $series_type = 'distance');
$client->getStreamsEffort($id, $types, $resolution = 'all', $series_type = 'distance');
$client->getStreamsSegment($id, $types, $resolution = 'all', $series_type = 'distance');

The documentation isn't quite clear on this, but all isn't a valid value:

curl -G https://www.strava.com/api/v3/activities/683597852/streams/latlng -H "Authorization: Bearer abc" -d resolution=all

returns

{"message":"Bad Request","errors":[{"resource":"Application","field":"resolution","code":"invalid"}]}

As I understand it:
If you don't specify the parameter, all points are returned.
If you specify it (with low, medium or high), only (100/1000/10000) values are returned.

Integration with Laravel project

Dear Bas,

I am a learning developer and want to integrate your StravaPHP into my project. I can not find a lot of documentation on the installation process. Can you help me get started?

Thanks in advance,

Houdoe,

Thomas

Incorrect parameter name for getSegmentEffort

    $parameters = array(
        'bounds' => $athlete_id,
        'start_date_local' => $start_date_local,
        'end_date_local' => $end_date_local,
        'page' => $page,
        'per_page' => $per_page
    );

Should be:

    $parameters = array(
        'athlete_id' => $athlete_id,
        'start_date_local' => $start_date_local,
        'end_date_local' => $end_date_local,
        'page' => $page,
        'per_page' => $per_page
    );

Exceptions with Guzzle

Hi,

i know this perhaps isn't the right place but is anyone having issues handling exceptions since the update to use Guzzle?

This is my example code:

use Strava\API\OAuth;
use Strava\API\Client;
use Strava\API\Exception;
#use Strava\API\Exception\ClientException;
use Strava\API\Service\REST;
#use GuzzleHttp\Exception\RequestException;
#use GuzzleHttp\Exception\ClientException;

try{
    $token = $_SESSION['AuthToken'] ; 
    $adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3/']);
    $service = new REST($token, $adapter);
    
    $client = new Client($service);
    $athlete = $client->getAthlete();
    } catch (Exception $e){
    echo "in here";
            throw new Exception('Unauthorised');
            }

var_dump($athlete);

This returns:

string(209) "Client error: GET https://www.strava.com/api/v3/athlete resulted in a 401 Unauthorized response: {"message":"Authorization Error","errors":[{"resource":"Athlete","field":"access_token","code":"invalid"}]} "

I have tried loads of combinations of ClientException and Exception in different namespaces but do not get an exception thrown, as far as i can tell i am copying the readme examples. Does anyone have an idea what is have done wrong? This worked fine and caught the 401 errors with the previous version.

Thanks!
Richard

Null is returned when I try to get athlete or the activities

Hi everyone,

Many thanks for your time spending in this issue.
I am following all the steps and and I do receive a proper respond from strava and I do have the user_token, strava_user_id so all the credentials are fine. And after I check the user in Strava I do see my new application in My Apps. I have 2 old activities and 1 from today.

But I receive null when I
$adapter = new Pest('https://www.strava.com/api/v3'); $service = new REST('the_token', $adapter); // Define your user token here. $client = new Client($service); print_r($client->getAthlete()); //null print_r($client->getAthleteActivities()); //null

Do you have any idea do I miss anything or the API has changed as a few mounts ago it was working fine.

Thanks

Fix tests after type hints

The tests are broken because they now expect a return type and the mock service returns a json string. Also the mock data is incomplete.

Getting Map via Polyline

Having trouble displaying the map using the Polyline code retrieved from the activity object. Any ideas on how to display it (PHP or JS) ?

OAuth code upgrade is incomplete

#18 recently upgraded dependency league/oauth2-client from 0.8.1 to 1.4.2. That old version was an alpha one, and the abstract methods to implement changed in the final release 1.0.

Specifically, getUser*() methods were removed on 9 May 2015, and some of the new ones are left unimplemented here, e.g. createResourceOwner(). This is messy and should be fixed. I can take care of this.

userUid(), userEmail(), userScreenName() methods should be deprecated here, and removed in the next major release. The code to implement for the new methods is already available in Edwin-Luijten/oauth2-strava. We could copy it here (MIT license allows it), or make this package depend on it. Any preference?

getResponse doesn't throw, it already catches

Since this method in Rest.php catches and returns the error,
the try/catch in the method in Client.php doesn't work

    // see: https://github.com/basvandorst/StravaPHP/blob/master/src/Strava/API/Service/REST.php#L83
    protected function getResponse($method, $path, $parameters)
    {
        try {
            $response = $this->adapter->request($method, $path, $parameters);
            return $this->getResult($response);
        }
        catch (\Exception $e) {
            return $e->getMessage();
        }
    }

Client.php

    // See: https://github.com/basvandorst/StravaPHP/blob/master/src/Strava/API/Client.php#L120
    public function getAthleteActivities($before = null, $after = null, $page = null, $per_page = null)
    {
        try {
            return $this->service->getAthleteActivities($before, $after, $page, $per_page);
        } catch (ServiceException $e) {
            throw new ClientException('[SERVICE] ' . $e->getMessage());
        }
    }

Idea

Would it be an idea to rethrow (or remove the try/catch block in getResponse()
instead of returning $e->getMessage()?

getAthleteActivities is buggy when using parameters

Hello,

I don't really know what is happening but there is a problem when passing parameters.

If passing parameters, the method starts filtering results that it shouldn't.

I checked my parameters and tried the request manually into my browser with those parameters and it works fine so the problem is not from the Starva side, the filter works nice.

But when using the function:
getAthleteActivities($startTime, $endTime)

There are no results, so it is not matching the behavior from Strava. I checked the parameters into the Client class and they seem fine, I don't know if the HTTP headers are messing up the call or if the parameters are altered in a bad way before the HTTP call. Does someone else experience that?

If I don't pass the parameters before and after, the function returns the activities that are not filtered.

I was on 1.4 and I tried to revert to 1.2 to see if one of the latest update broke something, but it is still happening even with 1.2.

Webhook Subscriptions

The project I am working on needs Webhook subscriptions. The API actually has CRUD endpoints for push subscriptions. Would this library be interested in having these added? They function a little different vis-a-vis authentication because they exist at the service level (not individual accounts).

Composer update got error

Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for basvandorst/stravaphp 1.0.0 -> satisfiable by basvandorst/stravaphp[1.0.0].
- basvandorst/stravaphp 1.0.0 requires league/oauth2-client dev-master -> no matching package found.

Could you fix that?
Thank you.

Get "Required option not passed: "access_token"" message, when try to exchange token second time.

I test $oauth->getAccessToken() method in this section: https://github.com/basvandorst/StravaPHP#usage-1
When I call it first time with some token, everything is OK, I retrieve the following response:

image

But when I call it second time, I get an InvalidArgumentException:

image

I understand why this happens - there is no "access_token" in response, 'cause response looks like that:

image

But at first it was not obvious to me. Is it possible to handle this? I mean, is it possible to throw another exception, more clear, about exactly invalid authorization code; some exception, that clearly tells us, that we can't use same auth code twice? Then it would be easier to handle this more specific exception.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.