A laravel package to access data from the Strava API.

Overview
GitHub release GitHub watchers GitHub stars GitHub forks GitHub code size in bytes GitHub issues GitHub last commit

Laravel Strava Package

A laravel package to access data from the Strava API. Compatible with Laravel 5.0 and above.

Table of Contents

Strava Access Credentials

In order to use this package you will need to create an app from within your strava account. Create Strava App to access your API credentials. Click here for more information on the Strava API.

Installation

To install the package within your laravel project use the following composer command:

composer require codetoad/strava

Publish Strava Config File

The vendor:publish commmand will publish a file named ct_strava.php within your laravel project config folder config/ct_strava.php. Edit this file with your Strava API credentials, generated from the Strava app you created.

php artisan vendor:publish --provider="CodeToad\Strava\StravaServiceProvider"

Published Config File Contents

'client_id' => env('CT_STRAVA_CLIENT_ID', '')
'client_secret' => env('CT_STRAVA_SECRET_ID', '')
'redirect_uri' => env('CT_STRAVA_REDIRECT_URI', '')

Alternatively you can ignore the above publish command and add this following variables to your .env file. Make sure to add your Strava App credentials

CT_STRAVA_CLIENT_ID=ADD-STRAVA-CLIENT-ID-HERE
CT_STRAVA_SECRET_ID=ADD-STRAVA-SECRET-HERE
CT_STRAVA_REDIRECT_URI=ADD-STRAVA-REDIRECT-URI-HERE

Auto Discovery

If you're using Laravel 5.5+ you don't need to manually add the service provider or facade. This will be Auto-Discovered. For all versions of Laravel below 5.5, you must manually add the ServiceProvider & Facade to the appropriate arrays within your Laravel project config/app.php

Provider

CodeToad\Strava\StravaServiceProvider::class,

Alias / Facade

'Strava' => CodeToad\Strava\StravaFacade::class,

Usage

Use Strava Facade

Add the Strava facade to the top of your controller so you can access the Strava class methods.

use Strava;

class MyController extends Controller
{
  // Controller functions here...
}

Authenticate User

Call the Strava::authenticate() method to redirect you to Strava. If authentication is successful the user will be redirected to the redirect_uri that you added to the config file or your .env file. You may now also pass $scope as a parameter when authenticating. You can add or remove scopes as required. Some are required, some are optional. Details on available scopes can be seen here Strava Authentication Scopes

public function stravaAuth()
{
  return Strava::authenticate($scope='read_all,profile:read_all,activity:read_all');
}

Obtain User Access Token

When returned to the redirected uri, call the Strava::token($code) method to generate the users Strava access token & refresh token. The tokens are generated using the code parameter value within the redirected uri. Be sure to store the users access_token & refresh_token in your database.

public function getToken(Request $request)
{
  $token = Strava::token($request->code);

  // Store $token->access_token & $token->refresh_token in database
}

Example Response

"token_type": "Bearer"
"expires_at": 1555165838
"expires_in": 21600 // 6 Hours
"refresh_token": "671129e56b1ce64d7e0c7e594cb6522b239464e1"
"access_token": "e105062b153da39f81a439b90b23357c741a40a0"
"athlete": ...

At this point you have access to the Athlete object that can be used to login to your website. Of course you'll need to write the logic for your login system, but the athlete name, email etc.. is contained within the object for you to verify the user against your own database data.

Access Token Expiry

Access tokens will now expire after 6 hours under the new flow that Strava have implemented and will need to be updated using a refresh token. In the example above you can see the response has a refresh_token and an expires_at field. When storing the user access tokens you may also want to store the expires_at field too. This will allow you to check when the current access token has expired.

When calling any of the Strava methods below you may want to compare the current time against the expires_at field in order to validate the token. If the token is expired you'll need to call the Strava::refreshToken($refreshToken) method in order to generate a new tokens. All you need to do is pass the users currently stored refresh_token, the method will then return a new set of tokens (access & refresh), update the current users tokens with the new tokens from the response. Heres an example of how that might work, using the Strava::athlete($token) method.

