İnstagram Client Apimizi instagram.com/developer sitesinden oluşturmuşturup Client ID ve Client Secret anahtarlarımızı da almıştık eğer bunları yapmadıysanız buraya tıklayarak İnstagram Api nasıl alınır makalesini inceleyebilirsiniz.
Şimdi php dosyalarımızı oluşturmaya başlayalım.
- Localhost
- callback.php
- index.php
- islem.php
- Localhost > lib klasörüne
- instaclass.php
- config.php
Dizinimizi bu şekilde oluşturduktan sonra config.php dosyamızın içerisinde instagram clientimizin bilgileri bulunacak
<?php $instagram = new Instagram(array( 'apiCallback' => 'http://localhost/1-proje/inst2/callback.php', 'apiKey' => 'buraya Client ID', 'apiSecret' => 'buraya Client Secret', )); ?>
yukarıdaki kod parçasında apiCallback , api client oluştururken Valid redirect URIs alanıyla aynı olmak zorunda farkı olursa hatayla karşılaşırız.
instaclass.php dosyamızın içerisine. Bu dosya instagram apiyi kullanmamız için kullanılan kütüphane
<?php class Instagram { const API_URL = 'https://api.instagram.com/v1/'; const API_OAUTH_URL = 'https://api.instagram.com/oauth/authorize'; const API_OAUTH_TOKEN_URL = 'https://api.instagram.com/oauth/access_token'; private $_apikey; private $_apisecret; private $_callbackurl; private $_accesstoken; private $_scopes = array('basic', 'likes', 'comments', 'relationships'); public function __construct($config) { if (true === is_array($config)) { // if you want to access user data $this->setApiKey($config['apiKey']); $this->setApiSecret($config['apiSecret']); $this->setApiCallback($config['apiCallback']); } else if (true === is_string($config)) { // if you only want to access public data $this->setApiKey($config); } else { throw new Exception("Error: __construct() - Configuration data is missing."); } } public function getLoginUrl($scope = array('basic')) { if (is_array($scope) && count(array_intersect($scope, $this->_scopes)) === count($scope)) { return self::API_OAUTH_URL.'?client_id='.$this->getApiKey().'&redirect_uri='.$this->getApiCallback().'&scope='.implode('+', $scope).'&response_type=code'; } else { throw new Exeption("Error: getLoginUrl() - The parameter isn't an array or invalid scope permissions used."); } } public function searchUser($name, $limit = 0) { return $this->_makeCall('users/search', false, array('q' => $name, 'count' => $limit)); } public function getUser($id = 0) { $auth = false; if ($id === 0 && isset($this->_accesstoken)) { $id = 'self'; $auth = true; } return $this->_makeCall('users/'.$id, $auth); } public function getUserFeed($limit = 0) { return $this->_makeCall('users/self/feed', true, array('count' => $limit)); } public function getUserMedia($id = 'self', $limit = 0) { return $this->_makeCall('users/'.$id.'/media/recent', true, array('count' => $limit)); } public function getUserLikes($limit = 0) { return $this->_makeCall('users/self/media/liked', true, array('count' => $limit)); } public function searchMedia($lat, $lng) { return $this->_makeCall('media/search', false, array('lat' => $lat, 'lng' => $lng)); } public function getMedia($id) { return $this->_makeCall('media/'.$id); } public function getPopularMedia() { return $this->_makeCall('media/popular'); } public function searchTags($name) { return $this->_makeCall('tags/search', false, array('q' => $name)); } public function getTag($name) { return $this->_makeCall('tags/'.$name); } public function getTagMedia($name) { return $this->_makeCall('tags/'.$name.'/media/recent'); } public function getOAuthToken($code, $token = false) { $apiData = array( 'grant_type' => 'authorization_code', 'client_id' => $this->getApiKey(), 'client_secret' => $this->getApiSecret(), 'redirect_uri' => $this->getApiCallback(), 'code' => $code ); $result = $this->_makeOAuthCall($apiData); return (false === $token) ? $result : $result->access_token; } private function _makeCall($function, $auth = false, $params = null) { if (false === $auth) { // if the call doesn't requires authentication $authMethod = '?client_id='.$this->getApiKey(); } else { // if the call needs a authenticated user if (true === isset($this->_accesstoken)) { $authMethod = '?access_token='.$this->getAccessToken(); } else { throw new Exeption("Error: _makeCall() | $function - This method requires an authenticated users access token."); } } if (isset($params) && is_array($params)) { $params = '&'.http_build_query($params); } else { $params = null; } $apiCall = self::API_URL.$function.$authMethod.$params; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiCall); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); $jsonData = curl_exec($ch); curl_close($ch); return json_decode($jsonData); } private function _makeOAuthCall($apiData) { $apiHost = self::API_OAUTH_TOKEN_URL; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiHost); curl_setopt($ch, CURLOPT_POST, count($apiData)); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData)); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $jsonData = curl_exec($ch); curl_close($ch); return json_decode($jsonData); } public function setAccessToken($data) { (true === is_object($data)) ? $token = $data->access_token : $token = $data; $this->_accesstoken = $token; } public function getAccessToken() { return $this->_accesstoken; } public function setApiKey($apiKey) { $this->_apikey = $apiKey; } public function getApiKey() { return $this->_apikey; } public function setApiSecret($apiSecret) { $this->_apisecret = $apiSecret; } public function getApiSecret() { return $this->_apisecret; } public function setApiCallback($apiCallback) { $this->_callbackurl = $apiCallback; } public function getApiCallback() { return $this->_callbackurl; } } ?>
index.php dosyamızın içerisine kodlarını yazıyoruz. Kodları yazarken olabildiğince basit ve sade tutmaya çalıştım. Böylelikle ilk defa uğraşanlar için bu kod neymiş nereden gelmiş sorularıyla uğraşmak yerine önce çalıştırıp test edip sonuçlarını gördükten sonra çeşitli bilgileri istediğiniz bilgiyi getirebilirsiniz.
<?php session_start(); include ('lib/instaclass.php'); include ('lib/config.php'); ?> <!DOCTYPE html> <html > <head> <title>İnstagram Api / Api Kütüphanesi</title> </head> <body> <?php //eğer daha önce userData session değişkeninde user name yoksa giriş yapması gerekecek. if(empty($_SESSION['userData']->user->username)) { $instagramLoginUrl = $instagram->getLoginUrl(); echo "<a href='".$instagramLoginUrl."'>Instagram hesabınızla giriş yapın</a><br>"; echo $instagramLoginUrl; }else { print_r($_SESSION['userData']); } ?> </body> </html>
getLoginUrl Kodu ile instagrama giriş yapacağımız instagram sayfasına yönlendiren bir link üretiyor. Link içeriğini görmek için hemen altında instagramLoginUrl ‘i yazdırdım
$instagramLoginUrl = $instagram->getLoginUrl();
Yazdırdığım linki inceleyelim.
api.instagram.com/…../autohorize?client_id=config dosyasındaki client id&redirect_uri=conf dosyasındaki geri yönlendire urli&scope=izinler&response_type=geriye dönecek değer
https://api.instagram.com/oauth/authorize?client_id=8b34cfb60afb4c508cd02f5ded81cc56&redirect_uri=http://localhost/1-proje/inst2/callback.php&scope=basic&response_type=code
Bizim config.php dosyasına kaydettiğimiz bilgileri instagram api sayfasına giderek karşılaştırma yapıyor eğer herhangi bir sorun yoksa izinleri alıp code üretip redirect_uri sayfamıza yönlendiriyor (Valid redirect URIs)
Geldik callback.php dosyasının içerisine
<?php include ('lib/ins.class.php'); include ('lib/ins.conf.php'); $code = $_GET['code']; if (true === isset($code)) { $data = $instagram->getOAuthToken($code); if(empty($data->user->username)) { print_r($data); header('Location: index.php'); } else { session_start(); $_SESSION['userdetails']=$data; $user=$data->user->username; header('Location: islem.php'); } } else { if (true === isset($_GET['error'])) { echo 'Bir hata oluştu: '.$_GET['error_description']; } } ?>
Yukarıdaki callback.php dosyasında instagramdan yapılan yönlendirme yanında bir code de getirmişti şimdi bu code yi kullanarak access_token imizi üretelim.
$data = $instagram->getOAuthToken($code);
kodu yardımıyla hem access_tokeni hemde diğer bilgileri üretmiş olduk ve islem.php dosyasına yönlendirdik.
islem.php dosyasının içerisine
<?php session_start(); ob_start(); $data = $_SESSION['userdetails']; ?> <!DOCTYPE html> <html> <head> <title>İnstagram api kullanımı</title> </head> <body> <?php echo "<pre>"; print_r($data); ?> </body> </html>
Burada artık Access Tokeni almış oluyoruz bundan sonrası artık istediğimiz gibi bilgileri curl ile çekerek kullanacağız.
Bayadir internet sayfanizi geziyorum evet baya basarili buluyorum
Teşekkürler 🙂 Anlatılmasını istediğiniz bir web site api’si varsa listeye alabilirim
Deniyorum şu an, kaç gündür bir ton yöntem denedim. Çalışırsa eğer, öpücüğe ihtiyacın varsa gelir öperim 🙂
Merhaba, bir sorunla karşılaştım fakat çözemedim. “instagram sayfanıza giriş yapın ” butonuna tıkladıktan sonra , islem.php sayfasına yönlendirmesi gerekirken , index.php sayfasına yönlendiriyor. Yardımcı olur musunuz ?
http://www.apikutuphanesi.com/instagram-api/instagram-api-nasil-alinir/
Sayfasında belirttiğim gibi valid Redirect URL’e hangi sayfanızı yazarsanız oraya yönlenecektir. iyi çalışmalar
Hocam bende hangi yolu denersem deneyim
error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.
bu hatayı alıyorum
{“error_type”: “OAuthException”, “code”: 400, “error_message”: “Redirect URI does not match registered redirect URI”} şu hatayı nasıl çözerim?
Merhaba Uğur Bey,
Valid redirect uris alanını yanlış doldurmuşsunuz. http://www.apikutuphanesi.com/instagram-api/instagram-api-nasil-alinir/ sayfasında anlattığım gibi valid redirect uris alanını kontrol edin.