Switch calls to use Client ID instead of Access Token

This commit is contained in:
Justin Foell
2019-06-03 16:07:15 -05:00
parent 33c0deb870
commit 520bd1b649
10 changed files with 125 additions and 57 deletions
+60 -7
View File
@@ -7,10 +7,27 @@ class WPStrava_API {
const STRAVA_V3_API = 'https://www.strava.com/api/v3/';
public function __construct( $access_token = null ) {
$this->access_token = $access_token;
private $client_id = null;
/**
* Constructor.
*
* @param int $client_id Strava API Client ID representing an athlete.
* @author Justin Foell <justin@foell.org>
*/
public function __construct( $client_id = null ) {
$this->client_id = $client_id;
}
/**
* POST something to the Strava API.
*
* @param string $uri Path within the Strava API.
* @param array $data Data to POST.
* @return stdClass Strava API response.
* @throws WPStrava_Exception
* @author Justin Foell <justin@foell.org>
*/
public function post( $uri, $data = null ) {
$url = self::STRAVA_V3_API;
@@ -21,8 +38,9 @@ class WPStrava_API {
'timeout' => 30,
);
if ( $this->access_token ) {
$args['headers']['Authorization'] = 'Bearer ' . $this->access_token;
$access_token = $this->get_access_token();
if ( $access_token ) {
$args['headers']['Authorization'] = 'Bearer ' . $access_token;
}
$response = wp_remote_post( $url . $uri, $args );
@@ -53,6 +71,15 @@ class WPStrava_API {
return json_decode( $response['body'] );
}
/**
* GET something from the Strava API.
*
* @param string $uri Path within the Strava API.
* @param array $args Request arguments.
* @return stdClass Strava API response.
* @throws WPStrava_Exception
* @author Justin Foell <justin@foell.org>
*/
public function get( $uri, $args = null ) {
$url = self::STRAVA_V3_API;
@@ -68,8 +95,9 @@ class WPStrava_API {
'timeout' => 30,
);
if ( $this->access_token ) {
$get_args['headers']['Authorization'] = 'Bearer ' . $this->access_token;
$access_token = $this->get_access_token();
if ( $access_token ) {
$get_args['headers']['Authorization'] = 'Bearer ' . $access_token;
}
$response = wp_remote_get( $url, $get_args );
@@ -102,4 +130,29 @@ class WPStrava_API {
return json_decode( $response['body'] );
}
} // Class API.
/**
* Get the (ever changing) access token based on current Client ID.
*
* @return string|null String for access token, null if not found.
* @author Justin Foell <justin@foell.org>
* @since 2.0.0
*/
private function get_access_token() {
static $access_token = null;
// If client_id not set (OAuth set-up), don't even look.
if ( ! $this->client_id ) {
return null;
}
if ( ! $access_token ) {
$settings = WPStrava::get_instance()->settings;
$info = $settings->info;
if ( ! empty( $info[ $this->client_id ]->access_token ) ) {
$access_token = $info[ $this->client_id ]->access_token;
}
}
return $access_token;
}
}