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() { $response = $this->client()->get('/me/media', ['query' => ['access_token' => $this->page->access_token, 'fields' => 'caption,id,media_url,permalink,timestamp']]); return json_decode((string) $response->getBody(), true); } public function sync(): void { foreach ($this->posts()['data'] as $image) { $payload = [ 'message' => $image['caption'], 'remote_id' => $image['id'], 'href' => $image['permalink'], 'created_at' => Carbon::parse($image['timestamp']), ]; $existing = $this->page->posts()->where('remote_id', $image['id'])->first(); if ($existing) { $existing->update($payload); } else { $existing = $this->page->posts()->create($payload); } $existing->attachments()->updateOrCreate(['remote_id' => $image['id']], [ 'remote_id' => $image['id'], 'href' => $this->saveUrl($image['media_url']), 'type' => 'image', ]); } $this->cleanOutdated(); } }