use Carbon\Carbon;

public function myControllerFunction(Request $request)
{
  // Get the user
  $user = User::find($request->id);

  // Check if current token has expired
  if(strtotime(Carbon::now()) > $user->expires_at)
  {
    // Token has expired, generate new tokens using the currently stored user refresh token
    $refresh = Strava::refreshToken($user->refresh_token);

    // Update the users tokens
    User::where('id', $request->id)->update([
      'access_token' => $refresh->access_token,
      'refresh_token' => $refresh->refresh_token
    ]);

    // Call Strava Athlete Method with newly updated access token.
    $athlete = Strava::athlete($user->access_token);

    // Return $athlete array to view
    return view('strava.athlete')->with(compact('athlete'));

  }else{

    // Token has not yet expired, Call Strava Athlete Method
    $athlete = Strava::athlete($user->access_token);

    // Return $athlete array to view
    return view('strava.athlete')->with(compact('athlete'));

  }

}

Unauthenticate User

You can allow users to unauthenticate their Strava account with your Strava app. Simply allow users to call the following method, passing the access token that has been stored for their account.

Strava::unauthenticate($token);

Available Methods

All methods require an access token, some methods accept additional optional parameters listed below.

  • Optional Parameters
    • $page (Int - default 1)
    • $perpage (Int - default 10)
    • $before (Int/Timestamp - default = most recent)
    • $after (Int/Timestamp - default = most recent)

Athlete Data

Returns the currently authenticated athlete.

Strava::athlete($token);

User Activities Data

Returns the activities of an athlete.

Strava::activities($token, $page, $perPage, $before, $after);

User Single Activity

Returns the given activity that is owned by the authenticated athlete.

Strava::activity($token, $activityID);

User Single Activity Stream

Returns the given activity's streams.

// $keys is a string array containing required streams
// e.g. ['latlng', 'time']
Strava::activityStream($token, $activityID, $keys = '', $keyByType = true);

Activity Comments

Returns the comments on the given activity.

Strava::activityComments($token, $activityID, $page, $perPage);

Activity Kudos

Returns the athletes who kudoed an activity.

Strava::activityKudos($token, $activityID, $page, $perPage);

Activity Laps

Returns the laps data of an activity.

Strava::activityLaps($token, $activityID);

Activity Zones

Summit Feature Required. Returns the zones of a given activity.

Strava::activityZones($token, $activityID);

Update Activity

Updates the given activity that is owned by the authenticated athlete. Requires activity:write, so in order to update activities, you will need to authenticate as follows: Strava::authenticate('read_all,profile:read_all,activity:read_all,activity:write');.

Strava::updateActivityById($token, $activityID, array $updateableActivity);

You may update one or more individual parameters from the following:

// Example $updateableActivity
$updateableActivity = [
    'commute' => false,
    'trainer' => false,
    'description' => 'Easier ride than usual',
    'name' => 'Fun ride',
    'type' => 'Ride', // string, instance of ActivityType
    'gear_id' => 'b12345678987654321',
];

Find additional details in the official Strava documentation:

Athlete Zones

Returns the the authenticated athlete's heart rate and power zones.

Strava::athleteZones($token);

Athlete Stats

Returns the activity stats of an athlete.

Strava::athleteStats($token, $athleteID, $page, $perPage);

Club

Returns a given club using its identifier.

Strava::club($token, $clubID);

Club Members

Returns a list of the athletes who are members of a given club.

Strava::clubMembers($token, $clubID, $page, $perPage);

Club Activities

Retrieve recent activities from members of a specific club. The authenticated athlete must belong to the requested club in order to hit this endpoint. Pagination is supported. Athlete profile visibility is respected for all activities.

Strava::clubActivities($token, $clubID, $page, $perPage);

Club Admins

Returns a list of the administrators of a given club.

