Instagram API使用PHP检索代码

时间:2017-05-31 16:49:45

标签: php api curl instagram

我尝试使用Instagram API,但这真的不容易。

根据API文档,必须检索代码才能获取访问令牌,然后向Instagram API发出请求。

但经过几次尝试,我没有成功。

我已经很好地配置了https://www.instagram.com/developer

中的设置

我使用api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code调用了网址curl,但我没有重定向uri,其中包含响应代码。

你能帮我吗?)!

3 个答案:

答案 0 :(得分:0)

我建议您使用现有的PHP Instagram客户端库之一,例如https://github.com/cosenary/Instagram-PHP-API

答案 1 :(得分:0)

我不久前做过这个,这里有一个很好的参考:

https://auth0.com/docs/connections/social/instagram

让我知道它是否有帮助!

答案 2 :(得分:0)

我已经制作了这段代码,我希望它没有错误,但是我只是为了你想要的用例而做了这个代码,我将在下面解释它这段代码是如何工作的。

$authorization_url = "https://api.instagram.com/oauth/authorize/?client_id=".$instagram_client_id."&redirect_uri=".$your_website_redirect_uri."&response_type=code";
$username='ig_username';
$password='ig_password';
$_defaultHeaders = array(
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Encoding: ',
        'Connection: keep-alive',
        'Upgrade-Insecure-Requests: 1',
        'Cache-Control: max-age=0'
    );
$ch  = curl_init();
    $cookie='/application/'.strtoupper(VERSI)."instagram_cookie/instagram.txt";
            curl_setopt( $ch, CURLOPT_POST, 0 );
            curl_setopt( $ch, CURLOPT_HTTPGET, 1 );
            if($this->token!==null){
                array_push($this->_defaultHeaders,"Authorization: ".$this->token);   
            }
            curl_setopt( $ch, CURLOPT_HTTPHEADER, $this->_defaultHeaders);
            curl_setopt( $ch, CURLOPT_HEADER, true);
            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_COOKIEFILE,getcwd().$cookie );
            curl_setopt( $ch, CURLOPT_COOKIEJAR, getcwd().$cookie );
            curl_setopt($this->curlHandle,CURLOPT_URL,$url);
            curl_setopt($this->curlHandle,CURLOPT_FOLLOWLOCATION,true);

            $result = curl_exec($this->curlHandle);
            $redirect_uri = curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
            $form = explode('login-form',$result)[1];
        $form = explode("action=\"",$form)[1];
//        vd('asd',$form);
        $action = substr($form,0,strpos($form,"\""));
//        vd('action',$action);
        $csrfmiddlewaretoken = explode("csrfmiddlewaretoken\" value=\"",$form);
        $csrfmiddlewaretoken = substr($csrfmiddlewaretoken[1],0,strpos($csrfmiddlewaretoken[1],"\""));
        //finish getting parameter

        $post_param['csrfmiddlewaretoken']=$csrfmiddlewaretoken;
        $post_param['username']=$username;
        $post_param['password']=$password;
//format instagram cookie from vaha's answer https://stackoverflow.com/questions/26003063/instagram-login-programatically
    preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);

    $cookieFileContent = '';

    foreach($matches[1] as $item)
    {
        $cookieFileContent .= "$item; ";
    }

    $cookieFileContent = rtrim($cookieFileContent, '; ');
    $cookieFileContent = str_replace('sessionid=; ', '', $cookieFileContent);
    $cookie=getcwd().'/application/'.strtoupper(VERSI)."instagram_cookie/instagram.txt";
    $oldContent = file_get_contents($cookie);
    $oldContArr = explode("\n", $oldContent);
    if(count($oldContArr))
    {
        foreach($oldContArr as $k => $line)
        {
            if(strstr($line, '# '))
            {
                unset($oldContArr[$k]);
            }
        }

        $newContent = implode("\n", $oldContArr);
        $newContent = trim($newContent, "\n");
        file_put_contents(
            $cookie,
            $newContent
        );
    }


    // end format
    $useragent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0";
    $arrSetHeaders = array(
        'origin: https://www.instagram.com',
        'authority: www.instagram.com',
        'upgrade-insecure-requests: 1',
        'Host: www.instagram.com',
        "User-Agent: $useragent",
        'content-type: application/x-www-form-urlencoded',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Encoding: deflate, br',
        "Referer: $redirect_uri",
        "Cookie: $cookieFileContent",
        'Connection: keep-alive',
        'cache-control: max-age=0',
    );

    $ch  = curl_init();
    curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);
    curl_setopt($ch, CURLOPT_URL, $this->base_url.$action);
    curl_setopt($ch, CURLOPT_REFERER, $redirect_uri);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_param));

    sleep(5);
    $page = curl_exec($ch);


    preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);
    $cookies = array();
    foreach($matches[1] as $item) {
        parse_str($item, $cookie1);
        $cookies = array_merge($cookies, $cookie1);
    }
var_dump($page);

第1步: 我们需要先登录登录页面。
我们可以使用curl get访问它,CURLOPT_FOLLOWLOCATION设置为true,这样我们就会被重定向到登录页面,我们访问我们的应用程序Instagram授权网址

$authorization_url = "https://api.instagram.com/oauth/authorize/?client_id=".$instagram_client_id."&redirect_uri=".$your_website_redirect_uri."&response_type=code";
$username='ig_username';

这是Instagram文档here的第一步 现在第一次获得curl的结果我们有了响应页面和我们存储在$ redirect_uri的页面uri,当我们为登录登录时,必须将它放在referer标题上。

获得login_page的结果后,我们需要格式化cookie,我知道并使用vaha中的一些代码来回答vaha's answer

第2步: 获取login_page后,我们将提取操作URL,提取csrfmiddlewaretoken隐藏的输入值 在我们得到它之后,我们将做一个post参数登录 我们必须设置重定向uri,并且不要忘记cookiejar,以及其他标题设置,如上面的代码。
成功发送登录参数后,Instagram将调用你的重定向uri,例如https://www.yourwebsite.com/save_instagram_code在那里您必须使用或保存您的Instagram代码才能再次使用curl获取访问令牌(我只解释如何获取代码:D)
我在短时间内完成了这项工作,如果我有时间的话,我会更新我测试过的代码,并随时建议编辑可行的代码或更好的解释。