【问题标题】:Instagram New API - how to get authorization code using purely PHP codeInstagram 新 API - 如何使用纯 PHP 代码获取授权代码
【发布时间】:2020-01-30 10:54:07
【问题描述】:

主要目标:获取 access_token,以便我可以在网站上显示我的 Instagram 供稿。

目前,要获取访问令牌,我们去这个url点击授权获取代码,进一步交换access_token。

 https://api.instagram.com/oauth/authorize
  ?client_id={app-id}
  &redirect_uri={redirect-uri}
  &scope=user_profile,user_media
  &response_type=code

现在,如果我正在编写一个 PHP-curl 脚本来发送此 access_token 并获取我的帖子,我将如何每次获取访问令牌,我无法在每次我的 API 请求数据时真正点击授权,进一步,点击每 60 天授权一次对我来说也不是一个长期的解决方案。

所以我希望有办法(我可以调用此 URL,并直接获取授权码?)

到目前为止我的脚本:

$authURL = "https://api.instagram.com/oauth/authorize
?client_id=$client_id
&redirect_uri=$redirect_uri
&scope=user_profile,user_media
&response_type=code";

//STEP 1, GET THE AUTHORIZATION CODE (i am stuck here, how to get code from only PHP, 
//without external clicks..)
//https://www.redirecturl.com?code=AQgw#_

$authorization_code = '48FduaX0g.....VZIj';

//STEP 2 GIVE THE CODE FOR TOKEN

$url = 'https://api.instagram.com/oauth/access_token';
$myjson = "
            {'client_id': $client_id,
             'client_secret': $client_secret,
             'grant_type':'authorization_code',
             'redirect_uri':$redirect_uri,
             'code': $authorization_code
            }";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myjson);
$result = curl_exec($ch);
curl_close($ch);

$insta_details = json_decode($result);
echo $insta_details['access_token'];


curl -X GET \
  'https://graph.instagram.com/17841405793187218/media?access_token=IGQVJ...'

【问题讨论】:

    标签: php rest curl instagram instagram-graph-api


    【解决方案1】:

    授权步骤需要人工交互才能使用用户名/密码登录。所以没有办法只通过 PHP 来做到这一点。

    但是如果你只需要使用 PHP 在网站上显示一个提要,你可以使用这个包:https://packagist.org/packages/espresso-dev/instagram-basic-display-php

    在认证后的回调中获取code

    $code = $_GET['code'];

    然后使用以下方法:

    • getOAuthToken() 获取初始令牌
    • getLongLivedToken() 获取有效期为 60 天的长寿命令牌

    存储长期存在的令牌,以便可用于检索帖子,只需每 50 天左右调用一次refreshToken() 方法即可在后台刷新令牌并更新您正在使用的令牌。

    【讨论】:

    • 我可以不使用 echo "Login with Instagram" 来获取代码吗? .. 我的意思是我的网站访问者必须点击该锚点才能查看帖子,对吗?我希望访问者在主页上看到这些帖子..而不需要这样的交互..
    • 您自己的帖子,还是访问者的帖子?如果是为了您自己的帖子,那么不,他们不需要使用他们的 Instagram 帐户登录。您将使用自己的帐户令牌来显示提要。
    • 想在我自己的网站上显示我自己的帖子。是的,那么我将如何获得这些令牌?每 60 天后,我必须通过单击授权继续重新生成它们?
    • 不,您可以使用上述和文档中提到的刷新端点:developers.facebook.com/docs/instagram-basic-display-api/guides/…
    • github.com/Divya-Singal/instagram-basic-display-php 请关注此问题,如果它适合您,请为这个问题投票! @灵魂之火
    猜你喜欢
    • 2017-09-15
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2020-03-10
    • 1970-01-01
    相关资源
    最近更新 更多