首页 > 解决方案 > 如何使用 PHP 获取访问令牌 Strava Api

问题描述

public function auth_callback()
{
  if ($this->input->get("code") != null)
  {
    $this->Strava_model->UpdateProfileStravaToken($this->input->get("code"),$this->session->userdata("athlete_id"));
    $url = "http://www.strava.com/oauth/token?client_id=[xxxxx]&client_secret=[xxxxxxxxxxx]&code=".$this->input->get("code")."&grant_type=authorization_code";
            
    $post = array();
    $options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($post)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }

        var_dump($result);
        echo $result;exit;
            
        $cURLConnection = curl_init($url);
        curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $post);
        curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

        $apiResponse = curl_exec($cURLConnection);
        curl_close($cURLConnection);
        $jsonArrayResponse = json_decode($apiResponse);
            
        redirect($this->config->item("base_url") . "/activity");
  }
}

我设法获取代码,现在继续获取访问令牌。

我使用 php curl 发送帖子如下:

http://www.strava.com/oauth/token?client_id= [xxxx]&client_secret=[xxxxx]&code=[从重定向中检索代码]&grant_type=authorization_code

一旦我执行上面的代码,我就会得到这个“你正在被重定向.....”

任何人都可以提供建议和帮助吗?

标签: phpstrava

解决方案


通常,对 OAuth2 令牌端点的请求需要在请求正文中作为表单数据传递参数。根据您当前的来源,您正在发送一个空的请求正文。


推荐阅读