Instagram API retrieve the code using PHP

Deadly 提交于 2020-01-23 17:17:12

问题


I try to use the Instagram API but it's really not easy.

According to the API documentation, a code must be retrieved in order to get an access token and then make requests to Instagram API.

But after few try, I don't succeed.

I already well-configured the settings in https://www.instagram.com/developer

I call the url api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code with curl, but I don't have the redirect uri with the code in response.

Can you help me please ;)!


回答1:


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




回答2:


I did this not too long ago, here's a good reference:

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

Let me know if it helps!




回答3:


I've made this code, I hope it doesnt have error, but i've just made it for usecase like you wanted
Here is the code, I'll explain it 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'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);

Step 1: We need to get to the login page first.
We can access it using curl get, with CURLOPT_FOLLOWLOCATION set to true so that we will be redirected to the login page, we access our application instagram 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 from this Instagram documentation here
Now the result of the first get curl we have the response page and its page uri that we store at $redirect_uri, this must be needed and placed on referer header when we do http post for login.

After get the result of login_page, we will need to format the cookie, I know this and use some code from vaha answer here vaha's answer

Step 2: After we get the login_page we will extract the action url , extract csrfmiddlewaretoken hidden input value.
After we get it, we will do a post parameter to login.
We must set the redirect uri, and dont forget the cookiejar, and other header setting like above code.
After success sending the parameter post for login, Instagram will call your redirect uri, for example https://www.yourwebsite.com/save_instagram_code at there you must use or save your instagram code to get the access token using curl again ( i only explain how to get the code :D)
I make this in a short time, I'll update the code which I have tested and work if i have time, Feel free to suggest an edit of workable code or a better explanation.



来源:https://stackoverflow.com/questions/44290519/instagram-api-retrieve-the-code-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!