IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

APIs Réseaux sociaux Discussion :

Gérer un flux Instagram


Sujet :

APIs Réseaux sociaux

  1. #1
    Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2014
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2014
    Messages : 236
    Points : 61
    Points
    61
    Par défaut Gérer un flux Instagram
    Bonjour,

    Est-il possible de récupérer les photos d'utilisateurs ayant mis un hashtag particulier ?

    Depuis cette doc : https://www.instagram.com/developer/endpoints/tags/

    J'arrive à appeler l'url : https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token=ACCESS-TOKEN

    Mais le problème c'est qu'il me demande des valeurs pour min_tag_id et max_tag_id.

    J'arrive à afficher les photos de mon compte avec cette classe et fonction :

    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    <?php
     
    namespace AppBundle\Model;
     
    class Instagram
    {
        /*
         * Attributes
         */
        private $username, //Instagram username
                $access_token, //Your access token
                $userid; //Instagram userid
     
        /*
         * Constructor
         */
        function __construct($username='',$access_token='') {
            if(empty($username) || empty($access_token)){
                $this->error('empty username or access token');
            } else {
                $this->username=$username;
                $this->access_token = $access_token;
            }
        }
     
        /*
         * The api works mostly with user ids, but it's easier for users to use their username.
         * This function gets the userid corresponding to the username
         */
        public function getUserIDFromUserName(){
            if(strlen($this->username)>0 && strlen($this->access_token)>0){
                //Search for the username
                $useridquery = $this->queryInstagram('https://api.instagram.com/v1/users/search?q='.$this->username.'&access_token='.$this->access_token);
                if(!empty($useridquery) && $useridquery->meta->code=='200' && $useridquery->data[0]->id>0){
                    //Found
                    $this->userid=$useridquery->data[0]->id;
                } else {
                    //Not found
                    $this->error('getUserIDFromUserName');
                }
            } else {
                $this->error('empty username or access token');
            }
        }
     
        /*
         * Get the most recent media published by a user.
         * you can use the $args array to pass the attributes that are used by the GET/users/user-id/media/recent method
         */
        public function getUserMedia($args=array()){
            if($this->userid<=0){
                //If no user id, get user id
                $this->getUserIDFromUserName();
            }
            if($this->userid>0 && strlen($this->access_token)>0){
                $qs='';
                if(!empty($args)){ $qs = '&'.http_build_query($args); } //Adds query string if any args are specified
                $shots = $this->queryInstagram('https://api.instagram.com/v1/users/'.(int)$this->userid.'/media/recent?access_token='.$this->access_token.$qs); //Get shots
                if($shots->meta->code=='200'){
                    return $shots;
                } else {
                    $this->error('getUserMedia');
                }
            } else {
                $this->error('empty username or access token');
            }
        }
     
        /*
         * Method that simply displays the shots in a ul.
         * Used for simplicity and demo purposes
         * You should probably move the markup out of this class to use it directly in your page markup
         */
        public function simpleDisplay($shots){
            $simpleDisplay = '';
            if(!empty($shots->data)){
                $simpleDisplay.='<ul class="instagram_shots">';
                    foreach($shots->data as $istg){
                        //The image
                        $istg_thumbnail = $istg->{'images'}->{'thumbnail'}->{'url'}; //Thumbnail
                        //If you want to display another size, you can use 'low_resolution', or 'standard_resolution' in place of 'thumbnail'
     
                        //The link
                        $istg_link = $istg->{'link'}; //Link to the picture's instagram page, to link to the picture image only, use $istg->{'images'}->{'standard_resolution'}->{'url'}
     
                        //The caption
                        $istg_caption = "";
                        if(isset( $istg->{'caption'}->{'text'} )) {
                            $istg_caption = $istg->{'caption'}->{'text'};
                        }
     
                        //The markup
                        $simpleDisplay.='<li><a class="instalink" href="'.$istg_link.'" target="_blank"><img src="'.$istg_thumbnail.'" alt="'.$istg_caption.'" title="'.$istg_caption.'" /></a></li>';
                    }
                $simpleDisplay.='<ul>';
            } else {
                $this->error('simpleDisplay');
            }
            return $simpleDisplay;
        }
     
        /*
         * Common mechanism to query the instagram api
         */
        public function queryInstagram($url){
            //prepare caching
            $cachefolder = __DIR__.'/';
            $cachekey = md5($url);
            $cachefile = $cachefolder.$cachekey.'_'.date('i').'.txt'; //cached for one minute
     
            //If not cached, -> instagram request
            if(!file_exists($cachefile)){
                //Request
                $request='error';
                if(!extension_loaded('openssl')){ $request = 'This class requires the php extension open_ssl to work as the instagram api works with httpS.'; }
                else { $request = file_get_contents($url); }
     
                //remove old caches
                $oldcaches = glob($cachefolder.$cachekey."*.txt");
                if(!empty($oldcaches)){foreach($oldcaches as $todel){
                  unlink($todel);
                }}
     
                //Cache result
                $rh = fopen($cachefile,'w+');
                fwrite($rh,$request);
                fclose($rh);
            }
            //Execute and return query
            $query = json_decode(file_get_contents($cachefile));
            return $query;
        }
     
        /*
         * Error
         */
        public function error($src=''){
            trigger_error( '/!\ error '.$src.'. ', E_USER_WARNING);
        }
     
    }

    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
            $username='mitsukk1992';
            $access_token='295228573.1f565ea.11fa220f2d2f4d48b5ef62f41039f41c';
            $count='2';
     
            if(!empty($username) && !empty($access_token)) {
                $isg = new Instagram($username, $access_token);
                $shots = $isg->getUserMedia(array('count'=> $count));
                dump($shots);die;
            } else {
                echo'Please update your settings to provide a valid username and access token';
            }
            //4 - Display
            if(!empty($shots)) {
                echo $isg->simpleDisplay($shots);
            }

    Mais la classe Instagram ne me permet pas d'aller plus loin, j'ai donc utiliser ce bundle : https://github.com/cosenary/Instagram-PHP-API

    Mais je n'arrive toujours pas à réaliser ce que je veux.

  2. #2
    Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2014
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2014
    Messages : 236
    Points : 61
    Points
    61
    Par défaut
    Bon j'ai finalement réussi à l'aide de ce bundle qui génère une connexion à Instagram à l'aide d'un device :

    https://github.com/liamcottle/Instagram-SDK-PHP

    J'ai créé cette commande :

    Code PHP : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    <?php
     
    namespace Carrefour\CarrefourBoxBundle\Command;
     
    use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    use Symfony\Component\Console\Style\SymfonyStyle;
    use Instagram\Instagram;
    use Carrefour\CarrefourBoxBundle\Entity\PostsInstagram;
     
    class InstagramCommand extends ContainerAwareCommand
    {
        protected $em;
        protected $container;
        protected $io;
     
        protected function configure()
        {
            $this
                ->setName('box:instagram')
                ->setDescription('Import latest posts Instagram whit hashtag paniercuistot.');
        }
     
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $this->io = new SymfonyStyle($input, $output);
     
            $this->io->title('Import Instagram posts');
     
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
     
            $this->container = $this->getContainer();
     
            $this->em->beginTransaction();
     
            try {
                $this->cleanDatabase();
                $this->importInstagramPosts();
                $this->em->flush();
            } catch (\Exception $e) {
                $this->em->rollback();
                throw $e;
            }
     
            $this->em->commit();
            $this->io->success('Les 10 derniers posts Instagram avec le hashtag #paniercuistot ont bien été importés.');
        }
     
        /**
         * Clean database before import
         */
        protected function cleanDatabase()
        {
            $this->em->createQuery("DELETE CarrefourBoxBundle:PostsInstagram")->execute();
            $this->io->note('La table Instagram a été vidée pour importer les derniers posts comportant le hashtag #paniercuistot.');
        }
     
        /**
         * Clean database before import
         */
        protected function importInstagramPosts()
        {
            $instagram = new Instagram();
     
            $instagram->login($this->container->getParameter('instagram_account'), $this->container->getParameter('instagram_password'));
     
            $isgLatestPosts = array_slice($instagram->getTagFeed('paniercuistot')->getItems(), 0, 10);
     
            foreach ($isgLatestPosts as $isgLatest) {
                $instagramData = new PostsInstagram();
                $datetime = new \DateTime();
     
                $date = date('Y/m/d', $isgLatest->getCaption()->getCreatedAt());
                $newDate = $datetime->createFromFormat('Y/m/d', $date);
     
                $instagramData->setUsername($isgLatest->getUser()->getUsername());
                $instagramData->setUrlImage($isgLatest->getImageVersions2()->getCandidates()['0']->getUrl());
                $instagramData->setContent(utf8_encode($isgLatest->getCaption()->getText()));
                $instagramData->setNbLikes($isgLatest->getLikeCount());
                $instagramData->setDate($newDate);
                $instagramData->setCode($isgLatest->getCode());
                $this->em->persist($instagramData);
            }
        }
    }

    Qui récupère ce dont j'ai besoin pour l'affichage de ma vue.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Article] Tutoriel AngularJS : gérer les flux RSS
    Par vermine dans le forum AngularJS
    Réponses: 1
    Dernier message: 11/06/2013, 14h25
  2. [Debutant] Gérer un flux de fichier I/O
    Par cleml12 dans le forum Configuration
    Réponses: 8
    Dernier message: 12/09/2011, 09h46
  3. lire flux xml et gérer le timeout ?
    Par ellow dans le forum Format d'échange (XML, JSON...)
    Réponses: 1
    Dernier message: 08/06/2010, 15h06
  4. gérer les jpg dans une fenetre directdraw???
    Par Anonymous dans le forum DirectX
    Réponses: 1
    Dernier message: 14/06/2002, 13h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo