无法使用提供的PHP API从Instagram获取图像

时间:2016-11-17 02:18:39

标签: php curl instagram-api

我正在尝试使用Instagram PHP API来获取朋友的照片。我注册了一个沙箱用户以及一个没有随机图像的虚拟用户。然后,我邀请虚拟用户在沙盒中授予应用以连接他的帐户。

要获取访问令牌,我发送获取代码的请求,然后获取带范围的访问令牌:

https://api.instagram.com/oauth/access_token?client_id=CLIENT_ID&client_secret=SECRET_STRING&grant_type=authorization_code&redirect_uri=http://localhost/&code=CODE&scope=basic+public_content+comments+likes`

PHP代码:

$url = 'https://api.instagram.com/oauth/access_token';
    $payload = [
            $GLOBALS['KEY_CID'] => $GLOBALS['VAL_CID'],
            $GLOBALS['KEY_CECRET'] => $GLOBALS['VAL_CECRET'],
            'grant_type' => 'authorization_code',
            'redirect_uri' => 'http://localhost/',
            'code' => $param_code,
            'scope' => 'basic+public_content+comments+likes'];

$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url); // url
        curl_setopt($ch, CURLOPT_POST, true); // POST
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); // POST DATA
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN RESULT true
        curl_setopt($ch, CURLOPT_HEADER, 0); // RETURN HEADER false
        curl_setopt($ch, CURLOPT_NOBODY, 0); // NO RETURN BODY false / we need the body to return
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // VERIFY SSL HOST false
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VERIFY SSL PEER false
$response = json_decode(curl_exec($ch), true);
curl_close($ch);

成功获得访问令牌后。

我尝试从沙盒用户那里获取图片,这是我为测试而创建的虚拟帐户:

https://api.instagram.com/v1/users/fane.leee/media/recent?access_token=ACCESS_TOKEN

用于检索图像的PHP代码:

$url = 'https://api.instagram.com/v1/users/fane.leee/media/recent?access_token='.$ACCESS_TOKEN;
    $ch = curl_init(); // initializing
    curl_setopt( $ch, CURLOPT_URL, $url ); // API URL to connect
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
    curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
    $response = json_decode(curl_exec($ch), true); // connect and get json data
    curl_close($ch);

问题
获取图像请求的$响应是NULL,没有错误消息。有人对这个问题有任何想法吗?

感谢。

参考

  1. Instagram开发文档 authenticationauthorization

  2. 关于 user endpoints

  3. 的Instagram开发文档
  4. 关于Instagram网络API的另一个StackOverflow post

  5. 开发环境: Ubuntu 16.04
    Apache2的
    PHP 7.0.8
    MySQL 14.14

    编辑1:添加调用cUrl函数的PHP代码 编辑2:如果我替换用户ID' fane.leee'通过使用' self',我可以检索我发布的图像。我也关注了用户' fane.leee'。我应该做的任何其他事情来检索朋友'媒体?

1 个答案:

答案 0 :(得分:0)

fane.leee是用户名。 Instagram需要API调用者中的用户ID。

要通过调用instagram API函数获取用户ID,我们可以使用
https://www.instagram.com/{username}/?__a=1

获取用户ID的另一种方法是使用第三方网站。它能够从用户名中检索Instagram用户ID。它是here

参考:
Thinh Vu在this thread - Not the accepted answer, but the answer underneath. P.S the accepted answer is not working anymore.

中的回答