-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
91 lines (80 loc) · 1.92 KB
/
api.php
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
<?php
/**
* API functions that connects and retrieve
* data from REMP CRM API
*
* @package WP REMP Connector
* @author Peter PayteR Gašparík
* @license MIT
* @copyright Copyright (c) 2020
* @version 0.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Get parsed data from api or null
*
* @param $url
* @param array $options
* @param string $method
* @return array|mixed|object|null
*/
function remp_api_data($url, $options = [], $method = 'GET') {
$client = remp_api_client($url, $options = [], $method = 'GET');
if(!$client) {
return null;
}
return json_decode((string) $client->getBody());
}
/**
* Will connect to the REMP API and return back Guzzle client object
*
* @param $url
* @param array $options
* @param string $method
* @return null|\Psr\Http\Message\ResponseInterface
*/
function remp_api_client($url, $options = [], $method = 'GET')
{
static $client;
try {
if(!$client) {
$client = new GuzzleHttp\Client(['base_uri' => remp_get_url()]);
}
if (!isset($options['headers']['Authorization'])) {
$options['headers']['Authorization'] = remp_api_get_bearer();
}
if(!$options['headers']['Authorization']) {
return null;
}
if (!isset($options['headers']['Content-Type'])) {
$options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
return $client->request($method, $url, $options);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
return null;
}
}
/**
* Retrieve formatted bearer string with token
*
* @return string|null
*/
function remp_api_get_bearer()
{
$token = remp_api_get_token();
if(!$token) {
return null;
}
return "Bearer " . $token;
}
/**
* Retrieve token from cookies
*
* @return string|null
*/
function remp_api_get_token()
{
return $_COOKIE[REMP_N_TOKEN] ?? null;
}