Strava::clubAdmins($token, $clubID, $page, $perPage);

Athlete Clubs

Returns a list of the clubs whose membership includes the authenticated athlete.

Strava::athleteClubs($token, $page, $perPage);

Gear

Returns equipment data using gear ID.

Strava::gear($token, $gearID);

Route

Returns a route using its route ID.

Strava::route($token, $routeID);

Athlete Routes

Returns a list of the routes created by the authenticated athlete using their athlete ID.

Strava::athleteRoutes($token, $athleteID, $page, $perPage);

Segment

Returns the specified segment.

Strava::segment($token, $segmentID);

Segment Effort

Returns a segment effort from an activity that is owned by the authenticated athlete.

Strava::segmentEffort($token, $segmentID);

Starred Segments

List of the authenticated athlete's starred segments.

Strava::starredSegments($token, $page, $perPage);

Getting API Limits

Strava returns information about API calls allowance and usage in response headers.

The methods listed below will return this information upon a call which uses up the API limit (like fetching activities). Some calls like refreshing access tokens seem not to use up the API call limit, that's why you will get nulls in the resulting array.

As well when you try to get the limits at the very beginning, before any API call using up the limits , you will receive nulls. The default allowance limits are not hardcoded as different accounts may have different limits.

All API Limits

Returns all limits in a multidimensional array, eg.:

[  
	['allowance']['15minutes'] => "100",  
	['allowance']['daily'] => "1000",  
	['usage']['15minutes'] => "7",  
	['usage']['daily'] => "352",  
]
Strava::getApiLimits();

Allocated API Limits

Returns daily and 15-minute request limits available for the Strava account , eg.:

[  
	['15minutes'] => '100',  
	['daily'] => '1000',  
]
Strava::getApiAllowanceLimits();

Used API Calls

Returns number of daily and 15-minute calls used up at the Strava account , eg.:

[  
	['15minutes'] => '7',  
	['daily'] => '352',  
]
Strava::getApiUsageLimits();

Parameter Types

$token        = string
$activityID   = integer
$athleteID    = integer
$clubID       = integer
$gearID       = integer
$routeID      = integer
$segmentID    = integer
$page         = integer
$perPage      = integer
$before       = integer (timestamp)
$after        = integer (timestamp)

Caching

It's highly recommended that you cache your requests made to Strava for 2 reasons.

(1) Rate Limiting

Strava have API Rate Limit of 100 requests every 15 minutes and 10,000 daily. If your website has high traffic you might want to consider caching your Strava response data so you don't exceed these limits.

(2) Website Loading Speed

Caching your Strava data will drastically improve website load times.

Useful Links

