akaunting/app/Traits/SiteApi.php

67 lines
1.7 KiB
PHP
Raw Normal View History

2017-09-14 22:21:00 +03:00
<?php
namespace App\Traits;
use GuzzleHttp\Client;
2018-05-25 06:11:53 +03:00
use GuzzleHttp\Exception\RequestException;
2017-09-14 22:21:00 +03:00
trait SiteApi
{
2019-12-04 18:10:38 +03:00
public static $base_uri = 'https://api.akaunting.com/';
2017-09-14 22:21:00 +03:00
2019-12-04 18:10:38 +03:00
protected static function siteApiRequest($method, $path, $extra_data = [])
2017-09-14 22:21:00 +03:00
{
2019-12-04 18:10:38 +03:00
$client = new Client(['verify' => false, 'base_uri' => static::$base_uri]);
2017-09-14 22:21:00 +03:00
2019-11-16 10:21:14 +03:00
$headers['headers'] = [
'Authorization' => 'Bearer ' . setting('apps.api_key'),
2017-09-14 22:21:00 +03:00
'Accept' => 'application/json',
2019-12-18 15:29:59 +03:00
'Referer' => app()->runningInConsole() ? config('app.url') : url('/'),
2018-12-19 15:36:40 +03:00
'Akaunting' => version('short'),
2019-12-04 18:10:38 +03:00
'Language' => language()->getShortCode(),
2019-11-16 10:21:14 +03:00
];
2017-09-14 22:21:00 +03:00
2019-12-04 18:10:38 +03:00
$data = array_merge([
'timeout' => 30,
'referer' => true,
'http_errors' => false,
], $extra_data);
2017-10-17 16:56:53 +03:00
2019-12-04 18:10:38 +03:00
$options = array_merge($data, $headers);
2017-09-14 22:21:00 +03:00
2018-05-25 06:11:53 +03:00
try {
2019-12-04 18:10:38 +03:00
$response = $client->request($method, $path, $options);
2018-05-25 06:11:53 +03:00
} catch (RequestException $e) {
2019-12-04 18:10:38 +03:00
$response = $e;
}
return $response;
}
public static function getResponse($method, $path, $data = [])
{
$response = static::siteApiRequest($method, $path, $data);
if (!$response || ($response instanceof RequestException) || ($response->getStatusCode() != 200)) {
return false;
}
return $response;
}
public static function getResponseData($method, $path, $data = [])
{
if (!$response = static::getResponse($method, $path, $data)) {
return [];
}
$body = json_decode($response->getBody());
if (!is_object($body)) {
return [];
2018-05-25 06:11:53 +03:00
}
2017-09-14 22:21:00 +03:00
2019-12-04 18:10:38 +03:00
return $body->data;
2017-09-14 22:21:00 +03:00
}
2018-05-25 16:57:58 +03:00
}