Justique
@Justique

Странное api инстаграма?

Появилась необходимость работать с апи инстраграма, первым же делом полез искать классы для работы и переодически натыкаюсь на такого рода ссылки к котрому обращаются по API
//i.instagram.com/api/v1/
а в документации
//api.instagram.com/v1/

Причём автризация в первом примере полностью отличается от той что описана в док-ции

Первый вариант который отличается от док-ции.
private function Auth() {
        $this->inLog("Auth");
        $login = $this->makeApiCall('accounts/login/', $this->user, true, false);
		print_r($login);
        if(isset($login['status']) && $login['status'] == 'ok') {
            $this->inLog("Login success..\nLogged in as ".$login['logged_in_user']['username']); //todo msgs in array
            $this->is_logged = true;
            $this->user = $login['logged_in_user'];
        } else die($this->inLog('Wrong username/password'));
    }


Весь класс
set_time_limit(0);

class Instagram {
    
    public $user;
    private $signatureKey;
    public $is_logged = false;
    public static $apiURL    = '//i.instagram.com/api/v1/';
    public static $userAgent = 'Instagram 6.9.1 Android (15/4.0.4; 160dpi; 320x480; Sony; MiniPro; mango; semc; en_Us)';
    public static $key_ver   = 4;
    
    
    public function __construct($login, $password, $key) {
        $this->user = array('username'=>$login, 'password'=>$password);
        $this->signatureKey = $key;
        $this->GUID = $this->GenerateGuid();
        $this->curl = new cUrl($this->user['username'], self::$userAgent);
        $this->Auth();
		
        return true;
    }
    
    private function Auth() {
        $this->inLog("Auth");
        $login = $this->makeApiCall('accounts/login/', $this->user, true, false);
		print_r($login);
        if(isset($login['status']) && $login['status'] == 'ok') {
            $this->inLog("Login success..\nLogged in as ".$login['logged_in_user']['username']); //todo msgs in array
            $this->is_logged = true;
            $this->user = $login['logged_in_user'];
        } else die($this->inLog('Wrong username/password'));
    }

    public function getUsers($from, $data, $count) {
        $this->inLog("getUsers");
        $fromlist = array('followers', 'following', 'likes');
        $list = array();
        if(!isset($from) || !in_array($from, $fromlist)) die("from get users?");

        if($from == 'following' || $from == 'followers') {
            $users = $this->getUsersByRelationships($from, $data['id'], $count);
        } elseif ($from == 'likes') {
            $users = $this->getUsersFromLikes($data['media'], $count);
        }


        return new UserActions($this, array_slice($users, 0, $count));
    }

    public function getNotMutualRelationships() {

        $followers = $this->getUsersByRelationships('followers', $this->user['pk'], 9999999); 
        $following = $this->getUsersByRelationships('following', $this->user['pk'], 9999999); 


        $list = $following;

        foreach ($following as $key => $user) {
            foreach ($followers as $follower) {
                if($user['pk'] === $follower['pk']) {
                    unset($list[$key]);
                    break;
                }
            }
        }

        $this->inLog("Not mutual relationships: ".count($list));
        return new UserActions($this, $list);

    }

    public function getUsersFromLikes($media, $count) {
        $this->inLog("getUsersFromLikes");
        $list = array();
        $req = $this->makeApiCall('media/'.$media.'/likers/');
        return $req;
    }

    public function getUsersByRelationships($from, $id, $count) {
        $this->inLog("getUsersByRelationships ".$from);
        $fromlist = array("followers", "following");
        if(!isset($from) || !in_array($from, $fromlist)) die("from get users?");

        $list = array();

        while(count($list) < $count) {
            $req = $this->makeApiCall('friendships/'.$id.'/'.$from.'/?max_id='.$max_id);
            $list = array_merge($list, $req['users']);
            if(isset($req['next_max_id'])) {
                $max_id = $req['next_max_id'];
            } else break;
        }
        return array_slice($list, 0, $count);
    }


    public function searchUserByUsername($username) {
        $this->inLog("searchUserByUsername ".$username);
        $req = $this->makeApiCall('users/search/?query='.$username);
        return $req;
    }

    public function getMedia($id, $count) {
        /*$this->inLog("getMedia ".$id);
        
        $list = array();

        while(count($list) < $count) {
            $req = $this->makeApiCall('feed/user/'.$id.'/?max_id='.$max_id);
            
            if(end($req['items'])['id'] != $max_id) {
                $max_id = end($req['items'])['id'];
            } else break;
            
            $list = array_merge($list, $req['items']); 

        }
        return array_slice($list, 0, $count);*/
    }

    public function Follow($uid, $destroy = false) {
       /* $request = $this->makeApiCall('friendships/'.($destroy ? 'destroy/' :'create/').$uid.'/', ['user_id'=>$uid]);
        return $request;*/
    }


    public function inLog($str) {
		if(is_array($str)){
				echo "#######Start ARRAY#######\n";
			foreach($str as $key =>$values){
				echo @date("[H:i:s]: ").'['.$key.']'.$values.PHP_EOL . "\n";
			}
				echo "########End ARRAY########\n";
		}else{
				echo @date("[H:i:s]: ").$str.PHP_EOL;
		}
    }

    public function makeApiCall($method, $params = array(), $ssl = false, $use_cookie = true, $server = true) {
        $defaultRequestBody = array(
            "device_id"=>'android-'.$this->GUID,
            "guid"=>$this->GUID,
            "Content-Type"=>"application/x-www-form-urlencoded; charset=UTF-8"
        );
		$signedBody = '';
        if(!empty($params)) {
            $params = json_encode(array_merge($defaultRequestBody, $params));
            $signedBody = 'signed_body='.$this->generateSig($params).".".urlencode($params).'&ig_sig_key_version='.self::$key_ver;
        }
		
	$server = self::$apiURL;
        $result = json_decode($this->curl->call(($ssl ? 'https:' : 'http:').$server.$method, $signedBody, $use_cookie), true);
        return $result;
    }
    
    private function generateSig($str) {
        return hash_hmac('sha256', $str, $this->signatureKey);
    }

    private function GenerateGuid() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(16384, 20479), 
            mt_rand(32768, 49151), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535)
        );
    }

    
}


Собственно методы описанные в документации с этим классом не работают(
  • Вопрос задан
  • 4387 просмотров
Решения вопроса 1
BupycNet
@BupycNet
Основатель PushAll
Это не API инстаграма, это неофициальный расковыренный апи через которое работают приложения инстаграма.
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
smidl
@smidl
WordPress-разработчик
не работает этот класс с приложениями, которые были созданы после 17 ноября 2015 года.

Во всех новых приложениях теперь необходимо использовать access_token с корректным scope. Раньше хватало client_id.

Тем более, что новые приложения работают режиме песочницы, которая очень урезает лимиты и возможности приложения. А чтобы стать полностью функциональным - приложению нужно пройти муторный аппрув в инстаграмме.
Ответ написан
Комментировать
phtimofeeff
@phtimofeeff
МИРЭА Прикладная математика
так а что хотите от Instagram?
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
YCLIENTS Москва
от 200 000 до 350 000 ₽
Ведисофт Екатеринбург
от 25 000 ₽
от 300 000 до 500 000 ₽
07 мая 2024, в 15:47
12000 руб./за проект
07 мая 2024, в 15:10
1500 руб./в час
07 мая 2024, в 15:07
1500 руб./в час