Instagram API retrieves code using PHP

I'm trying to use the Instagram API, but it's really not easy.

According to the API documentation, the code needs to be fetched to get the access token and then make requests to the Instagram API.

But after several tries I fail.

I have already configured the settings well at https://www.instagram.com/developer

I call url api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code

with curl

, but I have no redirect uri

code in response.

Can you help me?)!

+1


source to share


3 answers


I would recommend that you use one of the existing PHP scripting client libraries like https://github.com/cosenary/Instagram-PHP-API



0


source


I did it not too long ago, here's a good link:

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



Let me know if it helps!

0


source


I made this code, hopefully it has no error, but I just did it for the usecase as you wanted. Here is the code, I will explain below how this code works.

$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 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);

      

Step 1: First, we need to go to the login page.
We can access it using curl get, with CURLOPT_FOLLOWLOCATION

set to true so that we are redirected to the login page and we can access our application authorization url.

$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';

      

This is step one of this Instagram documentation here
Now the result of the first get curl we have a response page and its page uri which we store in $ redirect_uri, this must be needed and put in the referer header when we make an http post to login.

After getting the login_page result, we need to format the cookie, I know this and using the code from vaha here vaha's answer

Step 2: After we get the login_page, we fetch the action url, extract the csrfmiddlewaretoken

hidden input.
After we get it, we will enter the parameter to enter. We have to set the uri redirect and not forget the cookiejar and other header settings like above code.
After successfully sending the login parameter message, Instagram will trigger your uri redirect, for example https://www.yourwebsite.com/save_instagram_code

where you should use or save the instagram code to get the access token using curl again (I will only explain how to get the code: D)
I will do it for in a short time, I will update the code I tested and work, if I have time, feel free to suggest editing a workable code or a better explanation.

0


source







All Articles