Comments
  • The scope variable is not accepted during the authorization process

    The scope variable is not accepted during the authorization process

    Describe the bug Trying to authorize my application, which works in a way, but I need a specific scope. The scope I sent to

    Strava::authenticate($scope='my needed scope here');

    does not work

    To Reproduce Steps to reproduce the behavior: in the code the URL is hardcoded when it comes to the scope Class Strava line 37

    # # Strava Authenticate # public function authenticate() { return redirect('https://www.strava.com/oauth/authorize?client_id='. $this->client_id .'&response_type=code&redirect_uri='. $this->redirect_uri . '&scope=read_all,profile:read_all,activity:read_all&state=strava'); }

    Expected behavior I think it would be sufficient to have a parameter for the scope in the ct_strava.php file

    opened by edwink75 5
  • Getting API limits from response headers

    Getting API limits from response headers

    Strava returns information about API calls allowance and usage in response headers. Let's read it and make this information available inside the class.

    I updated as well the readme file with explanations on how to use the new methods.

    opened by boryn 3
  • Laravel 7 Compatibility

    Laravel 7 Compatibility

    Currently installation fails on a fresh copy of Laravel 7.

    I believe this is just a fix to dependencies in composer.json, but wanted to create a request to discuss which version strings to use now that Laravel is on a 6 monthly major release schedule. Currently some other packages are using ^8.0 for things like laravel/support

    opened by iDemonix 3
  • Fix method on single activity

    Fix method on single activity

    This would allow users the ability to add events back to Strava if they have the correct scope on their activity token.

    Usage

    $activities = Strava::createActivity($token, [
        'name' => 'Testing API',
        'type' => 'Workout',
        'start_date_local' => now()->toIso8601String(),
        'elapsed_time' => 60,
        'description' => 'I passed through the seven levels of the Candy Cane forest, through the sea of swirly twirly gum drops, and then I walked through the Lincoln Tunnel.',
        'trainer' => 1,
    ]);
    
    opened by modernben 2
  • Getting API limits from response headers

    Getting API limits from response headers

    Strava returns information about API calls allowance and usage in response headers. Let's read it and make this information available inside the class.

    I updated as well the readme file with explanations on how to use the new methods.

    opened by boryn 2
  • segmentExplorer

    segmentExplorer

    Is your feature request related to a problem? Please describe. Can you add this feature?

    Describe the solution you'd like

    # Strava Segments explore
    #
    public function exploreSegments($token, $bounds, $activity_type)
    {
        $url = $this->strava_uri . '/segments/explore?bounds='. $bounds .'&activity_type=' . $activity_type;
        $config = $this->bearer($token);
        $res = $this->get($url, $config);
        return $res;
    }
    

    Thank you

    opened by MaoX17 2
  • Allow for querying using before and after

    Allow for querying using before and after

    Adds the ability to query via after & before, e.g Strava::activities($user->access_token, 10, '1554076800', '1556668799')

    https://developers.strava.com/docs/reference/#api-Activities-getLoggedInAthleteActivities

    opened by leepownall 2
  • Getting API limits from response headers

    Getting API limits from response headers

    Strava returns information about API calls allowance and usage in response headers. Let's read it and make this information available inside the class.

    I updated as well the readme file with explanations on how to use the new methods.

    opened by boryn 1
  • Define Callback URI

    Define Callback URI

    Hiya,

    Great package. Would love to be able to define a callback URI per request.

    Relatively simple, I can do a pull request if you like?

    return Strava::authenticate($scope='read_all,profile:read_all,activity:read_all', $redirect_uri);

    opened by lachlanhickey 1
  • Fix loading strava credentials

    Fix loading strava credentials

    First time I used laraval, wanted to experiment with this package but the config was located at a different key. Was using laraval 7.

    Maybe I did something wrong but I couldn't figure it out.

    opened by BramG 1
  • Strava::activities($token, $perPage, $after, $before);

    Strava::activities($token, $perPage, $after, $before);

    User Activities Data In the guidelines you have this... Strava::activities($token, $perPage, $after, $before);

    Unless I am missing something the function looks like this and is missing the parameters

    public function activities($token, $perPage = 10)
        {
            $url = $this->strava_uri . '/athlete/activities?per_page=' . $perPage;
            $config = $this->bearer($token);
            $res = $this->get($url, $config);
            return $res;
        }
    

    I re-worked mine to look like this, so I can fetch all activities by offsetting the page

    public function activities($token, $perPage = 10, $page = 1)
        {
            $url = $this->strava_uri . '/athlete/activities?per_page=' . $perPage .  '&page=' . $page;
            $config = $this->bearer($token);
            $res = $this->get($url, $config);
            return $res;
        }
    
    opened by ghost 1
  • Define Callback URI

    Define Callback URI

    Fixes #17

    Default value is still defined by the environment variable CT_STRAVA_REDIRECT_URI. But it can now be overriden in the function call:

    return Strava::authenticate($scope='read_all,profile:read_all,activity:read_all', $redirect_uri);
    
    opened by clementmas 0
Releases(1.0.12)
Owner
Richie
Student @ DKIT
Richie
Login system designed by fragX to validate the user and prevent unauthorized access to confidential data.

