goosfraba/strava-sdk

Strava SDK for PHP

dev-main 2023-10-02 18:11 UTC

This package is auto-updated.

Last update: 2024-08-31 00:45:59 UTC


README

此包提供了Strava API的高级SDK

安装

使用composer安装此包

composer require goosfraba/strava-sdk

用法

本节展示了如何使用SDK

请求访问URL

SDK提供了一个方便的方法来生成请求访问URL(例如,用于与Strava连接的按钮)。

use Goosfraba\StravaSDK\Access\RequestAccessUrl;
use Goosfraba\StravaSDK\Access\Scope;
use Goosfraba\StravaSDK\Access\ApprovalPrompt;

$url = (string)(new RequestAccessUrl(
    "231243", // your app client ID
    "https://your-app.com/strava/access-granted", // the callback URL
    [
        Scope::general(true), // general scope "read_all"
        Scope::profile(false), // profile resource scope "read"
        Scope::activity(false, true), // activity resource scope "read" and "write",
    ], // the list of the scopes, select whatever your app needs
    null, // optional: the state of your application (passed to your callback URL in query string) 
    ApprovalPrompt::auto() // optional: the approval prompt mode, "auto" by default
));

身份验证(与Strava连接)

为了使用API,您需要利用传递到您的回调URL的code。以下是一个示例控制器,用于处理回调URL。

免责声明:此控制器仅用于演示目的,用于展示流程和特定SDK组件的工作方式。它以任何方式都不处于生产状态。

use Goosfraba\StravaSDK\Auth\AuthApi;
use Goosfraba\StravaSDK\Auth\AuthApiFactory;
use Goosfraba\StravaSDK\Auth\ClientCredentials;

class StravaCallbackController
{
    private AuthApi $authApi;
    
    public function __construct(AuthApi $authApi)
    {
        $oAuthApiFactory = new AuthApiFactory();
        $this->authApi = $oAuthApiFactory->create(
            new ClientCredentials("your app id", "your app secret")
        );
    }
    
    /**
     * 
     */
    public function accessGranted($request)
    {
        // "code" from the query string of the URL
        $tokenResponse = $this->authApi->authorise($request["code"]);
        
        // "state" from the query string of the callback URL
        $state = $request["state"]; // whatever was passed into the access request URL
        
        /**
         * The athlete that gave the permissions.
         * Link it with your user.
         */
        $athlete = $tokenResponse->athlete()
        
        /**
         * The OAuth token to be used in further queries.
         * Save it along with the user.
         */           
        $oAuthToken = $tokenResponse->token(); 
    }
}

OAuthApi

此API允许授权您的应用程序,刷新访问令牌并取消授权您的应用程序。

创建OAuthAPi

use Goosfraba\StravaSDK\Auth\AuthApiFactory;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Goosfraba\StravaSDK\Auth\ClientCredentials;

/**
 * The event dispatcher is an important component in the flow od the API usage.
 * The APIs support automatic token refresh, and you want to make sure you store the latest viable token.
 * More in the section "Automatic Token Refresh"
 */
$oAuthApiFactory = new AuthApiFactory();

$oAuthApi = $oAuthApiFactory->create(new ClientCredentials("your app id", "your app secret"));

授权

授权过程生成OAuth令牌并返回运动员的详细信息

/** @var \Goosfraba\StravaSDK\Auth\AuthApi $oAuthApi */
$code = "32443534safgfgsfgfssew3224323"; // the code from the callback URL
$tokenResponse = $oAuthApi->authorise($code);
$token = $tokenResponse->token();
$athlete = $tokenResponse->athlete();

取消授权

取消授权过程将您的应用程序从运动员的Stava账户中取消链接

/** @var \Goosfraba\StravaSDK\Auth\AuthApi $oAuthApi */
/** @var \Goosfraba\StravaSDK\Auth\AuthToken $token */
$oAuthApi->deAuthorize($token);

令牌刷新

过期的访问令牌需要不时刷新。

/** @var \Goosfraba\StravaSDK\Auth\AuthApi $oAuthApi */
/** @var \Goosfraba\StravaSDK\Auth\AuthToken $token */
$newToken = $oAuthApi->refreshToken($token);

自动令牌刷新

所有API都支持自动令牌刷新。您需要确保您已存储了最新的有效令牌。为了做到这一点,您需要向OAuthApi提供OAuthTokenCallback实现。

示例实现

use Goosfraba\StravaSDK\Auth\TokenCallback\OAuthTokenCallback;
use Goosfraba\StravaSDK\Auth\AuthToken;

final class YourAppOAuthTokenCallback implements OAuthTokenCallback
{
    private UserRepository $userRepository;
    
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function onAuthorise(string $code, AuthorisationResponse $tokenResponse): void
    {
        $user = new User(
            // fill up the data from the token response
        );
        $user->updateStravaToken($tokenResponse->token());
        
        $this->userRepository->save($user);
    }

    public function onDeAuthorise(AuthToken $token): void
    {
        $user = $this->userRepository->findByStravaToken($token);
        if (!$user) {
            return;
        }
        
        $user->deAuthoriseStrava();
        $this->userRepository->save($user);
    }

    public function onTokenRefresh(AuthToken $newToken, AuthToken $oldToken): void
    {        
        $user = $this->userRepository->findByStravaToken($oldToken);        
        $user->updateStravaToken($newToken);
        $this->userRepository->save($user);
    }
}

注册您的令牌回调

use Goosfraba\StravaSDK\Auth\AuthApiFactory;
/** @var UserRepositroy $userRepository */

$oAuthApiFactory = new AuthApiFactory(
    new YourAppOAuthTokenCallback($userRepository)
);

ApiFactory组件

此组件创建特定API的实例。

use Goosfraba\StravaSDK\ApiFactory;use Goosfraba\StravaSDK\Auth\AuthToken;use Goosfraba\StravaSDK\Http\Buzz\AuthenticatedBrowserFactory;

$apiFactory = new ApiFactory(
    new AuthenticatedBrowserFactory(
        $oAuthApi,
        new AuthToken("refresh token", "access token")
    )
);

AthletesApi

创建AthletesApi

use Goosfraba\StravaSDK\ApiFactory;

/** @var ApiFactory $apiFactory */

$athletesApi = $apiFactory->athletesApi();

支持的操作

  • getAuthenticatedAthlete - 获取已认证运动员的详细信息

ActivitiesApi

创建ActivitiesApi

use Goosfraba\StravaSDK\ApiFactory;

/** @var ApiFactory $apiFactory */

$activitiesApi = $apiFactory->activitiesApi();

支持的操作

  • listAthleteActivities - 列出已认证运动员的活动
  • getActivity - 根据ID获取单个活动
  • createActivity - 创建新的活动
  • updateActivity - 更新现有活动
  • listActivityComments - 列出给定活动的评论
  • listActivityKudoers - 列出给定活动的赞者
  • listActivityLaps - 列出给定活动的圈数
  • listActivityZones - 列出给定活动的区域