oc-social-plugin/classes/InstagramService.php

114 lines
3.3 KiB
PHP
Raw Normal View History

2021-10-30 12:16:27 +02:00
<?php
namespace Zoomyboy\Social\Classes;
use Carbon\Carbon;
use Generator;
2021-10-30 12:16:27 +02:00
use GuzzleHttp\Client;
use Zoomyboy\Social\Models\Page;
use Zoomyboy\Social\Models\Setting;
class InstagramService extends SocialService {
public function getType(): string
{
return 'instagram';
}
public function refresh(Page $page): void
{
$response = $this->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);
}
2021-12-16 23:58:36 +01:00
public function clientId(): ?string
2021-10-30 12:16:27 +02:00
{
return Setting::get('instagram_client_id');
}
public function posts(): Generator
2021-10-30 12:16:27 +02:00
{
$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'],
]
],
2021-10-30 12:16:27 +02:00
];
}
}
}