Login_System v.0.1 Login system designed by fragX to validate the user and prevent unauthorized access to confidential data. ?? Features Sign In and S

fragX 1 Jan 28, 2022
This project uses dflydev/dot-access-data to provide simple output filtering for cli applications.

FilterViaDotAccessData This project uses dflydev/dot-access-data to provide simple output filtering for applications built with annotated-command / Ro

Consolidation 44 Jul 19, 2022
A package to access messari apis for laravel

Messari API - Laravel Laravel wrapper for messari.io API Full API documentation could be found on messari.io Installation PHP 7.2+ and Composer are re

Seyyed Ahmad Mousavi 2 Apr 13, 2022
Provides access to Pexels API for Laravel projects

Laravel Pexels Provides access to Pexels API for Laravel projects Table of contents Installation Using Installation To get the latest version of Larav

Raviga Group Limited 3 Dec 1, 2022
The Laravel Boilerplate Project - https://laravel-boilerplate.com - For Slack access, visit:

Laravel Boilerplate (Current: Laravel 8.*) (Demo) Demo Credentials Admin: [email protected] Password: secret User: [email protected] Password: secret Offici

Anthony Rappa 5.4k Jan 7, 2023
An easy way to get vendor and package data from Packagist via API calls

Laravel Packagist Laravel Packagist (LaravelPackagist) is a package for Laravel 5 to interact with the packagist api quickly and easily. Table of cont

Jeremy Kenedy 5 Jul 18, 2022
A dynamic table component for Laravel Livewire - For Slack access, visit:

A dynamic Laravel Livewire component for data tables. Bootstrap 4 Demo | Bootstrap 5 Demo | Tailwind Demo | Demo Repository Installation You can insta

Anthony Rappa 1.3k Jan 1, 2023
Access laravel log through Filament admin panel

Access laravel log through Filament admin panel Features Syntax highlighting Quickly jump between start and end of the file Refresh log contents Clear

Guilherme Saade 20 Nov 22, 2022
Laravel Simple Access Log

Laravel Simple Access Log Many systems need to log user access for auditing purposes. This package creates a database table with sensible fields for l

Irfaan Nujjoo 0 Jan 13, 2022
Control frontend access to properties/methods in Livewire using PHP 8 attributes.

This package adds PHP 8.0 attribute support to Livewire. In specific, the attributes are used for flagging component properties and methods as frontend-accessible.

ARCHTECH 83 Dec 17, 2022
A multitool library offering access to recommended security related libraries, standardised implementations of security defences, and secure implementations of commonly performed tasks.

SecurityMultiTool A multitool library offering access to recommended security related libraries, standardised implementations of security defences, an

Pádraic Brady 131 Oct 30, 2022
Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Laratips 27 Mar 2, 2022
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
Laravel Grid is a package that helps you display table data.

Laravel Grid Laravel Grid is a package that helps you display table data. I could not find package that would satisfy my needs so I decided to write o

null 9 Nov 29, 2022
Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Ogundiran Adewale Charles 2 Jul 27, 2022
Laravel package to normalize your data before saving into the database.

This package helps you normalize your data in order to save them into the database. The Goal is to having separate classes that handle the data normalization, and thus can be tested independently.

Nicolas Widart 11 Apr 21, 2021
Laravel 5.* package to easily introduce a transformation layer for your data

Laraformer Laraformer is a laravel 5.* package that lets you easily introduce a transformation layer for your data. Laraformer (originated from Larave

Kamran Ahmed 30 Oct 19, 2022
A Laravel package to fetch Open Graph data of a website.

OpenGraph is a laravel package to fetch Open Graph metadata of a website/link. Features Easily fetch metadata of a URL. Laravel OpenGraph fetches all

Shashi Prakash Gautam 128 Dec 24, 2022
Laravel package to work with geospatial data types and functions.

Laravel Spatial Laravel package to work with geospatial data types and functions. For now it supports only MySql Spatial Data Types and Functions. Sup

Tarfin 47 Oct 3, 2022