client()->get('/refresh_access_token', ['query' => [ 'grant_type' => 'ig_refresh_token', 'access_token' => $page->access_token, ]]); $page->update([ 'access_token' => json_decode((string) $response->getBody())->access_token ]); } public function client() { return new Client([ 'base_uri' => 'https://graph.instagram.com', ]); } public function authClient() { return new Client([ 'base_uri' => 'https://api.instagram.com', ]); } public function authenticate(): string { $response = $this->authClient()->post('/oauth/access_token', [ 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], 'form_params' => [ 'client_id' => Setting::get('instagram_client_id'), 'redirect_uri' => $this->redirectUri(), 'client_secret' => Setting::get('instagram_client_secret'), 'grant_type' => 'authorization_code', 'code' => request()->query('code') ] ]); $accessToken = json_decode((string) $response->getBody())->access_token; $response = $this->client()->get('/access_token', ['query' => [ 'grant_type' => 'ig_exchange_token', 'client_secret' => Setting::get('instagram_client_secret'), 'access_token' => $accessToken, ]]); return json_decode((string) $response->getBody())->access_token; } public function redirectUri(): string { return env('INSTAGRAM_REDIRECT_URI', url()->current()); } public function me(string $accessToken): array { $response = $this->client()->get('/me', ['query' => [ 'access_token' => $accessToken, 'fields' => 'id,username', ]]); return json_decode((string) $response->getBody(), true); } public function clientId(): ?string { return Setting::get('instagram_client_id'); } public function posts(): Generator { $response = $this->client()->get('/me/media', ['query' => ['access_token' => $this->page->access_token, 'fields' => 'caption,id,media_url,permalink,timestamp']]); $posts = json_decode((string) $response->getBody(), true)['data']; foreach ($posts as $post) { if (!data_get($post, 'caption')) { continue; } yield [ 'message' => data_get($post, 'caption', ''), 'remote_id' => $post['id'], 'href' => $post['permalink'], 'created_at' => Carbon::parse($post['timestamp']), 'attachments' => [ [ 'type' => 'image', 'href' => $this->saveUrl($post['media_url']), 'remote_id' => $post['id'], ] ], ]; } } }