Instagram API 使用 PHP 检索代码 [英] Instagram API retrieve the code using PHP

查看:27
本文介绍了Instagram API 使用 PHP 检索代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

我已经在 https://www.instagram.com/developer 中配置好了设置

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

我使用 curl 调用 url api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code>,但我没有响应代码的重定向 uri.

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.

你能帮我吗;)!

推荐答案

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

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

第 1 步:我们需要先进入登录页面.
我们可以使用 curl get 访问它,将 CURLOPT_FOLLOWLOCATION 设置为 true 以便我们将被重定向到登录页面,我们访问我们的应用程序 instagram 授权 url

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

这是 Instagram 文档的第一步此处
现在,第一个 get curl 的结果是我们将响应页面及其页面 uri 存储在 $redirect_uri 中,当我们进行 http post 登录时,必须需要并放置在引用标头上.

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

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

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.

这篇关于Instagram API 使用 PHP 检索代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